commands.go 1.75 KB
Newer Older
1 2 3 4 5 6 7
/*
Package commands implements the IPFS command interface

Using github.com/ipfs/go-ipfs/commands to define the command line and
HTTP APIs.  This is the interface available to folks consuming IPFS
from outside of the Go language.
*/
8 9 10
package commands

import (
11
	"bytes"
12
	"io"
13
	"sort"
14

15
	cmds "github.com/ipfs/go-ipfs/commands"
16 17 18 19 20 21 22
)

type Command struct {
	Name        string
	Subcommands []Command
}

23 24 25 26
// CommandsCmd takes in a root command,
// and returns a command that lists the subcommands in that root
func CommandsCmd(root *cmds.Command) *cmds.Command {
	return &cmds.Command{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27 28 29 30
		Helptext: cmds.HelpText{
			Tagline:          "List all available commands.",
			ShortDescription: `Lists all available commands (and subcommands) and exits.`,
		},
31

32
		Run: func(req cmds.Request, res cmds.Response) {
33
			root := cmd2outputCmd("ipfs", root)
34
			res.SetOutput(&root)
35
		},
36
		Marshalers: cmds.MarshalerMap{
37
			cmds.Text: func(res cmds.Response) (io.Reader, error) {
38
				v := res.Output().(*Command)
39
				buf := new(bytes.Buffer)
40 41 42
				for _, s := range cmdPathStrings(v) {
					buf.Write([]byte(s + "\n"))
				}
43
				return buf, nil
44
			},
45
		},
46
		Type: Command{},
47
	}
48 49
}

50
func cmd2outputCmd(name string, cmd *cmds.Command) Command {
51 52 53 54 55 56 57
	output := Command{
		Name:        name,
		Subcommands: make([]Command, len(cmd.Subcommands)),
	}

	i := 0
	for name, sub := range cmd.Subcommands {
58
		output.Subcommands[i] = cmd2outputCmd(name, sub)
59 60 61 62 63 64
		i++
	}

	return output
}

65 66
func cmdPathStrings(cmd *Command) []string {
	var cmds []string
67

68 69 70 71 72 73
	var recurse func(prefix string, cmd *Command)
	recurse = func(prefix string, cmd *Command) {
		cmds = append(cmds, prefix+cmd.Name)
		for _, sub := range cmd.Subcommands {
			recurse(prefix+cmd.Name+" ", &sub)
		}
74 75
	}

76 77 78
	recurse("", cmd)
	sort.Sort(sort.StringSlice(cmds))
	return cmds
79
}