dag.go 1.76 KB
Newer Older
Łukasz Magiera's avatar
Łukasz Magiera committed
1 2 3 4 5 6 7 8 9 10
package coreapi

import (
	"context"
	"fmt"
	"io"

	gopath "path"

	coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
11
	caopts "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
Łukasz Magiera's avatar
Łukasz Magiera committed
12 13
	coredag "github.com/ipfs/go-ipfs/core/coredag"

Łukasz Magiera's avatar
Łukasz Magiera committed
14
	cid "gx/ipfs/QmeSrf6pzut73u6zLQkRFQ3ygt3k6XFT2kjdYP8Tnkwwyg/go-cid"
Łukasz Magiera's avatar
Łukasz Magiera committed
15 16
)

17 18 19 20
type DagAPI struct {
	*CoreAPI
	*caopts.DagOptions
}
Łukasz Magiera's avatar
Łukasz Magiera committed
21

22 23 24 25
func (api *DagAPI) Put(ctx context.Context, src io.Reader, opts ...caopts.DagPutOption) ([]coreiface.Node, error) {
	settings, err := caopts.DagPutOptions(opts...)
	if err != nil {
		return nil, err
Łukasz Magiera's avatar
Łukasz Magiera committed
26 27
	}

28
	codec, ok := cid.CodecToStr[settings.Codec]
Łukasz Magiera's avatar
Łukasz Magiera committed
29
	if !ok {
30
		return nil, fmt.Errorf("invalid codec %d", settings.Codec)
Łukasz Magiera's avatar
Łukasz Magiera committed
31 32
	}

33
	nds, err := coredag.ParseInputs(settings.InputEnc, codec, src, settings.MhType, settings.MhLength)
Łukasz Magiera's avatar
Łukasz Magiera committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	if err != nil {
		return nil, err
	}
	if len(nds) == 0 {
		return nil, fmt.Errorf("no node returned from ParseInputs")
	}

	out := make([]coreiface.Node, len(nds))
	for n, nd := range nds {
		_, err := api.node.DAG.Add(nd)
		if err != nil {
			return nil, err
		}
		out[n] = nd
	}

	return out, nil
}

53
func (api *DagAPI) Get(ctx context.Context, path coreiface.Path) (coreiface.Node, error) {
Łukasz Magiera's avatar
Łukasz Magiera committed
54 55 56
	return api.core().ResolveNode(ctx, path)
}

57 58 59 60 61 62
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
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
63 64 65 66
	n, err := api.Get(ctx, p)
	if err != nil {
		return nil, err
	}
67
	paths := n.Tree("", settings.Depth)
Łukasz Magiera's avatar
Łukasz Magiera committed
68 69 70 71 72 73 74 75 76 77 78
	out := make([]coreiface.Path, len(paths))
	for n, p2 := range paths {
		out[n], err = ParsePath(gopath.Join(p.String(), p2))
		if err != nil {
			return nil, err
		}
	}

	return out, nil
}

79 80
func (api *DagAPI) core() coreiface.CoreAPI {
	return api.CoreAPI
Łukasz Magiera's avatar
Łukasz Magiera committed
81
}