commands.go 3.82 KB
Newer Older
1
// Package commands implements the ipfs command interface
2 3 4 5
//
// Using github.com/ipfs/go-ipfs/commands to define the command line and HTTP
// APIs.  This is the interface available to folks using IPFS from outside of
// the Go language.
6 7 8
package commands

import (
Jan Winkelmann's avatar
Jan Winkelmann committed
9
	"fmt"
10
	"io"
11
	"os"
12
	"sort"
13
	"strings"
14

Steven Allen's avatar
Steven Allen committed
15
	"github.com/ipfs/go-ipfs-cmds"
16 17
)

Jan Winkelmann's avatar
Jan Winkelmann committed
18 19 20 21 22 23 24 25 26 27 28
type commandEncoder struct {
	w io.Writer
}

func (e *commandEncoder) Encode(v interface{}) error {
	var (
		cmd *Command
		ok  bool
	)

	if cmd, ok = v.(*Command); !ok {
Dimitris Apostolou's avatar
Dimitris Apostolou committed
29
		return fmt.Errorf(`core/commands: unexpected type %T, expected *"core/commands".Command`, v)
Jan Winkelmann's avatar
Jan Winkelmann committed
30 31 32 33 34 35 36 37 38 39 40 41
	}

	for _, s := range cmdPathStrings(cmd, cmd.showOpts) {
		_, err := e.w.Write([]byte(s + "\n"))
		if err != nil {
			return err
		}
	}

	return nil
}

42 43 44
type Command struct {
	Name        string
	Subcommands []Command
45
	Options     []Option
Jan Winkelmann's avatar
Jan Winkelmann committed
46 47

	showOpts bool
48 49 50 51
}

type Option struct {
	Names []string
52 53
}

54
const (
55
	flagsOptionName = "flags"
56 57
)

58 59 60 61
// 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{
Steven Allen's avatar
Steven Allen committed
62
		Helptext: cmds.HelpText{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63 64 65
			Tagline:          "List all available commands.",
			ShortDescription: `Lists all available commands (and subcommands) and exits.`,
		},
Steven Allen's avatar
Steven Allen committed
66 67
		Options: []cmds.Option{
			cmds.BoolOption(flagsOptionName, "f", "Show command flags"),
68
		},
69
		Extra: CreateCmdExtras(SetDoesNotUseRepo(true)),
keks's avatar
keks committed
70
		Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
71
			rootCmd := cmd2outputCmd("ipfs", root)
72
			rootCmd.showOpts, _ = req.Options[flagsOptionName].(bool)
keks's avatar
keks committed
73
			return cmds.EmitOnce(res, &rootCmd)
74
		},
Jan Winkelmann's avatar
Jan Winkelmann committed
75
		Encoders: cmds.EncoderMap{
76
			cmds.Text: func(req *cmds.Request) func(io.Writer) cmds.Encoder {
Jan Winkelmann's avatar
Jan Winkelmann committed
77
				return func(w io.Writer) cmds.Encoder { return &commandEncoder{w} }
78
			},
79
		},
80
		Type: Command{},
81
	}
82 83
}

84 85 86 87 88 89
func cmd2outputCmd(name string, cmd *cmds.Command) Command {
	opts := make([]Option, len(cmd.Options))
	for i, opt := range cmd.Options {
		opts[i] = Option{opt.Names()}
	}

90 91
	output := Command{
		Name:        name,
92
		Subcommands: make([]Command, 0, len(cmd.Subcommands)),
93
		Options:     opts,
94 95
	}

Jan Winkelmann's avatar
Jan Winkelmann committed
96
	for name, sub := range cmd.Subcommands {
97
		output.Subcommands = append(output.Subcommands, cmd2outputCmd(name, sub))
Jan Winkelmann's avatar
Jan Winkelmann committed
98 99
	}

100 101 102
	return output
}

103
func cmdPathStrings(cmd *Command, showOptions bool) []string {
104
	var cmds []string
105

106 107
	var recurse func(prefix string, cmd *Command)
	recurse = func(prefix string, cmd *Command) {
rht's avatar
rht committed
108 109
		newPrefix := prefix + cmd.Name
		cmds = append(cmds, newPrefix)
110 111
		if prefix != "" && showOptions {
			for _, options := range cmd.Options {
112
				var cmdOpts []string
113
				for _, flag := range options.Names {
114 115 116 117 118 119
					if len(flag) == 1 {
						flag = "-" + flag
					} else {
						flag = "--" + flag
					}
					cmdOpts = append(cmdOpts, newPrefix+" "+flag)
rht's avatar
rht committed
120
				}
121
				cmds = append(cmds, strings.Join(cmdOpts, " / "))
rht's avatar
rht committed
122 123
			}
		}
124
		for _, sub := range cmd.Subcommands {
rht's avatar
rht committed
125
			recurse(newPrefix+" ", &sub)
126
		}
127 128
	}

129
	recurse("", cmd)
130
	sort.Strings(cmds)
131
	return cmds
132
}
Jan Winkelmann's avatar
Jan Winkelmann committed
133

134 135
type nonFatalError string

136
// streamResult is a helper function to stream results that possibly
Kevin Atkinson's avatar
Kevin Atkinson committed
137 138
// contain non-fatal errors.  The helper function is allowed to panic
// on internal errors.
139
func streamResult(procVal func(interface{}, io.Writer) nonFatalError) func(cmds.Response, cmds.ResponseEmitter) error {
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
	return func(res cmds.Response, re cmds.ResponseEmitter) (err error) {
		defer func() {
			if r := recover(); r != nil {
				err = fmt.Errorf("internal error: %v", r)
			}
			re.Close()
		}()

		var errors bool
		for {
			v, err := res.Next()
			if err != nil {
				if err == io.EOF {
					break
				}
				return err
			}

			errorMsg := procVal(v, os.Stdout)

			if errorMsg != "" {
				errors = true
				fmt.Fprintf(os.Stderr, "%s\n", errorMsg)
			}
		}

		if errors {
			return fmt.Errorf("errors while displaying some entries")
		}
		return nil
	}
}