go-arg/usage.go

109 lines
2.4 KiB
Go
Raw Normal View History

2015-10-31 20:32:20 -05:00
package arg
import (
"fmt"
"io"
"os"
2015-11-01 01:57:26 -05:00
"path/filepath"
2015-10-31 20:32:20 -05:00
"reflect"
"strings"
)
// Fail prints usage information to stderr and exits with non-zero status
func (p *Parser) Fail(msg string) {
p.WriteUsage(os.Stderr)
fmt.Fprintln(os.Stderr, "error:", msg)
os.Exit(-1)
2015-10-31 20:32:20 -05:00
}
// WriteUsage writes usage information to the given writer
func (p *Parser) WriteUsage(w io.Writer) {
2015-10-31 20:32:20 -05:00
var positionals, options []*spec
for _, spec := range p.spec {
2015-10-31 20:32:20 -05:00
if spec.positional {
positionals = append(positionals, spec)
} else {
options = append(options, spec)
}
}
fmt.Fprintf(w, "usage: %s", filepath.Base(os.Args[0]))
2015-10-31 20:32:20 -05:00
// write the option component of the usage message
2015-10-31 20:32:20 -05:00
for _, spec := range options {
// prefix with a space
fmt.Fprint(w, " ")
2015-10-31 20:32:20 -05:00
if !spec.required {
fmt.Fprint(w, "[")
}
fmt.Fprint(w, synopsis(spec, "--"+spec.long))
if !spec.required {
fmt.Fprint(w, "]")
}
}
// write the positional component of the usage message
2015-10-31 20:32:20 -05:00
for _, spec := range positionals {
// prefix with a space
fmt.Fprint(w, " ")
2015-10-31 20:32:20 -05:00
up := strings.ToUpper(spec.long)
if spec.multiple {
2015-10-31 20:48:38 -05:00
fmt.Fprintf(w, "[%s [%s ...]]", up, up)
2015-10-31 20:32:20 -05:00
} else {
fmt.Fprint(w, up)
}
}
fmt.Fprint(w, "\n")
}
// WriteHelp writes the usage string followed by the full help string for each option
func (p *Parser) WriteHelp(w io.Writer) {
var positionals, options []*spec
for _, spec := range p.spec {
if spec.positional {
positionals = append(positionals, spec)
} else {
options = append(options, spec)
}
}
p.WriteUsage(w)
2015-10-31 20:32:20 -05:00
// write the list of positionals
if len(positionals) > 0 {
fmt.Fprint(w, "\npositional arguments:\n")
for _, spec := range positionals {
fmt.Fprintf(w, " %s\n", spec.long)
}
}
// write the list of options
if len(options) > 0 {
fmt.Fprint(w, "\noptions:\n")
const colWidth = 25
for _, spec := range options {
left := " " + synopsis(spec, "--"+spec.long)
2015-10-31 20:32:20 -05:00
if spec.short != "" {
left += ", " + synopsis(spec, "-"+spec.short)
2015-10-31 20:32:20 -05:00
}
2015-11-04 11:47:58 -06:00
fmt.Fprint(w, left)
2015-10-31 20:32:20 -05:00
if spec.help != "" {
if len(left)+2 < colWidth {
fmt.Fprint(w, strings.Repeat(" ", colWidth-len(left)))
} else {
fmt.Fprint(w, "\n"+strings.Repeat(" ", colWidth))
}
fmt.Fprint(w, spec.help)
}
fmt.Fprint(w, "\n")
}
}
}
2015-11-01 01:57:26 -05:00
func synopsis(spec *spec, form string) string {
if spec.dest.Kind() == reflect.Bool {
return form
}
2015-11-11 07:08:28 -06:00
return form + " " + strings.ToUpper(spec.long)
2015-11-01 01:57:26 -05:00
}