refs.go 6.64 KB
Newer Older
1 2 3
package commands

import (
4
	"bytes"
Jeromy's avatar
Jeromy committed
5 6
	"errors"
	"fmt"
7
	"io"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	"strings"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9

10
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
11
	key "github.com/ipfs/go-ipfs/blocks/key"
12 13 14 15 16
	cmds "github.com/ipfs/go-ipfs/commands"
	"github.com/ipfs/go-ipfs/core"
	dag "github.com/ipfs/go-ipfs/merkledag"
	path "github.com/ipfs/go-ipfs/path"
	u "github.com/ipfs/go-ipfs/util"
17 18
)

19 20
// KeyList is a general type for outputting lists of keys
type KeyList struct {
21
	Keys []key.Key
22 23 24
}

// KeyListTextMarshaler outputs a KeyList as plaintext, one key per line
25
func KeyListTextMarshaler(res cmds.Response) (io.Reader, error) {
26
	output := res.Output().(*KeyList)
27
	buf := new(bytes.Buffer)
28
	for _, key := range output.Keys {
29
		buf.WriteString(key.B58String() + "\n")
30
	}
31
	return buf, nil
32 33
}

34
var RefsCmd = &cmds.Command{
35
	Helptext: cmds.HelpText{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
36
		Tagline: "Lists links (references) from an object",
37 38
		ShortDescription: `
Retrieves the object named by <ipfs-path> and displays the link
39
hashes it contains, with the following format:
40

41 42
  <link base58 hash>

43 44 45
Note: list all refs recursively with -r.
`,
	},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47 48
	Subcommands: map[string]*cmds.Command{
		"local": RefsLocalCmd,
	},
49
	Arguments: []cmds.Argument{
50
		cmds.StringArg("ipfs-path", true, true, "Path to the object(s) to list refs from").EnableStdin(),
51 52
	},
	Options: []cmds.Option{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53 54
		cmds.StringOption("format", "Emit edges with given format. tokens: <src> <dst> <linkname>"),
		cmds.BoolOption("edges", "e", "Emit edge format: `<from> -> <to>`"),
55
		cmds.BoolOption("unique", "u", "Omit duplicate refs from output"),
56
		cmds.BoolOption("recursive", "r", "Recursively list links of child nodes"),
57
	},
58
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
59 60
		ctx := req.Context()
		n, err := req.InvocContext().GetNode()
61
		if err != nil {
62 63
			res.SetError(err, cmds.ErrNormal)
			return
64
		}
65

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
66
		unique, _, err := req.Option("unique").Bool()
67
		if err != nil {
68 69
			res.SetError(err, cmds.ErrNormal)
			return
70
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71 72 73

		recursive, _, err := req.Option("recursive").Bool()
		if err != nil {
74 75
			res.SetError(err, cmds.ErrNormal)
			return
76 77
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
		edges, _, err := req.Option("edges").Bool()
79
		if err != nil {
80 81
			res.SetError(err, cmds.ErrNormal)
			return
82
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84 85
		format, _, err := req.Option("format").String()
		if err != nil {
86 87
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88 89
		}

90
		objs, err := objectsForPaths(ctx, n, req.Arguments())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
		if err != nil {
92 93
			res.SetError(err, cmds.ErrNormal)
			return
94
		}
95

Jeromy's avatar
Jeromy committed
96 97
		out := make(chan interface{})
		res.SetOutput((<-chan interface{})(out))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98 99

		go func() {
Jeromy's avatar
Jeromy committed
100
			defer close(out)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101 102

			rw := RefWriter{
Jeromy's avatar
Jeromy committed
103
				out:       out,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
				DAG:       n.DAG,
105
				Ctx:       ctx,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106 107
				Unique:    unique,
				PrintEdge: edges,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108
				PrintFmt:  format,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109 110 111 112 113
				Recursive: recursive,
			}

			for _, o := range objs {
				if _, err := rw.WriteRefs(o); err != nil {
Jeromy's avatar
Jeromy committed
114
					out <- &RefWrapper{Err: err.Error()}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115 116 117 118
					return
				}
			}
		}()
Jeromy's avatar
Jeromy committed
119 120 121 122 123 124 125
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			outChan, ok := res.Output().(<-chan interface{})
			if !ok {
				return nil, u.ErrCast()
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126

Jeromy's avatar
Jeromy committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
			marshal := func(v interface{}) (io.Reader, error) {
				obj, ok := v.(*RefWrapper)
				if !ok {
					fmt.Println("%#v", v)
					return nil, u.ErrCast()
				}

				if obj.Err != "" {
					return nil, errors.New(obj.Err)
				}

				return strings.NewReader(obj.Ref), nil
			}

			return &cmds.ChannelMarshaler{
				Channel:   outChan,
				Marshaler: marshal,
			}, nil
		},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146
	},
Jeromy's avatar
Jeromy committed
147
	Type: RefWrapper{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149 150 151 152 153 154 155 156 157
}

var RefsLocalCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Lists all local references",
		ShortDescription: `
Displays the hashes of all local objects.
`,
	},

158
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
159 160
		ctx := req.Context()
		n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161
		if err != nil {
162 163
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164 165 166
		}

		// todo: make async
167
		allKeys, err := n.Blockstore.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168
		if err != nil {
169 170
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171 172 173 174 175 176 177
		}

		piper, pipew := io.Pipe()

		go func() {
			defer pipew.Close()

178
			for k := range allKeys {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179 180
				s := k.Pretty() + "\n"
				if _, err := pipew.Write([]byte(s)); err != nil {
Jeromy's avatar
Jeromy committed
181
					log.Error("pipe write error: ", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
					return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183 184 185 186
				}
			}
		}()

Jeromy's avatar
Jeromy committed
187
		res.SetOutput(piper)
188 189 190
	},
}

191
func objectsForPaths(ctx context.Context, n *core.IpfsNode, paths []string) ([]*dag.Node, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192 193
	objects := make([]*dag.Node, len(paths))
	for i, p := range paths {
194
		o, err := core.Resolve(ctx, n, path.Path(p))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
195 196 197 198 199 200 201 202
		if err != nil {
			return nil, err
		}
		objects[i] = o
	}
	return objects, nil
}

Jeromy's avatar
Jeromy committed
203 204 205
type RefWrapper struct {
	Ref string
	Err string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206 207 208
}

type RefWriter struct {
Jeromy's avatar
Jeromy committed
209
	out chan interface{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
210 211
	DAG dag.DAGService
	Ctx context.Context
212

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213 214 215
	Unique    bool
	Recursive bool
	PrintEdge bool
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216
	PrintFmt  string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217

218
	seen map[key.Key]struct{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219 220 221 222
}

// WriteRefs writes refs of the given object to the underlying writer.
func (rw *RefWriter) WriteRefs(n *dag.Node) (int, error) {
223 224 225
	if rw.Recursive {
		return rw.writeRefsRecursive(n)
	}
rht's avatar
rht committed
226
	return rw.writeRefsSingle(n)
227 228 229
}

func (rw *RefWriter) writeRefsRecursive(n *dag.Node) (int, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
230 231 232 233 234 235 236 237 238
	nkey, err := n.Key()
	if err != nil {
		return 0, err
	}

	if rw.skip(nkey) {
		return 0, nil
	}

239 240
	var count int
	for i, ng := range rw.DAG.GetDAG(rw.Ctx, n) {
241
		lk := key.Key(n.Links[i].Hash)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242 243 244 245
		if rw.skip(lk) {
			continue
		}

246
		if err := rw.WriteEdge(nkey, lk, n.Links[i].Name); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248
			return count, err
		}
249

250
		nd, err := ng.Get(rw.Ctx)
251
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252
			return count, err
253 254
		}

255
		c, err := rw.writeRefsRecursive(nd)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256
		count += c
257
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258
			return count, err
259 260
		}
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261
	return count, nil
262 263
}

264 265 266 267 268 269 270 271 272 273 274 275
func (rw *RefWriter) writeRefsSingle(n *dag.Node) (int, error) {
	nkey, err := n.Key()
	if err != nil {
		return 0, err
	}

	if rw.skip(nkey) {
		return 0, nil
	}

	count := 0
	for _, l := range n.Links {
276
		lk := key.Key(l.Hash)
277 278 279 280 281 282 283 284 285 286 287 288 289

		if rw.skip(lk) {
			continue
		}

		if err := rw.WriteEdge(nkey, lk, l.Name); err != nil {
			return count, err
		}
		count++
	}
	return count, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
290
// skip returns whether to skip a key
291
func (rw *RefWriter) skip(k key.Key) bool {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292 293 294
	if !rw.Unique {
		return false
	}
295

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296
	if rw.seen == nil {
297
		rw.seen = make(map[key.Key]struct{})
298 299
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
300 301 302 303 304
	_, found := rw.seen[k]
	if !found {
		rw.seen[k] = struct{}{}
	}
	return found
305 306
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
307
// Write one edge
308
func (rw *RefWriter) WriteEdge(from, to key.Key, linkname string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
309 310 311 312 313
	if rw.Ctx != nil {
		select {
		case <-rw.Ctx.Done(): // just in case.
			return rw.Ctx.Err()
		default:
314 315 316
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
317
	var s string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
318 319 320 321 322 323 324 325 326 327
	switch {
	case rw.PrintFmt != "":
		s = rw.PrintFmt
		s = strings.Replace(s, "<src>", from.Pretty(), -1)
		s = strings.Replace(s, "<dst>", to.Pretty(), -1)
		s = strings.Replace(s, "<linkname>", linkname, -1)
	case rw.PrintEdge:
		s = from.Pretty() + " -> " + to.Pretty()
	default:
		s += to.Pretty()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
328
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
329
	s += "\n"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
330

Jeromy's avatar
Jeromy committed
331
	rw.out <- &RefWrapper{Ref: s}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332
	return nil
333
}