pin.go 2.37 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
package commands

import (
	"errors"
	"fmt"

	cmds "github.com/jbenet/go-ipfs/commands"
)

var pinCmd = &cmds.Command{
	Options: []cmds.Option{
		cmds.Option{[]string{"recursive", "r"}, cmds.Bool},
		cmds.Option{[]string{"depth", "d"}, cmds.Uint},
	},
	Arguments: []cmds.Argument{
		cmds.Argument{"object", cmds.ArgString, true, true},
	},
	Run: func(res cmds.Response, req cmds.Request) {
		n := req.Context().Node

		// set recursive flag
		opt, _ := req.Option("recursive")
		recursive, _ := opt.(bool) // false if cast fails.

		/*depth := 1 // default (non recursive)

		// if recursive, set depth flag
		if recursive {
			opt, found := req.Option("depth")
			if d, ok := opt.(int); found && ok {
				depth = d
			} else {
				res.SetError(errors.New("cast error"), cmds.ErrNormal)
				return
			}
		}*/

		for _, arg := range req.Arguments() {
			path, ok := arg.(string)
			if !ok {
				res.SetError(errors.New("cast error"), cmds.ErrNormal)
				return
			}

			dagnode, err := n.Resolver.ResolvePath(path)
			if err != nil {
				res.SetError(fmt.Errorf("pin error: %v", err), cmds.ErrNormal)
				return
			}

			err = n.Pinning.Pin(dagnode, recursive)
			if err != nil {
				res.SetError(fmt.Errorf("pin: %v", err), cmds.ErrNormal)
				return
			}
		}

		err := n.Pinning.Flush()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
		}

		// TODO: create some output to show what got pinned
	},
}

var unpinCmd = &cmds.Command{
	Options: []cmds.Option{
		cmds.Option{[]string{"recursive", "r"}, cmds.Bool},
	},
	Arguments: []cmds.Argument{
		cmds.Argument{"object", cmds.ArgString, true, true},
	},
	Run: func(res cmds.Response, req cmds.Request) {
		n := req.Context().Node

		// set recursive flag
		opt, _ := req.Option("recursive")
		recursive, _ := opt.(bool) // false if cast fails.

		for _, arg := range req.Arguments() {
			path, ok := arg.(string)
			if !ok {
				res.SetError(errors.New("cast error"), cmds.ErrNormal)
				return
			}

			dagnode, err := n.Resolver.ResolvePath(path)
			if err != nil {
				res.SetError(fmt.Errorf("pin error: %v", err), cmds.ErrNormal)
				return
			}

			k, _ := dagnode.Key()
			err = n.Pinning.Unpin(k, recursive)
			if err != nil {
				res.SetError(fmt.Errorf("pin: %v", err), cmds.ErrNormal)
				return
			}
		}

		err := n.Pinning.Flush()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
		}

		// TODO: create some output to show what got unpinned
	},
}