/
tree.go
49 lines (42 loc) · 1.1 KB
/
tree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package ipfs
import (
"context"
"github.com/ipfs/go-cid"
ipld "github.com/ipfs/go-ipld-format"
)
type IPLDTreeNode struct {
Cid cid.Cid
Path []string
Children []IPLDTreeNode
}
func getTreeNode(ctx context.Context, navNode ipld.NavigableNode, path []string) (IPLDTreeNode, error) {
var children []IPLDTreeNode
for i, link := range navNode.GetIPLDNode().Links() {
childNavNode, err := navNode.FetchChild(ctx, uint(i))
if err != nil {
return IPLDTreeNode{}, err
}
childTreeNode, err := getTreeNode(ctx, childNavNode, append(path, link.Name))
if err != nil {
return IPLDTreeNode{}, err
}
children = append(children, childTreeNode)
}
node := IPLDTreeNode{
Cid: navNode.GetIPLDNode().Cid(),
Path: path,
Children: children,
}
return node, nil
}
func FlattenTreeNode(ctx context.Context, rootNode IPLDTreeNode) ([]IPLDTreeNode, error) {
nodes := []IPLDTreeNode{rootNode}
for _, child := range rootNode.Children {
nodeChildren, err := FlattenTreeNode(ctx, child)
if err != nil {
return nil, err
}
nodes = append(nodes, nodeChildren...)
}
return nodes, nil
}