refs.go 6.68 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
	key "github.com/ipfs/go-ipfs/blocks/key"
11 12 13 14
	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"
15
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
Jeromy's avatar
Jeromy committed
16
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
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{
rht's avatar
rht committed
36
		Tagline: "Lists links (references) from an object.",
37
		ShortDescription: `
Richard Littauer's avatar
Richard Littauer committed
38
Displays the link hashes an IPFS or IPNS object(s) contains, with the following format:
39

40 41
  <link base58 hash>

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

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

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

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

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

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

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

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

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

			for _, o := range objs {
				if _, err := rw.WriteRefs(o); err != nil {
Jeromy's avatar
Jeromy committed
113
					out <- &RefWrapper{Err: err.Error()}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114 115 116 117
					return
				}
			}
		}()
Jeromy's avatar
Jeromy committed
118 119 120 121 122 123 124
	},
	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
125

Jeromy's avatar
Jeromy committed
126 127 128 129 130 131 132 133 134 135 136
			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)
				}

Jeromy's avatar
Jeromy committed
137
				return strings.NewReader(obj.Ref + "\n"), nil
Jeromy's avatar
Jeromy committed
138 139 140 141 142
			}

			return &cmds.ChannelMarshaler{
				Channel:   outChan,
				Marshaler: marshal,
143
				Res:       res,
Jeromy's avatar
Jeromy committed
144 145
			}, 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
}

var RefsLocalCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
152
		Tagline: "Lists all local references.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153 154 155 156 157
		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
	nkey, err := n.Key()
	if err != nil {
		return 0, err
	}

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

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

246
		nd, err := ng.Get(rw.Ctx)
247
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248
			return count, err
249 250
		}

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

260 261 262 263 264 265 266 267 268 269 270 271
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 {
272
		lk := key.Key(l.Hash)
273 274 275 276 277 278 279 280 281 282 283 284 285

		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
286
// skip returns whether to skip a key
287
func (rw *RefWriter) skip(k key.Key) bool {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288 289 290
	if !rw.Unique {
		return false
	}
291

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292
	if rw.seen == nil {
293
		rw.seen = make(map[key.Key]struct{})
294 295
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296 297 298 299 300
	_, found := rw.seen[k]
	if !found {
		rw.seen[k] = struct{}{}
	}
	return found
301 302
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
313
	var s string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
314 315 316 317 318 319 320 321 322 323
	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
324 325
	}

Jeromy's avatar
Jeromy committed
326
	rw.out <- &RefWrapper{Ref: s}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
327
	return nil
328
}