block.go 1.42 KB
Newer Older
1 2 3
package commands

import (
Henry's avatar
Henry committed
4
	"fmt"
5 6 7
	"io"
	"io/ioutil"
	"os"
Jeromy's avatar
Jeromy committed
8 9
	"time"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
11

Henry's avatar
Henry committed
12
	mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
13 14 15 16 17
	"github.com/jbenet/go-ipfs/blocks"
	"github.com/jbenet/go-ipfs/core"
	u "github.com/jbenet/go-ipfs/util"
)

Henry's avatar
Henry committed
18
// BlockGet retrives a raw ipfs block from the node's BlockService
19 20
func BlockGet(n *core.IpfsNode, args []string, opts map[string]interface{}, out io.Writer) error {

Henry's avatar
Henry committed
21 22 23 24 25 26 27 28 29 30
	if !u.IsValidHash(args[0]) {
		return fmt.Errorf("block get: not a valid hash")
	}

	h, err := mh.FromB58String(args[0])
	if err != nil {
		return fmt.Errorf("block get: %v", err)
	}

	k := u.Key(h)
31
	log.Debugf("BlockGet key: '%q'", k)
Jeromy's avatar
Jeromy committed
32 33
	ctx, _ := context.WithTimeout(context.TODO(), time.Second*5)
	b, err := n.Blocks.GetBlock(ctx, k)
34
	if err != nil {
Henry's avatar
Henry committed
35
		return fmt.Errorf("block get: %v", err)
36 37
	}

Henry's avatar
Henry committed
38 39
	_, err = out.Write(b.Data)
	return err
40 41
}

Henry's avatar
Henry committed
42
// BlockPut reads everything from conn and saves the data to the nodes BlockService
43
func BlockPut(n *core.IpfsNode, args []string, opts map[string]interface{}, out io.Writer) error {
44
	// TODO: this should read from an io.Reader arg
45 46 47 48 49 50
	data, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return err
	}

	b := blocks.NewBlock(data)
51
	log.Debugf("BlockPut key: '%q'", b.Key())
52

Henry's avatar
Henry committed
53 54 55 56 57
	k, err := n.Blocks.AddBlock(b)
	if err != nil {
		return err
	}
	fmt.Fprintf(out, "added as '%s'\n", k)
58

Henry's avatar
Henry committed
59
	return nil
60
}