github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/core/commands/commands.go (about) 1 /* 2 Package commands implements the IPFS command interface 3 4 Using github.com/ipfs/go-ipfs/commands to define the command line and 5 HTTP APIs. This is the interface available to folks consuming IPFS 6 from outside of the Go language. 7 */ 8 package commands 9 10 import ( 11 "bytes" 12 "io" 13 "sort" 14 15 cmds "github.com/ipfs/go-ipfs/commands" 16 ) 17 18 type Command struct { 19 Name string 20 Subcommands []Command 21 } 22 23 // CommandsCmd takes in a root command, 24 // and returns a command that lists the subcommands in that root 25 func CommandsCmd(root *cmds.Command) *cmds.Command { 26 return &cmds.Command{ 27 Helptext: cmds.HelpText{ 28 Tagline: "List all available commands.", 29 ShortDescription: `Lists all available commands (and subcommands) and exits.`, 30 }, 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 for _, s := range cmdPathStrings(v) { 41 buf.Write([]byte(s + "\n")) 42 } 43 return buf, nil 44 }, 45 }, 46 Type: Command{}, 47 } 48 } 49 50 func cmd2outputCmd(name string, cmd *cmds.Command) Command { 51 output := Command{ 52 Name: name, 53 Subcommands: make([]Command, len(cmd.Subcommands)), 54 } 55 56 i := 0 57 for name, sub := range cmd.Subcommands { 58 output.Subcommands[i] = cmd2outputCmd(name, sub) 59 i++ 60 } 61 62 return output 63 } 64 65 func cmdPathStrings(cmd *Command) []string { 66 var cmds []string 67 68 var recurse func(prefix string, cmd *Command) 69 recurse = func(prefix string, cmd *Command) { 70 cmds = append(cmds, prefix+cmd.Name) 71 for _, sub := range cmd.Subcommands { 72 recurse(prefix+cmd.Name+" ", &sub) 73 } 74 } 75 76 recurse("", cmd) 77 sort.Sort(sort.StringSlice(cmds)) 78 return cmds 79 }