grr cached root doesnt matter because server.tree called each time

master
Bel LaPointe 2022-02-16 15:47:35 -07:00
parent 2781114863
commit b076b6a9cf
1 changed files with 20 additions and 14 deletions

View File

@ -1,8 +1,8 @@
package main package main
import ( import (
"io"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"path" "path"
@ -55,6 +55,7 @@ func (base Leaf) Merge(updated Leaf) Leaf {
type Tree struct { type Tree struct {
root string root string
cachedRoot Branch cachedRoot Branch
cachedMetaRoot Branch
} }
func NewTree(root string) Tree { func NewTree(root string) Tree {
@ -64,11 +65,19 @@ func NewTree(root string) Tree {
func (tree Tree) WithRoot(root string) Tree { func (tree Tree) WithRoot(root string) Tree {
tree.root = root tree.root = root
tree.cachedRoot = Branch{} tree.cachedRoot = Branch{}
tree.cachedMetaRoot = Branch{}
return tree return tree
} }
func (tree Tree) GetRootMeta() (Branch, error) { func (tree Tree) GetRootMeta() (Branch, error) {
return tree.getRoot(NewID(""), false, false) if !tree.cachedMetaRoot.IsZero() {
return tree.cachedMetaRoot, nil
}
got, err := tree.getRoot(NewID(""), false, false)
if err == nil {
tree.cachedMetaRoot = got
}
return got, err
} }
func (tree Tree) GetRoot() (Branch, error) { func (tree Tree) GetRoot() (Branch, error) {
@ -93,7 +102,8 @@ func (tree Tree) getRoot(pid ID, withContent, withDeleted bool) (Branch, error)
} }
for _, entry := range entries { for _, entry := range entries {
if entry.Name() == "data.yaml" { if entry.Name() == "data.yaml" {
if b, err := peekFile(withContent, path.Join(tree.root, entry.Name())); err != nil { log.Printf("reading %s", tree.root)
if b, err := peekLeaf(withContent, path.Join(tree.root, entry.Name())); err != nil {
return Branch{}, err return Branch{}, err
} else if err := yaml.Unmarshal(b, &m.Leaf); err != nil { } else if err := yaml.Unmarshal(b, &m.Leaf); err != nil {
return Branch{}, err return Branch{}, err
@ -116,17 +126,11 @@ func (tree Tree) getRoot(pid ID, withContent, withDeleted bool) (Branch, error)
return m, nil return m, nil
} }
func peekFile(all bool, path string) ([]byte, error) { func peekLeaf(all bool, path string) ([]byte, error) {
if !all { if all {
return ioutil.ReadFile(path) return ioutil.ReadFile(path)
} }
f, err := os.Open(path) return ioutil.ReadFile(path)
if err != nil {
return nil, err
}
defer f.Close()
r := io.LimitReader(f, 1024)
return ioutil.ReadAll(r)
} }
func (tree Tree) toDir(id ID) string { func (tree Tree) toDir(id ID) string {
@ -159,6 +163,7 @@ func (tree Tree) Put(id ID, input Leaf) error {
return err return err
} }
tree.cachedRoot = Branch{} tree.cachedRoot = Branch{}
tree.cachedMetaRoot = Branch{}
return nil return nil
} }
@ -180,6 +185,7 @@ func (tree Tree) Del(id ID) error {
func (tree Tree) HardDel(id ID) error { func (tree Tree) HardDel(id ID) error {
os.RemoveAll(tree.toDir(id)) os.RemoveAll(tree.toDir(id))
tree.cachedRoot = Branch{} tree.cachedRoot = Branch{}
tree.cachedMetaRoot = Branch{}
return nil return nil
} }