commands.go 1021 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
package commands

import (
	"fmt"
	"strings"

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

type Command struct {
	Name        string
	Subcommands []Command
}

var commandsCmd = &cmds.Command{
	Help: "TODO",
	Run: func(res cmds.Response, req cmds.Request) {
		root := outputCommand("ipfs", Root)
		res.SetValue(&root)
	},
	Format: func(res cmds.Response) (string, error) {
		v := res.Value().(*Command)
		return formatCommand(v, 0), nil
	},
	Type: &Command{},
}

func outputCommand(name string, cmd *cmds.Command) Command {
	output := Command{
		Name:        name,
		Subcommands: make([]Command, len(cmd.Subcommands)),
	}

	i := 0
	for name, sub := range cmd.Subcommands {
		output.Subcommands[i] = outputCommand(name, sub)
		i++
	}

	return output
}

func formatCommand(cmd *Command, depth int) string {
	var s string

	if depth > 0 {
		indent := strings.Repeat("    ", depth-1)
		s = fmt.Sprintf("%s%s\n", indent, cmd.Name)
	}

	for _, sub := range cmd.Subcommands {
		s += formatCommand(&sub, depth+1)
	}

	return s
}