commands.go 2.08 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
)

type Command struct {
	Name        string
	Subcommands []Command
rht's avatar
rht committed
21
	Options     []cmds.Option
22 23
}

24 25 26 27
// 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
28 29 30 31
		Helptext: cmds.HelpText{
			Tagline:          "List all available commands.",
			ShortDescription: `Lists all available commands (and subcommands) and exits.`,
		},
32

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

51
func cmd2outputCmd(name string, cmd *cmds.Command) Command {
52 53 54
	output := Command{
		Name:        name,
		Subcommands: make([]Command, len(cmd.Subcommands)),
rht's avatar
rht committed
55
		Options:     cmd.Options,
56 57 58 59
	}

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

	return output
}

67 68
func cmdPathStrings(cmd *Command) []string {
	var cmds []string
69

70 71
	var recurse func(prefix string, cmd *Command)
	recurse = func(prefix string, cmd *Command) {
rht's avatar
rht committed
72 73 74 75 76 77 78 79 80 81 82 83 84
		newPrefix := prefix + cmd.Name
		cmds = append(cmds, newPrefix)
		if prefix != "" {
			for _, option := range cmd.Options {
				optName := option.Names()[0]
				if len(optName) == 1 {
					optName = "-" + optName
				} else {
					optName = "--" + optName
				}
				cmds = append(cmds, newPrefix+" "+optName)
			}
		}
85
		for _, sub := range cmd.Subcommands {
rht's avatar
rht committed
86
			recurse(newPrefix+" ", &sub)
87
		}
88 89
	}

90 91 92
	recurse("", cmd)
	sort.Sort(sort.StringSlice(cmds))
	return cmds
93
}