ipldutil.go 1.84 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
func Traverse(ctx context.Context, loader ipld.Loader, root ipld.Link, s selector.Selector, fn traversal.AdvVisitFn) error {
	builder := defaultChooser(root, ipld.LinkContext{})
	node, err := root.Load(ctx, ipld.LinkContext{}, builder, loader)
34 35 36
	if err != nil {
		return err
	}
37 38
	return traversal.Progress{
		Cfg: &traversal.Config{
39 40 41
			Ctx:                    ctx,
			LinkLoader:             loader,
			LinkNodeBuilderChooser: defaultChooser,
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) {
60
	reader := bytes.NewReader(encoded)
61
	return dagcbor.Decoder(free.NodeBuilder(), reader)
62 63
}

64
func ParseSelector(selector ipld.Node) (selector.Selector, error) {
65
	return ipldselector.ParseSelector(selector)
66
}