ipldutil.go 1.96 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
var (
26 27
	defaultChooser traversal.NodeBuilderChooser = dagpb.AddDagPBSupportToChooser(func(ipld.Link, ipld.LinkContext) (ipld.NodeBuilder, error) {
		return free.NodeBuilder(), nil
28 29 30
	})
)

31 32 33 34
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
	}
35 36 37 38
	builder, err := chooser(root, ipld.LinkContext{})
	if err != nil {
		return err
	}
39
	node, err := root.Load(ctx, ipld.LinkContext{}, builder, loader)
40 41 42
	if err != nil {
		return err
	}
43 44
	return traversal.Progress{
		Cfg: &traversal.Config{
45 46
			Ctx:                    ctx,
			LinkLoader:             loader,
47
			LinkNodeBuilderChooser: chooser,
48
		},
Edgar Lee's avatar
Edgar Lee committed
49
	}.WalkAdv(node, s, fn)
50 51
}

52
func WalkMatching(node ipld.Node, s selector.Selector, fn traversal.VisitFn) error {
53 54 55
	return ipldtraversal.WalkMatching(node, s, fn)
}

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

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

70
func ParseSelector(selector ipld.Node) (selector.Selector, error) {
71
	return ipldselector.ParseSelector(selector)
72
}