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

import (
4
	"context"
Jeromy's avatar
Jeromy committed
5

6 7
	mdag "github.com/ipfs/go-ipfs/merkledag"
	format "github.com/ipfs/go-ipfs/unixfs"
8
	cid "gx/ipfs/QmXUuRadqDq5BuFWzVU6VuKaSjTcNm1gNCtLvvP1TJCW4z/go-cid"
9 10 11 12 13 14 15
)

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

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

// 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.
Jeromy's avatar
Jeromy committed
32 33
func (d *directoryBuilder) AddChild(ctx context.Context, name string, c *cid.Cid) error {
	cnode, err := d.dserv.Get(ctx, c)
34 35 36 37
	if err != nil {
		return err
	}

38
	return d.dirnode.AddNodeLinkClean(name, cnode)
39 40
}

Henry's avatar
Henry committed
41
// GetNode returns the root of this directoryBuilder
42 43 44
func (d *directoryBuilder) GetNode() *mdag.Node {
	return d.dirnode
}