commands.go 1.52 KB
Newer Older
1 2 3
package commands

import (
4 5
	"bytes"
	"sort"
6 7 8 9 10 11 12 13 14

	cmds "github.com/jbenet/go-ipfs/commands"
)

type Command struct {
	Name        string
	Subcommands []Command
}

15 16 17 18
// 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
19 20 21 22
		Helptext: cmds.HelpText{
			Tagline:          "List all available commands.",
			ShortDescription: `Lists all available commands (and subcommands) and exits.`,
		},
23 24

		Run: func(req cmds.Request) (interface{}, error) {
25
			root := cmd2outputCmd("ipfs", root)
26 27
			return &root, nil
		},
28
		Marshalers: cmds.MarshalerMap{
29 30
			cmds.Text: func(res cmds.Response) ([]byte, error) {
				v := res.Output().(*Command)
31 32 33 34 35
				var buf bytes.Buffer
				for _, s := range cmdPathStrings(v) {
					buf.Write([]byte(s + "\n"))
				}
				return buf.Bytes(), nil
36
			},
37
		},
38 39
		Type: &Command{},
	}
40 41
}

42
func cmd2outputCmd(name string, cmd *cmds.Command) Command {
43 44 45 46 47 48 49
	output := Command{
		Name:        name,
		Subcommands: make([]Command, len(cmd.Subcommands)),
	}

	i := 0
	for name, sub := range cmd.Subcommands {
50
		output.Subcommands[i] = cmd2outputCmd(name, sub)
51 52 53 54 55 56
		i++
	}

	return output
}

57 58
func cmdPathStrings(cmd *Command) []string {
	var cmds []string
59

60 61 62 63 64 65
	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)
		}
66 67
	}

68 69 70
	recurse("", cmd)
	sort.Sort(sort.StringSlice(cmds))
	return cmds
71
}