restic/snapshot.go

83 lines
1.4 KiB
Go
Raw Normal View History

2014-08-04 18:47:04 +00:00
package khepri
import (
"encoding/json"
"os"
"os/user"
"time"
)
type Snapshot struct {
Time time.Time `json:"time"`
TreeID ID `json:"tree"`
2014-08-04 18:47:04 +00:00
Dir string `json:"dir"`
Hostname string `json:"hostname,omitempty"`
Username string `json:"username,omitempty"`
UID string `json:"uid,omitempty"`
GID string `json:"gid,omitempty"`
}
2014-08-04 20:46:14 +00:00
func NewSnapshot(dir string) *Snapshot {
2014-08-04 18:47:04 +00:00
sn := &Snapshot{
Dir: dir,
Time: time.Now(),
}
hn, err := os.Hostname()
if err == nil {
sn.Hostname = hn
}
usr, err := user.Current()
if err == nil {
sn.Username = usr.Username
sn.UID = usr.Uid
sn.GID = usr.Gid
}
return sn
}
2014-08-04 20:46:14 +00:00
func (sn *Snapshot) Save(repo *Repository) (ID, error) {
if sn.TreeID == nil {
2014-08-04 18:47:04 +00:00
panic("Snapshot.Save() called with nil tree id")
}
2014-08-04 20:46:14 +00:00
obj, id_ch, err := repo.Create(TYPE_REF)
2014-08-04 18:47:04 +00:00
if err != nil {
2014-08-04 20:46:14 +00:00
return nil, err
2014-08-04 18:47:04 +00:00
}
enc := json.NewEncoder(obj)
err = enc.Encode(sn)
if err != nil {
2014-08-04 20:46:14 +00:00
return nil, err
2014-08-04 18:47:04 +00:00
}
err = obj.Close()
if err != nil {
2014-08-04 20:46:14 +00:00
return nil, err
2014-08-04 18:47:04 +00:00
}
2014-08-04 20:46:14 +00:00
return <-id_ch, nil
2014-08-04 18:47:04 +00:00
}
2014-08-04 20:46:14 +00:00
func LoadSnapshot(repo *Repository, id ID) (*Snapshot, error) {
rd, err := repo.Get(TYPE_REF, id)
if err != nil {
return nil, err
}
2014-08-04 21:25:58 +00:00
// TODO: maybe inject a hashing reader here and test if the given id is correct
2014-08-04 20:46:14 +00:00
dec := json.NewDecoder(rd)
sn := &Snapshot{}
err = dec.Decode(sn)
if err != nil {
return nil, err
}
return sn, nil
2014-08-04 18:47:04 +00:00
}