helptext.go 8.14 KB
Newer Older
1 2 3 4
package cli

import (
	"fmt"
5
	"io"
6
	"sort"
7
	"strings"
8
	"text/template"
9 10 11 12 13 14 15 16 17 18 19 20

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

const (
	requiredArg = "<%v>"
	optionalArg = "[<%v>]"
	variadicArg = "%v..."
	optionFlag  = "-%v"
	optionType  = "(%v)"

	whitespace = "\r\n\t "
21 22

	indentStr = "    "
23 24
)

25 26
type helpFields struct {
	Indent      string
27
	Usage       string
28 29 30 31 32
	Path        string
	ArgUsage    string
	Tagline     string
	Arguments   string
	Options     string
33
	Synopsis    string
34 35
	Subcommands string
	Description string
36
	MoreHelp    bool
37 38
}

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
// TrimNewlines removes extra newlines from fields. This makes aligning
// commands easier. Below, the leading + tralining newlines are removed:
//	Synopsis: `
//	    ipfs config <key>          - Get value of <key>
//	    ipfs config <key> <value>  - Set value of <key> to <value>
//	    ipfs config --show         - Show config file
//	    ipfs config --edit         - Edit config file in $EDITOR
//	`
func (f *helpFields) TrimNewlines() {
	f.Path = strings.Trim(f.Path, "\n")
	f.ArgUsage = strings.Trim(f.ArgUsage, "\n")
	f.Tagline = strings.Trim(f.Tagline, "\n")
	f.Arguments = strings.Trim(f.Arguments, "\n")
	f.Options = strings.Trim(f.Options, "\n")
	f.Synopsis = strings.Trim(f.Synopsis, "\n")
	f.Subcommands = strings.Trim(f.Subcommands, "\n")
	f.Description = strings.Trim(f.Description, "\n")
}

// Indent adds whitespace the lines of fields.
func (f *helpFields) IndentAll() {
	indent := func(s string) string {
		if s == "" {
			return s
		}
		return indentString(s, indentStr)
	}

	f.Arguments = indent(f.Arguments)
	f.Options = indent(f.Options)
	f.Synopsis = indent(f.Synopsis)
	f.Subcommands = indent(f.Subcommands)
	f.Description = indent(f.Description)
}

74
const usageFormat = "{{if .Usage}}{{.Usage}}{{else}}{{.Path}}{{if .ArgUsage}} {{.ArgUsage}}{{end}} - {{.Tagline}}{{end}}"
75 76 77 78 79 80

const longHelpFormat = `
{{.Indent}}{{template "usage" .}}

{{if .Arguments}}ARGUMENTS:

81
{{.Arguments}}
82 83 84

{{end}}{{if .Options}}OPTIONS:

85
{{.Options}}
86 87 88

{{end}}{{if .Subcommands}}SUBCOMMANDS:

89
{{.Subcommands}}
90 91 92 93 94

{{.Indent}}Use '{{.Path}} <subcmd> --help' for more information about each command.

{{end}}{{if .Description}}DESCRIPTION:

95
{{.Description}}
96 97 98

{{end}}
`
99
const shortHelpFormat = `USAGE:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100

101
{{.Indent}}{{template "usage" .}}
102 103 104 105
{{if .Synopsis}}
{{.Synopsis}}
{{end}}{{if .Description}}
{{.Description}}
106
{{end}}
107 108
{{if .MoreHelp}}Use '{{.Path}} --help' for more information about this command.
{{end}}
109
`
110 111

var usageTemplate *template.Template
112 113
var longHelpTemplate *template.Template
var shortHelpTemplate *template.Template
114 115

func init() {
116 117 118
	usageTemplate = template.Must(template.New("usage").Parse(usageFormat))
	longHelpTemplate = template.Must(usageTemplate.New("longHelp").Parse(longHelpFormat))
	shortHelpTemplate = template.Must(usageTemplate.New("shortHelp").Parse(shortHelpFormat))
119
}
120

121 122 123 124 125
// LongHelp returns a formatted CLI helptext string, generated for the given command
func LongHelp(rootName string, root *cmds.Command, path []string, out io.Writer) error {
	cmd, err := root.Get(path)
	if err != nil {
		return err
126 127
	}

128 129 130
	pathStr := rootName
	if len(path) > 0 {
		pathStr += " " + strings.Join(path, " ")
131 132
	}

133 134 135 136
	fields := helpFields{
		Indent:      indentStr,
		Path:        pathStr,
		ArgUsage:    usageText(cmd),
137 138 139
		Tagline:     cmd.Helptext.Tagline,
		Arguments:   cmd.Helptext.Arguments,
		Options:     cmd.Helptext.Options,
140
		Synopsis:    cmd.Helptext.Synopsis,
141 142 143
		Subcommands: cmd.Helptext.Subcommands,
		Description: cmd.Helptext.ShortDescription,
		Usage:       cmd.Helptext.Usage,
144
		MoreHelp:    (cmd != root),
145 146
	}

147 148
	if len(cmd.Helptext.LongDescription) > 0 {
		fields.Description = cmd.Helptext.LongDescription
149 150
	}

151
	// autogen fields that are empty
152
	if len(fields.Arguments) == 0 {
153
		fields.Arguments = strings.Join(argumentText(cmd), "\n")
154
	}
155
	if len(fields.Options) == 0 {
156 157
		fields.Options = strings.Join(optionText(cmd), "\n")
	}
158
	if len(fields.Subcommands) == 0 {
159 160 161
		fields.Subcommands = strings.Join(subcommandText(cmd, rootName, path), "\n")
	}

162 163 164 165 166
	// trim the extra newlines (see TrimNewlines doc)
	fields.TrimNewlines()

	// indent all fields that have been set
	fields.IndentAll()
167

168
	return longHelpTemplate.Execute(out, fields)
169 170
}

171 172 173 174 175 176 177
// ShortHelp returns a formatted CLI helptext string, generated for the given command
func ShortHelp(rootName string, root *cmds.Command, path []string, out io.Writer) error {
	cmd, err := root.Get(path)
	if err != nil {
		return err
	}

178 179 180 181 182
	// default cmd to root if there is no path
	if path == nil && cmd == nil {
		cmd = root
	}

183 184 185 186 187 188 189 190 191
	pathStr := rootName
	if len(path) > 0 {
		pathStr += " " + strings.Join(path, " ")
	}

	fields := helpFields{
		Indent:      indentStr,
		Path:        pathStr,
		ArgUsage:    usageText(cmd),
192
		Tagline:     cmd.Helptext.Tagline,
193
		Synopsis:    cmd.Helptext.Synopsis,
194 195
		Description: cmd.Helptext.ShortDescription,
		Usage:       cmd.Helptext.Usage,
196
		MoreHelp:    (cmd != root),
197 198
	}

199 200 201 202 203
	// trim the extra newlines (see TrimNewlines doc)
	fields.TrimNewlines()

	// indent all fields that have been set
	fields.IndentAll()
204 205 206 207

	return shortHelpTemplate.Execute(out, fields)
}

208 209 210 211
func argumentText(cmd *cmds.Command) []string {
	lines := make([]string, len(cmd.Arguments))

	for i, arg := range cmd.Arguments {
212 213 214 215 216
		lines[i] = argUsageText(arg)
	}
	lines = align(lines)
	for i, arg := range cmd.Arguments {
		lines[i] += " - " + arg.Description
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
	}

	return lines
}

func optionText(cmd ...*cmds.Command) []string {
	// get a slice of the options we want to list out
	options := make([]cmds.Option, 0)
	for _, c := range cmd {
		for _, opt := range c.Options {
			options = append(options, opt)
		}
	}

	// add option names to output (with each name aligned)
	lines := make([]string, 0)
	j := 0
	for {
		done := true
		i := 0
		for _, opt := range options {
			if len(lines) < i+1 {
				lines = append(lines, "")
			}
241

242
			names := sortByLength(opt.Names())
243 244
			if len(names) >= j+1 {
				lines[i] += fmt.Sprintf(optionFlag, names[j])
245
			}
246
			if len(names) > j+1 {
247 248 249 250 251 252 253 254 255 256 257 258 259 260
				lines[i] += ", "
				done = false
			}

			i++
		}

		if done {
			break
		}

		lines = align(lines)
		j++
	}
261
	lines = align(lines)
262 263 264

	// add option types to output
	for i, opt := range options {
265
		lines[i] += " " + fmt.Sprintf("%v", opt.Type())
266 267 268 269 270
	}
	lines = align(lines)

	// add option descriptions to output
	for i, opt := range options {
271
		lines[i] += " - " + opt.Description()
272 273 274 275 276 277 278
	}

	return lines
}

func subcommandText(cmd *cmds.Command, rootName string, path []string) []string {
	prefix := fmt.Sprintf("%v %v", rootName, strings.Join(path, " "))
279 280 281
	if len(path) > 0 {
		prefix += " "
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282
	subcmds := make([]*cmds.Command, len(cmd.Subcommands))
283 284 285 286 287
	lines := make([]string, len(cmd.Subcommands))

	i := 0
	for name, sub := range cmd.Subcommands {
		usage := usageText(sub)
Matt Bell's avatar
Matt Bell committed
288 289 290
		if len(usage) > 0 {
			usage = " " + usage
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
291 292
		lines[i] = prefix + name + usage
		subcmds[i] = sub
293 294 295
		i++
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296 297 298 299 300
	lines = align(lines)
	for i, sub := range subcmds {
		lines[i] += " - " + sub.Helptext.Tagline
	}

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
	return lines
}

func usageText(cmd *cmds.Command) string {
	s := ""
	for i, arg := range cmd.Arguments {
		if i != 0 {
			s += " "
		}
		s += argUsageText(arg)
	}

	return s
}

func argUsageText(arg cmds.Argument) string {
	s := arg.Name

	if arg.Required {
		s = fmt.Sprintf(requiredArg, s)
	} else {
		s = fmt.Sprintf(optionalArg, s)
	}

	if arg.Variadic {
		s = fmt.Sprintf(variadicArg, s)
	}

	return s
}

func align(lines []string) []string {
	longest := 0
	for _, line := range lines {
		length := len(line)
		if length > longest {
			longest = length
		}
	}

	for i, line := range lines {
		length := len(line)
		if length > 0 {
			lines[i] += strings.Repeat(" ", longest-length)
		}
	}

	return lines
}

func indent(lines []string, prefix string) []string {
	for i, line := range lines {
		lines[i] = prefix + indentString(line, prefix)
	}
	return lines
}

func indentString(line string, prefix string) string {
359
	return prefix + strings.Replace(line, "\n", "\n"+prefix, -1)
360
}
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

type lengthSlice []string

func (ls lengthSlice) Len() int {
	return len(ls)
}
func (ls lengthSlice) Swap(a, b int) {
	ls[a], ls[b] = ls[b], ls[a]
}
func (ls lengthSlice) Less(a, b int) bool {
	return len(ls[a]) < len(ls[b])
}

func sortByLength(slice []string) []string {
	output := make(lengthSlice, len(slice))
	for i, val := range slice {
		output[i] = val
	}
	sort.Sort(output)
	return []string(output)
}