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

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

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

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

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

	indentStr = "    "
22 23
)

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

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
// 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)
}

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

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

{{if .Arguments}}ARGUMENTS:

79
{{.Arguments}}
80 81 82

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

83
{{.Options}}
84 85 86

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

87
{{.Subcommands}}
88 89 90 91 92

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

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

93
{{.Description}}
94 95 96

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

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

var usageTemplate *template.Template
109 110
var longHelpTemplate *template.Template
var shortHelpTemplate *template.Template
111 112 113

func init() {
	tmpl, err := template.New("usage").Parse(usageFormat)
114
	if err != nil {
115
		panic(err)
116
	}
117
	usageTemplate = tmpl
118

119 120 121
	tmpl, err = usageTemplate.New("longHelp").Parse(longHelpFormat)
	if err != nil {
		panic(err)
122
	}
123
	longHelpTemplate = tmpl
124 125 126 127 128 129

	tmpl, err = usageTemplate.New("shortHelp").Parse(shortHelpFormat)
	if err != nil {
		panic(err)
	}
	shortHelpTemplate = tmpl
130
}
131

132 133 134 135 136
// 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
137 138
	}

139 140 141
	pathStr := rootName
	if len(path) > 0 {
		pathStr += " " + strings.Join(path, " ")
142 143
	}

144
	// TODO: get the fields from the HelpText struct by default (when commands are ported to use it)
145 146 147 148 149 150 151
	fields := helpFields{
		Indent:      indentStr,
		Path:        pathStr,
		ArgUsage:    usageText(cmd),
		Tagline:     cmd.Description,
		Arguments:   cmd.ArgumentHelp,
		Options:     cmd.OptionHelp,
152
		Synopsis:    cmd.Helptext.Synopsis,
153 154
		Subcommands: cmd.SubcommandHelp,
		Description: cmd.Help,
155 156
	}

157 158 159 160 161 162 163 164 165 166 167
	// TODO: don't do these checks, just use these fields by default (when commands get ported to it)
	if len(cmd.Helptext.Tagline) > 0 {
		fields.Tagline = cmd.Helptext.Tagline
	}
	if len(cmd.Helptext.ShortDescription) > 0 {
		fields.Description = cmd.Helptext.ShortDescription
	}
	if len(cmd.Helptext.Usage) > 0 {
		fields.Usage = cmd.Helptext.Subcommands
	}

168 169 170
	// autogen fields that are empty
	if len(cmd.ArgumentHelp) == 0 {
		fields.Arguments = strings.Join(argumentText(cmd), "\n")
171
	}
172 173 174 175 176 177 178
	if len(cmd.OptionHelp) == 0 {
		fields.Options = strings.Join(optionText(cmd), "\n")
	}
	if len(cmd.SubcommandHelp) == 0 {
		fields.Subcommands = strings.Join(subcommandText(cmd, rootName, path), "\n")
	}

179 180 181 182 183
	// trim the extra newlines (see TrimNewlines doc)
	fields.TrimNewlines()

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

185
	return longHelpTemplate.Execute(out, fields)
186 187
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
// 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
	}

	pathStr := rootName
	if len(path) > 0 {
		pathStr += " " + strings.Join(path, " ")
	}

	fields := helpFields{
		Indent:      indentStr,
		Path:        pathStr,
		ArgUsage:    usageText(cmd),
		Tagline:     cmd.Description,
205
		Synopsis:    cmd.Helptext.Synopsis,
206 207 208
		Description: cmd.Help,
	}

209 210 211 212 213 214 215 216 217 218 219 220 221
	// TODO: don't do these checks, just use these fields by default (when commands get ported to it)
	if len(cmd.Helptext.Tagline) > 0 {
		fields.Tagline = cmd.Helptext.Tagline
	}
	if len(cmd.Helptext.Arguments) > 0 {
		fields.Arguments = cmd.Helptext.Arguments
	}
	if len(cmd.Helptext.Options) > 0 {
		fields.Options = cmd.Helptext.Options
	}
	if len(cmd.Helptext.Subcommands) > 0 {
		fields.Subcommands = cmd.Helptext.Subcommands
	}
222
	if len(cmd.Helptext.ShortDescription) > 0 {
223 224 225 226 227 228
		fields.Description = cmd.Helptext.ShortDescription
	}
	if len(cmd.Helptext.Usage) > 0 {
		fields.Usage = cmd.Helptext.Subcommands
	}

229 230 231 232 233
	// trim the extra newlines (see TrimNewlines doc)
	fields.TrimNewlines()

	// indent all fields that have been set
	fields.IndentAll()
234 235 236 237

	return shortHelpTemplate.Execute(out, fields)
}

238 239 240 241
func argumentText(cmd *cmds.Command) []string {
	lines := make([]string, len(cmd.Arguments))

	for i, arg := range cmd.Arguments {
242 243
		lines[i] = argUsageText(arg) + " - " + arg.Description
		lines[i] = indentString(lines[i], "    ")
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
	}

	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, "")
			}
			if len(opt.Names) >= j+1 {
				lines[i] += fmt.Sprintf(optionFlag, opt.Names[j])
			}
			if len(opt.Names) > j+1 {
				lines[i] += ", "
				done = false
			}

			i++
		}

		if done {
			break
		}

		lines = align(lines)
		j++
	}
286
	lines = align(lines)
287 288 289

	// add option types to output
	for i, opt := range options {
290
		lines[i] += " " + fmt.Sprintf("%v", opt.Type)
291 292 293 294 295
	}
	lines = align(lines)

	// add option descriptions to output
	for i, opt := range options {
296 297
		lines[i] += " - " + opt.Description
		lines[i] = indentString(lines[i], "    ")
298 299 300 301 302 303 304
	}

	return lines
}

func subcommandText(cmd *cmds.Command, rootName string, path []string) []string {
	prefix := fmt.Sprintf("%v %v", rootName, strings.Join(path, " "))
305 306 307
	if len(path) > 0 {
		prefix += " "
	}
308 309 310 311 312
	lines := make([]string, len(cmd.Subcommands))

	i := 0
	for name, sub := range cmd.Subcommands {
		usage := usageText(sub)
313 314
		lines[i] = fmt.Sprintf("%v%v %v - %v", prefix, name, usage, sub.Description)
		lines[i] = indentString(lines[i], "    ")
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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
		i++
	}

	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 {
376
	return prefix + strings.Replace(line, "\n", "\n"+prefix, -1)
377
}