dirbuilder.go 1.22 KB
Newer Older
1 2 3
package io

import (
Jeromy's avatar
Jeromy committed
4 5 6 7
	"time"

	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"

8 9 10
	mdag "github.com/ipfs/go-ipfs/merkledag"
	format "github.com/ipfs/go-ipfs/unixfs"
	u "github.com/ipfs/go-ipfs/util"
11 12 13 14 15 16 17
)

type directoryBuilder struct {
	dserv   mdag.DAGService
	dirnode *mdag.Node
}

Henry's avatar
Henry committed
18 19 20 21 22 23
// NewEmptyDirectory returns an empty merkledag Node with a folder Data chunk
func NewEmptyDirectory() *mdag.Node {
	return &mdag.Node{Data: format.FolderPBData()}
}

// NewDirectory returns a directoryBuilder. It needs a DAGService to add the Children
24 25 26
func NewDirectory(dserv mdag.DAGService) *directoryBuilder {
	db := new(directoryBuilder)
	db.dserv = dserv
Henry's avatar
Henry committed
27
	db.dirnode = NewEmptyDirectory()
28 29 30
	return db
}

Henry's avatar
Henry committed
31
// AddChild adds a (name, key)-pair to the root node.
32
func (d *directoryBuilder) AddChild(name string, k u.Key) error {
Henry's avatar
Henry committed
33
	// TODO(cryptix): consolidate context managment
Jeromy's avatar
Jeromy committed
34 35 36 37
	ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
	defer cancel()

	cnode, err := d.dserv.Get(ctx, k)
38 39 40 41 42 43 44 45 46 47 48 49
	if err != nil {
		return err
	}

	err = d.dirnode.AddNodeLinkClean(name, cnode)
	if err != nil {
		return err
	}

	return nil
}

Henry's avatar
Henry committed
50
// GetNode returns the root of this directoryBuilder
51 52 53
func (d *directoryBuilder) GetNode() *mdag.Node {
	return d.dirnode
}