get without content

This commit is contained in:
Bel LaPointe
2022-02-09 11:34:18 -07:00
parent eedb6cc6a5
commit 4a9ecd820a
2 changed files with 111 additions and 5 deletions

View File

@@ -17,6 +17,18 @@ func (branch Branch) IsZero() bool {
return branch.Leaf == (Leaf{}) && len(branch.Branches) == 0
}
func (branch Branch) Find(baseId string) ([]string, bool) {
if _, ok := branch.Branches[baseId]; ok {
return []string{baseId}, true
}
for pid, child := range branch.Branches {
if subids, ok := child.Find(baseId); ok {
return append([]string{pid}, subids...), true
}
}
return nil, false
}
type Leaf struct {
Title string
Deleted bool
@@ -46,18 +58,30 @@ func (tree Tree) WithRoot(root string) Tree {
return tree
}
func (tree Tree) Find(baseId string) ([]string, bool) {
root, err := tree.GetRoot()
if err != nil {
return nil, false
}
return root.Find(baseId)
}
func (tree Tree) GetRootMeta() (Branch, error) {
return tree.getRoot(false)
}
func (tree Tree) GetRoot() (Branch, error) {
if !tree.cachedRoot.IsZero() {
return tree.cachedRoot, nil
}
got, err := tree.getRoot()
got, err := tree.getRoot(true)
if err == nil {
tree.cachedRoot = got
}
return got, err
}
func (tree Tree) getRoot() (Branch, error) {
func (tree Tree) getRoot(withContent bool) (Branch, error) {
m := Branch{Branches: map[string]Branch{}}
entries, err := os.ReadDir(tree.root)
if os.IsNotExist(err) {
@@ -73,8 +97,11 @@ func (tree Tree) getRoot() (Branch, error) {
} else if err := yaml.Unmarshal(b, &m.Leaf); err != nil {
return Branch{}, err
}
if !withContent {
m.Leaf.Content = ""
}
} else if entry.IsDir() {
if branch, err := tree.WithRoot(path.Join(tree.root, entry.Name())).getRoot(); err != nil {
if branch, err := tree.WithRoot(path.Join(tree.root, entry.Name())).getRoot(withContent); err != nil {
return Branch{}, err
} else {
m.Branches[entry.Name()] = branch
@@ -110,11 +137,16 @@ func (tree Tree) Put(id []string, input Leaf) error {
if err != nil {
return err
}
return ensureAndWrite(tree.toData(id), b)
if err := ensureAndWrite(tree.toData(id), b); err != nil {
return err
}
tree.cachedRoot = Branch{}
return nil
}
func (tree Tree) Del(id []string) error {
os.RemoveAll(tree.toDir(id))
tree.cachedRoot = Branch{}
return nil
}