importer.go 2.04 KB
Newer Older
1 2
// package importer implements utilities used to create ipfs DAGs from files
// and readers
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
3 4 5 6 7
package importer

import (
	"fmt"
	"io"
8
	"os"
9

10 11 12 13 14 15
	bal "github.com/ipfs/go-ipfs/importer/balanced"
	"github.com/ipfs/go-ipfs/importer/chunk"
	h "github.com/ipfs/go-ipfs/importer/helpers"
	trickle "github.com/ipfs/go-ipfs/importer/trickle"
	dag "github.com/ipfs/go-ipfs/merkledag"
	"github.com/ipfs/go-ipfs/pin"
16
	u "github.com/ipfs/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18
)

19
var log = u.Logger("importer")
20

Jeromy's avatar
Jeromy committed
21 22 23
// Builds a DAG from the given file, writing created blocks to disk as they are
// created
func BuildDagFromFile(fpath string, ds dag.DAGService, mp pin.ManualPinner) (*dag.Node, error) {
24 25 26 27 28 29
	stat, err := os.Stat(fpath)
	if err != nil {
		return nil, err
	}

	if stat.IsDir() {
30
		return nil, fmt.Errorf("`%s` is a directory", fpath)
31 32 33 34 35 36 37 38
	}

	f, err := os.Open(fpath)
	if err != nil {
		return nil, err
	}
	defer f.Close()

39
	return BuildDagFromReader(f, ds, chunk.DefaultSplitter, BasicPinnerCB(mp))
40
}
41

42
func BuildDagFromReader(r io.Reader, ds dag.DAGService, spl chunk.BlockSplitter, ncb h.NodeCB) (*dag.Node, error) {
Jeromy's avatar
Jeromy committed
43 44 45
	// Start the splitter
	blkch := spl.Split(r)

46 47 48
	dbp := h.DagBuilderParams{
		Dagserv:  ds,
		Maxlinks: h.DefaultLinksPerBlock,
49
		NodeCB:   ncb,
Jeromy's avatar
Jeromy committed
50 51
	}

52
	return bal.BalancedLayout(dbp.New(blkch))
Jeromy's avatar
Jeromy committed
53 54
}

55
func BuildTrickleDagFromReader(r io.Reader, ds dag.DAGService, spl chunk.BlockSplitter, ncb h.NodeCB) (*dag.Node, error) {
56 57
	// Start the splitter
	blkch := spl.Split(r)
Jeromy's avatar
Jeromy committed
58

59 60 61
	dbp := h.DagBuilderParams{
		Dagserv:  ds,
		Maxlinks: h.DefaultLinksPerBlock,
62
		NodeCB:   ncb,
Jeromy's avatar
Jeromy committed
63 64
	}

65
	return trickle.TrickleLayout(dbp.New(blkch))
66
}
67

68
func BasicPinnerCB(p pin.ManualPinner) h.NodeCB {
Jeromy's avatar
Jeromy committed
69
	return func(n *dag.Node, last bool) error {
70 71 72 73 74
		k, err := n.Key()
		if err != nil {
			return err
		}

Jeromy's avatar
Jeromy committed
75
		if last {
76 77 78 79 80 81 82 83 84
			p.PinWithMode(k, pin.Recursive)
			return p.Flush()
		} else {
			p.PinWithMode(k, pin.Indirect)
			return nil
		}
	}
}

85
func PinIndirectCB(p pin.ManualPinner) h.NodeCB {
Jeromy's avatar
Jeromy committed
86
	return func(n *dag.Node, last bool) error {
87 88 89 90 91
		k, err := n.Key()
		if err != nil {
			return err
		}

92 93 94 95
		p.PinWithMode(k, pin.Indirect)
		return nil
	}
}