forked from ipfs/kubo
/
dag.go
80 lines (65 loc) · 2.1 KB
/
dag.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package coreapi
import (
"context"
"fmt"
"io"
gopath "path"
coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
caopts "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
coredag "github.com/ipfs/go-ipfs/core/coredag"
cid "gx/ipfs/QmYVNvtQkeZ6AKSwDrjQTs432QtL6umrrK41EBq3cu7iSP/go-cid"
ipld "gx/ipfs/QmZtNq8dArGfnpCZfx2pUNY7UcjGhVp5qqwQ4hH6mpTMRQ/go-ipld-format"
)
type DagAPI CoreAPI
// Put inserts data using specified format and input encoding. Unless used with
// `WithCodes` or `WithHash`, the defaults "dag-cbor" and "sha256" are used.
// Returns the path of the inserted data.
func (api *DagAPI) Put(ctx context.Context, src io.Reader, opts ...caopts.DagPutOption) (coreiface.ResolvedPath, error) {
settings, err := caopts.DagPutOptions(opts...)
if err != nil {
return nil, err
}
codec, ok := cid.CodecToStr[settings.Codec]
if !ok {
return nil, fmt.Errorf("invalid codec %d", settings.Codec)
}
nds, err := coredag.ParseInputs(settings.InputEnc, codec, src, settings.MhType, settings.MhLength)
if err != nil {
return nil, err
}
if len(nds) == 0 {
return nil, fmt.Errorf("no node returned from ParseInputs")
}
err = api.node.DAG.Add(ctx, nds[0])
if err != nil {
return nil, err
}
return coreiface.IpldPath(nds[0].Cid()), nil
}
// Get resolves `path` using Unixfs resolver, returns the resolved Node.
func (api *DagAPI) Get(ctx context.Context, path coreiface.Path) (ipld.Node, error) {
return api.core().ResolveNode(ctx, path)
}
// Tree returns list of paths within a node specified by the path `p`.
func (api *DagAPI) Tree(ctx context.Context, p coreiface.Path, opts ...caopts.DagTreeOption) ([]coreiface.Path, error) {
settings, err := caopts.DagTreeOptions(opts...)
if err != nil {
return nil, err
}
n, err := api.Get(ctx, p)
if err != nil {
return nil, err
}
paths := n.Tree("", settings.Depth)
out := make([]coreiface.Path, len(paths))
for n, p2 := range paths {
out[n], err = coreiface.ParsePath(gopath.Join(p.String(), p2))
if err != nil {
return nil, err
}
}
return out, nil
}
func (api *DagAPI) core() coreiface.CoreAPI {
return (*CoreAPI)(api)
}