ipldutil.go 1.9 KB
Newer Older
1
package ipldutil
2 3 4 5 6 7

import (
	"bytes"
	"context"

	ipld "github.com/ipld/go-ipld-prime"
8
	dagpb "github.com/ipld/go-ipld-prime-proto"
Hannah Howard's avatar
Hannah Howard committed
9 10
	"github.com/ipld/go-ipld-prime/codec/dagcbor"
	basicnode "github.com/ipld/go-ipld-prime/node/basic"
11
	"github.com/ipld/go-ipld-prime/traversal"
12
	ipldtraversal "github.com/ipld/go-ipld-prime/traversal"
13
	"github.com/ipld/go-ipld-prime/traversal/selector"
14 15 16
	ipldselector "github.com/ipld/go-ipld-prime/traversal/selector"
)

17
var (
Eric Myhre's avatar
Eric Myhre committed
18 19
	defaultChooser traversal.LinkTargetNodePrototypeChooser = dagpb.AddDagPBSupportToChooser(func(ipld.Link, ipld.LinkContext) (ipld.NodePrototype, error) {
		return basicnode.Prototype.Any, nil
20 21 22
	})
)

Eric Myhre's avatar
Eric Myhre committed
23
func Traverse(ctx context.Context, loader ipld.Loader, chooser traversal.LinkTargetNodePrototypeChooser, root ipld.Link, s selector.Selector, fn traversal.AdvVisitFn) error {
24 25 26
	if chooser == nil {
		chooser = defaultChooser
	}
Hannah Howard's avatar
Hannah Howard committed
27
	ns, err := chooser(root, ipld.LinkContext{})
28 29 30
	if err != nil {
		return err
	}
Hannah Howard's avatar
Hannah Howard committed
31 32
	nb := ns.NewBuilder()
	err = root.Load(ctx, ipld.LinkContext{}, nb, loader)
33 34 35
	if err != nil {
		return err
	}
Hannah Howard's avatar
Hannah Howard committed
36
	node := nb.Build()
37 38
	return traversal.Progress{
		Cfg: &traversal.Config{
Hannah Howard's avatar
Hannah Howard committed
39 40
			Ctx:                        ctx,
			LinkLoader:                 loader,
Eric Myhre's avatar
Eric Myhre committed
41
			LinkTargetNodePrototypeChooser: chooser,
42
		},
Edgar Lee's avatar
Edgar Lee committed
43
	}.WalkAdv(node, s, fn)
44 45
}

46
func WalkMatching(node ipld.Node, s selector.Selector, fn traversal.VisitFn) error {
47 48 49
	return ipldtraversal.WalkMatching(node, s, fn)
}

50
func EncodeNode(node ipld.Node) ([]byte, error) {
51
	var buffer bytes.Buffer
52
	err := dagcbor.Encoder(node, &buffer)
53 54 55 56 57 58
	if err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}

59
func DecodeNode(encoded []byte) (ipld.Node, error) {
Eric Myhre's avatar
Eric Myhre committed
60
	nb := basicnode.Prototype.Any.NewBuilder()
Hannah Howard's avatar
Hannah Howard committed
61 62 63 64
	if err := dagcbor.Decoder(nb, bytes.NewReader(encoded)); err != nil {
		return nil, err
	}
	return nb.Build(), nil
65 66
}

67
func ParseSelector(selector ipld.Node) (selector.Selector, error) {
68
	return ipldselector.ParseSelector(selector)
69
}