diff options
| author | Shulhan <ms@kilabit.info> | 2022-04-05 23:17:15 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2022-04-06 00:12:43 +0700 |
| commit | ebb376744ff75473a5d8dd967581ffeb39d0a3ea (patch) | |
| tree | faf2cd3af4b077fd89fa4f6f1cf5961f9cfdc97f | |
| parent | 4433c73f2cb68c812522c946304a76ecb3c46d70 (diff) | |
| download | pakakeh.go-ebb376744ff75473a5d8dd967581ffeb39d0a3ea.tar.xz | |
lib/memfs: make the Node's addChild to be idempotent
If the same Node's Path already exists on the Childs, adding another
Node with same Path should not add the Node to the Childs.
| -rw-r--r-- | lib/memfs/node.go | 23 |
1 files changed, 20 insertions, 3 deletions
diff --git a/lib/memfs/node.go b/lib/memfs/node.go index d8b67013..72b62731 100644 --- a/lib/memfs/node.go +++ b/lib/memfs/node.go @@ -340,20 +340,37 @@ func (node *Node) Sys() interface{} { } // -// addChild add new node as sub-directory or file of this node. +// addChild add FileInfo fi as child of this node. +// This method is idempotent, which means, calling addChild with the same +// FileInfo will return the same Node. // func (node *Node) addChild( sysPath string, fi os.FileInfo, maxFileSize int64, ) (child *Node, err error) { + var ( + logp = "Node.addChild" + relPath = path.Join(node.Path, fi.Name()) + found bool + ) + + for _, child = range node.Childs { + if child.Path == relPath { + found = true + break + } + } + if found { + return child, nil + } + child, err = NewNode(node, fi, maxFileSize) if err != nil { - return nil, fmt.Errorf("addChild: %w", err) + return nil, fmt.Errorf("%s: %w", logp, err) } child.SysPath = sysPath node.Childs = append(node.Childs, child) - return child, nil } |
