dag.go 6.44 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 20 21 22
)

var DagCmd = &cmds.Command{
	Helptext: cmds.HelpText{
Jeromy's avatar
Jeromy committed
23 24 25 26 27 28 29
		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.
		`,
30 31
	},
	Subcommands: map[string]*cmds.Command{
Łukasz Magiera's avatar
Łukasz Magiera committed
32 33 34
		"put":     DagPutCmd,
		"get":     DagGetCmd,
		"resolve": DagResolveCmd,
35 36 37
	},
}

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

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

49 50 51
var DagPutCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Add a dag node to ipfs.",
Jeromy's avatar
Jeromy committed
52 53 54 55
		ShortDescription: `
'ipfs dag put' accepts input from a file or stdin and parses it
into an object of the specified format.
`,
56 57
	},
	Arguments: []cmds.Argument{
58
		cmds.FileArg("object data", true, true, "The object to put").EnableStdin(),
59 60
	},
	Options: []cmds.Option{
61 62
		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"),
63
		cmds.BoolOption("pin", "Pin this object when adding.").Default(false),
64
		cmds.StringOption("hash", "Hash function to use").Default(""),
65 66 67 68 69 70 71 72 73 74
	},
	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()
75
		hash, _, err := req.Option("hash").String()
76 77 78 79 80
		dopin, _, err := req.Option("pin").Bool()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
81

82 83 84 85 86 87 88 89 90 91 92 93 94
		// 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
			}
		}

95 96 97 98
		outChan := make(chan interface{}, 8)
		res.SetOutput((<-chan interface{})(outChan))

		addAllAndPin := func(f files.File) error {
Łukasz Magiera's avatar
Łukasz Magiera committed
99 100 101
			cids := cid.NewSet()
			b := n.DAG.Batch()

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
			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")
				}

Łukasz Magiera's avatar
Łukasz Magiera committed
119 120 121 122
				for _, nd := range nds {
					_, err := b.Add(nd)
					if err != nil {
						return err
123
					}
Łukasz Magiera's avatar
Łukasz Magiera committed
124
				}
125

Łukasz Magiera's avatar
Łukasz Magiera committed
126 127 128 129
				cid := nds[0].Cid()
				cids.Add(cid)
				outChan <- &OutputObject{Cid: cid}
			}
130

Łukasz Magiera's avatar
Łukasz Magiera committed
131 132 133
			if err := b.Commit(); err != nil {
				return err
			}
134

Łukasz Magiera's avatar
Łukasz Magiera committed
135 136
			if dopin {
				defer n.Blockstore.PinLock().Unlock()
Łukasz Magiera's avatar
Łukasz Magiera committed
137

Łukasz Magiera's avatar
Łukasz Magiera committed
138 139
				cids.ForEach(func(c *cid.Cid) error {
					n.Pinning.PinWithMode(c, pin.Recursive)
Łukasz Magiera's avatar
Łukasz Magiera committed
140
					return nil
Łukasz Magiera's avatar
Łukasz Magiera committed
141
				})
Łukasz Magiera's avatar
Łukasz Magiera committed
142

Łukasz Magiera's avatar
Łukasz Magiera committed
143 144 145 146
				err := n.Pinning.Flush()
				if err != nil {
					return err
				}
Jeromy's avatar
Jeromy committed
147
			}
148

149
			return nil
150
		}
151

152 153 154
		go func() {
			defer close(outChan)
			if err := addAllAndPin(req.Files()); err != nil {
155 156 157
				res.SetError(err, cmds.ErrNormal)
				return
			}
158
		}()
159 160 161 162
	},
	Type: OutputObject{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
163
			outChan, ok := res.Output().(<-chan interface{})
164
			if !ok {
165 166 167 168 169 170 171 172 173 174
				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
175 176
			}

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

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

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

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

216 217 218 219 220 221 222 223 224 225 226
		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)
227 228
	},
}
Łukasz Magiera's avatar
Łukasz Magiera committed
229

Łukasz Magiera's avatar
Łukasz Magiera committed
230
// DagResolveCmd returns address of highest block within a path and a path remainder
Łukasz Magiera's avatar
Łukasz Magiera committed
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 278 279 280
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{},
}