package main import ( "errors" "io/ioutil" "os" "time" yaml "gopkg.in/yaml.v2" ) type Tree struct { path string } type Branch struct { Title string Deleted bool Updated time.Time PID string } func NewTree(path string) *Tree { return &Tree{ path: path, } } func (tree *Tree) Get() (map[string]Branch, error) { b, err := ioutil.ReadFile(tree.path) if os.IsNotExist(err) { return map[string]Branch{}, nil } if err != nil { return nil, err } var m map[string]Branch err = yaml.Unmarshal(b, &m) return m, err } func (tree *Tree) Set(m map[string]Branch) error { b, err := yaml.Marshal(m) if err != nil { return err } return ioutil.WriteFile(tree.path, b, os.ModePerm) } func (tree *Tree) Del(id string) error { m, err := tree.Get() if err != nil { return err } branch, ok := m[id] if !ok { return nil } branch.Updated = time.Now().UTC() branch.Deleted = true m[id] = branch return tree.Set(m) } func (tree *Tree) Put(id string, branch Branch) error { branch.Updated = time.Now().UTC() if branch.Title == "" { branch.Title = "Untitled (" + time.Now().UTC().String() + ")" } m, err := tree.Get() if err != nil { return err } if _, ok := m[branch.PID]; !ok && branch.PID != "" { return errors.New("PID does not exist") } m[id] = branch return tree.Set(m) }