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

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

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

type Command struct {
	Name        string
	Subcommands []Command
}

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

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

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

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

	return output
}

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

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

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