dag.go 6.42 KB
Newer Older
1 2 3
package dagcmd

import (
Łukasz Magiera's avatar
Łukasz Magiera committed
4
	"bytes"
5 6
	"fmt"
	"io"
7
	"math"
8 9 10
	"strings"

	cmds "github.com/ipfs/go-ipfs/commands"
11
	files "github.com/ipfs/go-ipfs/commands/files"
12
	coredag "github.com/ipfs/go-ipfs/core/coredag"
13
	path "github.com/ipfs/go-ipfs/path"
14
	pin "github.com/ipfs/go-ipfs/pin"
15

16
	cid "gx/ipfs/QmNp85zy9RLrQ5oQD4hPyS39ezrrXpcaa7R4Y9kxdWQLLQ/go-cid"
17
	u "gx/ipfs/QmSU6eubNdhXjFBJBSksTp8kv8YRub8mGAPv8tVJHmL2EU/go-ipfs-util"
18
	mh "gx/ipfs/QmU9a9NV9RdPNwZQDYd5uKsm6N6LJLSvLbywDDYFbaaC6P/go-multihash"
19
	"reflect"
20 21 22 23
)

var DagCmd = &cmds.Command{
	Helptext: cmds.HelpText{
Jeromy's avatar
Jeromy committed
24 25 26 27 28 29 30
		Tagline: "Interact with ipld dag objects.",
		ShortDescription: `
'ipfs dag' is used for creating and manipulating dag objects.

This subcommand is currently an experimental feature, but it is intended
to deprecate and replace the existing 'ipfs object' command moving forward.
		`,
31 32
	},
	Subcommands: map[string]*cmds.Command{
Łukasz Magiera's avatar
Łukasz Magiera committed
33 34 35
		"put":     DagPutCmd,
		"get":     DagGetCmd,
		"resolve": DagResolveCmd,
36 37 38
	},
}

Łukasz Magiera's avatar
Łukasz Magiera committed
39
// OutputObject is the output type of 'dag put' command
40 41 42 43
type OutputObject struct {
	Cid *cid.Cid
}

Łukasz Magiera's avatar
Łukasz Magiera committed
44
// ResolveOutput is the output type of 'dag resolve' command
Łukasz Magiera's avatar
Łukasz Magiera committed
45 46 47 48 49
type ResolveOutput struct {
	Cid     *cid.Cid
	RemPath string
}

