github.com/zignig/go-ipfs@v0.0.0-20141111235910-c9e5fdf55a52/core/commands/block.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"io/ioutil"
     7  	"os"
     8  	"time"
     9  
    10  	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
    11  
    12  	mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
    13  	"github.com/jbenet/go-ipfs/blocks"
    14  	"github.com/jbenet/go-ipfs/core"
    15  	u "github.com/jbenet/go-ipfs/util"
    16  )
    17  
    18  // BlockGet retrives a raw ipfs block from the node's BlockService
    19  func BlockGet(n *core.IpfsNode, args []string, opts map[string]interface{}, out io.Writer) error {
    20  
    21  	if !u.IsValidHash(args[0]) {
    22  		return fmt.Errorf("block get: not a valid hash")
    23  	}
    24  
    25  	h, err := mh.FromB58String(args[0])
    26  	if err != nil {
    27  		return fmt.Errorf("block get: %v", err)
    28  	}
    29  
    30  	k := u.Key(h)
    31  	log.Debugf("BlockGet key: '%q'", k)
    32  	ctx, _ := context.WithTimeout(context.TODO(), time.Second*5)
    33  	b, err := n.Blocks.GetBlock(ctx, k)
    34  	if err != nil {
    35  		return fmt.Errorf("block get: %v", err)
    36  	}
    37  
    38  	_, err = out.Write(b.Data)
    39  	return err
    40  }
    41  
    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  	data, err := ioutil.ReadAll(os.Stdin)
    46  	if err != nil {
    47  		return err
    48  	}
    49  
    50  	b := blocks.NewBlock(data)
    51  	log.Debugf("BlockPut key: '%q'", b.Key())
    52  
    53  	k, err := n.Blocks.AddBlock(b)
    54  	if err != nil {
    55  		return err
    56  	}
    57  	fmt.Fprintf(out, "added as '%s'\n", k)
    58  
    59  	return nil
    60  }