Option types: bool int, int-array, string, string-array, string-map, file, dir
87 lines
2.1 KiB
Go
87 lines
2.1 KiB
Go
package cli
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
// Usage()
|
|
func (cli *CliParser) Usage() string {
|
|
var sb strings.Builder
|
|
|
|
program, _ := cli.GetVersionSection("program")
|
|
publicCount := cli.publicOptionCount()
|
|
if publicCount > 0 {
|
|
fmt.Fprintf(&sb, "USAGE: %s [<options>] %s\n", program, cli.getArgsTemplate())
|
|
} else {
|
|
fmt.Fprintf(&sb, "USAGE: %s %s\n", program, cli.getArgsTemplate())
|
|
}
|
|
|
|
if len(cli.argSpecs) > 0 || len(cli.options) > 0 {
|
|
fmt.Fprintf(&sb, "where:\n")
|
|
if len(cli.argSpecs) > 0 {
|
|
for _, argSpec := range cli.argSpecs {
|
|
arg := argSpec.getBase()
|
|
fmt.Fprintf(&sb, " <%s> %s\n", arg.name, arg.description)
|
|
}
|
|
}
|
|
if publicCount > 0 {
|
|
fmt.Fprintf(&sb, " <options>\n")
|
|
templates, maxWidth := cli.makeOptionTemplateList()
|
|
for i, opti := range cli.options {
|
|
if opti.isHidden() {
|
|
continue
|
|
}
|
|
opt := opti.getBase()
|
|
aliases := opt.aliases
|
|
if len(aliases) > 0 && opt.isArray {
|
|
// Skip the last alias because it is the implicit plural alias
|
|
aliases = aliases[0 : len(aliases)-1]
|
|
}
|
|
if len(aliases) > 0 {
|
|
fmt.Fprintf(&sb, " %-*s %s (alias: %s)", maxWidth, templates[i], opt.description, strings.Join(aliases, ", "))
|
|
} else {
|
|
fmt.Fprintf(&sb, " %-*s %s", maxWidth, templates[i], opt.description)
|
|
}
|
|
if value := opti.getDefaultValue(); value != "" {
|
|
fmt.Fprintf(&sb, " (default: %q)", value)
|
|
}
|
|
sb.WriteByte('\n')
|
|
}
|
|
}
|
|
}
|
|
return sb.String()
|
|
}
|
|
|
|
func (cli *CliParser) publicOptionCount() (count int) {
|
|
for _, opti := range cli.options {
|
|
opt := opti.getBase()
|
|
if !opt.hidden {
|
|
count++
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func (cli *CliParser) makeOptionTemplateList() (templates []string, maxWidth int) {
|
|
maxWidth = 0
|
|
templates = make([]string, len(cli.options))
|
|
for i, opti := range cli.options {
|
|
if opti.isHidden() {
|
|
templates[i] = ""
|
|
} else {
|
|
templates[i] = opti.getTemplate()
|
|
if len(templates[i]) > maxWidth {
|
|
maxWidth = len(templates[i])
|
|
}
|
|
}
|
|
}
|
|
return templates, maxWidth
|
|
}
|
|
|
|
// PrintUsage()
|
|
func (cli *CliParser) PrintUsage() {
|
|
os.Stdout.WriteString(cli.Usage())
|
|
}
|