50 51 52
var DagPutCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Add a dag node to ipfs.",
Jeromy's avatar
Jeromy committed
53 54 55 56
		ShortDescription: `
'ipfs dag put' accepts input from a file or stdin and parses it
into an object of the specified format.
`,
57 58
	},
	Arguments: []cmds.Argument{
59
		cmds.FileArg("object data", true, true, "The object to put").EnableStdin(),
60 61
	},
	Options: []cmds.Option{
62 63
		cmds.StringOption("format", "f", "Format that the object will be added as.").Default("cbor"),
		cmds.StringOption("input-enc", "Format that the input object will be.").Default("json"),
64
		cmds.BoolOption("pin", "Pin this object when adding.").Default(false),
65
		cmds.StringOption("hash", "Hash function to use").Default(""),
66 67 68 69 70 71 72 73 74 75
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		ienc, _, _ := req.Option("input-enc").String()
		format, _, _ := req.Option("format").String()
76
		hash, _, err := req.Option("hash").String()
77 78 79 80 81
		dopin, _, err := req.Option("pin").Bool()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
82

83 84 85 86 87 88 89 90 91 92 93 94 95
		// mhType tells inputParser which hash should be used. MaxUint64 means 'use
		// default hash' (sha256 for cbor, sha1 for git..)
		mhType := uint64(math.MaxUint64)

		if hash != "" {
			var ok bool
			mhType, ok = mh.Names[hash]
			if !ok {
				res.SetError(fmt.Errorf("%s in not a valid multihash name", hash), cmds.ErrNormal)
				return
			}
		}

96 97 98 99
		if dopin {
			defer n.Blockstore.PinLock().Unlock()
		}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
		outChan := make(chan interface{}, 8)
		res.SetOutput((<-chan interface{})(outChan))

		addAllAndPin := func(f files.File) error {
			for {
				file, err := f.NextFile()
				if err == io.EOF {
					// Finished the list of files.
					break
				} else if err != nil {
					return err
				}

				nds, err := coredag.ParseInputs(ienc, format, file, mhType, -1)
				if err != nil {
					return err
				}
				if len(nds) == 0 {
					return fmt.Errorf("no node returned from ParseInputs")
				}

				b := n.DAG.Batch()
				for _, nd := range nds {
					_, err := b.Add(nd)
					if err != nil {
						return err
					}
				}

				if err := b.Commit(); err != nil {
					return err
				}

				root := nds[0].Cid()
				if dopin {
					n.Pinning.PinWithMode(root, pin.Recursive)

					err := n.Pinning.Flush()
					if err != nil {
						return err
					}
				}

				outChan <- &OutputObject{Cid: root}
Jeromy's avatar
Jeromy committed
144
			}
145

146
			return nil
147
		}
148

149 150 151
		go func() {
			defer close(outChan)
			if err := addAllAndPin(req.Files()); err != nil {
152 153 154
				res.SetError(err, cmds.ErrNormal)
				return
			}
155
		}()
156 157 158 159
	},
	Type: OutputObject{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
160
			outChan, ok := res.Output().(<-chan interface{})
161
			if !ok {
162 163 164 165 166 167 168 169 170 171 172
				fmt.Println(reflect.TypeOf(res.Output()))
				return nil, u.ErrCast()
			}

			marshal := func(v interface{}) (io.Reader, error) {
				obj, ok := v.(*OutputObject)
				if !ok {
					return nil, u.ErrCast()
				}

				return strings.NewReader(obj.Cid.String() + "\n"), nil
173 174
			}

175 176 177 178 179
			return &cmds.ChannelMarshaler{
				Channel:   outChan,
				Marshaler: marshal,
				Res:       res,
			}, nil
180 181 182 183 184 185 186
		},
	},
}

var DagGetCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Get a dag node from ipfs.",
Jeromy's avatar
Jeromy committed
187 188 189
		ShortDescription: `
'ipfs dag get' fetches a dag node from ipfs and prints it out in the specifed format.
`,
190 191
	},
	Arguments: []cmds.Argument{
192
		cmds.StringArg("ref", true, false, "The object to get").EnableStdin(),
193 194 195 196 197 198 199 200
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

201
		p, err := path.ParsePath(req.Arguments()[0])
202 203 204 205 206
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

207
		obj, rem, err := n.Resolver.ResolveToLastNode(req.Context(), p)
208 209 210 211 212
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

213 214 215 216 217 218 219 220 221 222 223
		var out interface{} = obj
		if len(rem) > 0 {
			final, _, err := obj.Resolve(rem)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			out = final
		}

		res.SetOutput(out)
224 225
	},
}
Łukasz Magiera's avatar
Łukasz Magiera committed
226

Łukasz Magiera's avatar
Łukasz Magiera committed
227
// DagResolveCmd returns address of highest block within a path and a path remainder
Łukasz Magiera's avatar
Łukasz Magiera committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
var DagResolveCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Resolve ipld block",
		ShortDescription: `
'ipfs dag resolve' fetches a dag node from ipfs, prints it's address and remaining path.
`,
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("ref", true, false, "The path to resolve").EnableStdin(),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		p, err := path.ParsePath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		obj, rem, err := n.Resolver.ResolveToLastNode(req.Context(), p)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		res.SetOutput(&ResolveOutput{
			Cid:     obj.Cid(),
			RemPath: path.Join(rem),
		})
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			output := res.Output().(*ResolveOutput)
			buf := new(bytes.Buffer)
			p := output.Cid.String()
			if output.RemPath != "" {
				p = path.Join([]string{p, output.RemPath})
			}

			buf.WriteString(p)

			return buf, nil
		},
	},
	Type: ResolveOutput{},
}