restic/snapshot.go

81 lines
1.3 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"`
Tree ID `json:"tree"`
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) {
2014-08-04 18:47:04 +00:00
if sn.Tree == nil {
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
}
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
}