ipldutil.go 1.91 KB
Newer Older
1
package ipldutil
2 3 4 5

import (
	"bytes"
	"context"
6
	"errors"
7 8

	ipld "github.com/ipld/go-ipld-prime"
9
	dagpb "github.com/ipld/go-ipld-prime-proto"
10 11
	"github.com/ipld/go-ipld-prime/encoding/dagcbor"
	free "github.com/ipld/go-ipld-prime/impl/free"
12
	"github.com/ipld/go-ipld-prime/traversal"
13
	ipldtraversal "github.com/ipld/go-ipld-prime/traversal"
14
	"github.com/ipld/go-ipld-prime/traversal/selector"
15 16 17
	ipldselector "github.com/ipld/go-ipld-prime/traversal/selector"
)

18
var errDoNotFollow = errors.New("Dont Follow Me")
19

20 21 22
// ErrDoNotFollow is just a wrapper for whatever IPLD's ErrDoNotFollow ends up looking like
func ErrDoNotFollow() error {
	return errDoNotFollow
23 24
}

25 26 27 28 29 30
var (
	defaultChooser traversal.NodeBuilderChooser = dagpb.AddDagPBSupportToChooser(func(ipld.Link, ipld.LinkContext) ipld.NodeBuilder {
		return free.NodeBuilder()
	})
)

31 32 33 34 35
func Traverse(ctx context.Context, loader ipld.Loader, chooser traversal.NodeBuilderChooser, root ipld.Link, s selector.Selector, fn traversal.AdvVisitFn) error {
	if chooser == nil {
		chooser = defaultChooser
	}
	builder := chooser(root, ipld.LinkContext{})
36
	node, err := root.Load(ctx, ipld.LinkContext{}, builder, loader)
37 38 39
	if err != nil {
		return err
	}
40 41
	return traversal.Progress{
		Cfg: &traversal.Config{
42 43
			Ctx:                    ctx,
			LinkLoader:             loader,
44
			LinkNodeBuilderChooser: chooser,
45
		},
Edgar Lee's avatar
Edgar Lee committed
46
	}.WalkAdv(node, s, fn)
47 48
}

49
func WalkMatching(node ipld.Node, s selector.Selector, fn traversal.VisitFn) error {
50 51 52
	return ipldtraversal.WalkMatching(node, s, fn)
}

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

62
func DecodeNode(encoded []byte) (ipld.Node, error) {
63
	reader := bytes.NewReader(encoded)
64
	return dagcbor.Decoder(free.NodeBuilder(), reader)
65 66
}

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