@cryptotaxi247 / kubo / commits / 1342575d2

cmds2/commands: better sorting

Juan Batiz-Benet committed Nov 12, 2014 at 22:49 UTC 1342575d242198ff672160b67c4c454c6f45fbba
1 file changed +21 -15
core/commands2/commands.go
+21 -15
@@ -1,7 +1,8 @@
1 package commands
2
3 import (
4 - "fmt"
4 + "bytes"
5 + "sort"
6
7 cmds "github.com/jbenet/go-ipfs/commands"
8 )
@@ -21,21 +22,24 @@ func CommandsCmd(root *cmds.Command) *cmds.Command {
22 },
23
24 Run: func(req cmds.Request) (interface{}, error) {
24 - root := outputCommand("ipfs", root)
25 + root := cmd2outputCmd("ipfs", root)
26 return &root, nil
27 },
28 Marshallers: map[cmds.EncodingType]cmds.Marshaller{
29 cmds.Text: func(res cmds.Response) ([]byte, error) {
30 v := res.Output().(*Command)
30 - s := formatCommand("", v)
31 - return []byte(s), nil
31 + var buf bytes.Buffer
32 + for _, s := range cmdPathStrings(v) {
33 + buf.Write([]byte(s + "\n"))
34 + }
35 + return buf.Bytes(), nil
36 },
37 },
38 Type: &Command{},
39 }
40 }
41
38 -func outputCommand(name string, cmd *cmds.Command) Command {
42 +func cmd2outputCmd(name string, cmd *cmds.Command) Command {
43 output := Command{
44 Name: name,
45 Subcommands: make([]Command, len(cmd.Subcommands)),
@@ -43,23 +47,25 @@ func outputCommand(name string, cmd *cmds.Command) Command {
47
48 i := 0
49 for name, sub := range cmd.Subcommands {
46 - output.Subcommands[i] = outputCommand(name, sub)
50 + output.Subcommands[i] = cmd2outputCmd(name, sub)
51 i++
52 }
53
54 return output
55 }
56
53 -func formatCommand(prefix string, cmd *Command) string {
54 - if len(prefix) > 0 {
55 - prefix += " "
56 - }
57 - s := fmt.Sprintf("%s%s\n", prefix, cmd.Name)
57 +func cmdPathStrings(cmd *Command) []string {
58 + var cmds []string
59
59 - prefix += cmd.Name
60 - for _, sub := range cmd.Subcommands {
61 - s += formatCommand(prefix, &sub)
60 + var recurse func(prefix string, cmd *Command)
61 + recurse = func(prefix string, cmd *Command) {
62 + cmds = append(cmds, prefix+cmd.Name)
63 + for _, sub := range cmd.Subcommands {
64 + recurse(prefix+cmd.Name+" ", &sub)
65 + }
66 }
67
64 - return s
68 + recurse("", cmd)
69 + sort.Sort(sort.StringSlice(cmds))
70 + return cmds
71 }