Merge pull request #339 from bogem/fixes

Some fixes
This commit is contained in:
Eric Paris 2016-08-30 13:49:25 -04:00 committed by GitHub
commit 9c28e4bbd7
3 changed files with 67 additions and 70 deletions

View File

@ -401,10 +401,8 @@ func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error {
format += "=" format += "="
} }
format += "\")\n" format += "\")\n"
if _, err := fmt.Fprintf(w, format, name); err != nil { _, err := fmt.Fprintf(w, format, name)
return err return err
}
return nil
} }
func writeFlags(cmd *Command, w io.Writer) error { func writeFlags(cmd *Command, w io.Writer) error {

View File

@ -37,38 +37,36 @@ var templateFuncs = template.FuncMap{
var initializers []func() var initializers []func()
// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools. // Automatic prefix matching can be a dangerous thing to automatically enable in CLI tools.
// Set this to true to enable it // Set this to true to enable it.
var EnablePrefixMatching = false var EnablePrefixMatching = false
//EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. // EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
//To disable sorting, set it to false. // To disable sorting, set it to false.
var EnableCommandSorting = true var EnableCommandSorting = true
//AddTemplateFunc adds a template function that's available to Usage and Help // AddTemplateFunc adds a template function that's available to Usage and Help
//template generation. // template generation.
func AddTemplateFunc(name string, tmplFunc interface{}) { func AddTemplateFunc(name string, tmplFunc interface{}) {
templateFuncs[name] = tmplFunc templateFuncs[name] = tmplFunc
} }
//AddTemplateFuncs adds multiple template functions availalble to Usage and // AddTemplateFuncs adds multiple template functions availalble to Usage and
//Help template generation. // Help template generation.
func AddTemplateFuncs(tmplFuncs template.FuncMap) { func AddTemplateFuncs(tmplFuncs template.FuncMap) {
for k, v := range tmplFuncs { for k, v := range tmplFuncs {
templateFuncs[k] = v templateFuncs[k] = v
} }
} }
//OnInitialize takes a series of func() arguments and appends them to a slice of func(). // OnInitialize takes a series of func() arguments and appends them to a slice of func().
func OnInitialize(y ...func()) { func OnInitialize(y ...func()) {
for _, x := range y { initializers = append(initializers, y...)
initializers = append(initializers, x)
}
} }
//Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, // Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
//Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as // Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
//ints and then compared. // ints and then compared.
func Gt(a interface{}, b interface{}) bool { func Gt(a interface{}, b interface{}) bool {
var left, right int64 var left, right int64
av := reflect.ValueOf(a) av := reflect.ValueOf(a)
@ -96,7 +94,7 @@ func Gt(a interface{}, b interface{}) bool {
return left > right return left > right
} }
//Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic. // Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
func Eq(a interface{}, b interface{}) bool { func Eq(a interface{}, b interface{}) bool {
av := reflect.ValueOf(a) av := reflect.ValueOf(a)
bv := reflect.ValueOf(b) bv := reflect.ValueOf(b)
@ -116,7 +114,7 @@ func trimRightSpace(s string) string {
return strings.TrimRightFunc(s, unicode.IsSpace) return strings.TrimRightFunc(s, unicode.IsSpace)
} }
// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s // appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
func appendIfNotPresent(s, stringToAppend string) string { func appendIfNotPresent(s, stringToAppend string) string {
if strings.Contains(s, stringToAppend) { if strings.Contains(s, stringToAppend) {
return s return s
@ -124,7 +122,7 @@ func appendIfNotPresent(s, stringToAppend string) string {
return s + " " + stringToAppend return s + " " + stringToAppend
} }
//rpad adds padding to the right of a string // rpad adds padding to the right of a string.
func rpad(s string, padding int) string { func rpad(s string, padding int) string {
template := fmt.Sprintf("%%-%ds", padding) template := fmt.Sprintf("%%-%ds", padding)
return fmt.Sprintf(template, s) return fmt.Sprintf(template, s)
@ -138,7 +136,7 @@ func tmpl(w io.Writer, text string, data interface{}) error {
return t.Execute(w, data) return t.Execute(w, data)
} }
// ld compares two strings and returns the levenshtein distance between them // ld compares two strings and returns the levenshtein distance between them.
func ld(s, t string, ignoreCase bool) int { func ld(s, t string, ignoreCase bool) int {
if ignoreCase { if ignoreCase {
s = strings.ToLower(s) s = strings.ToLower(s)

View File

@ -140,17 +140,17 @@ func (c *Command) SetOutput(output io.Writer) {
c.output = &output c.output = &output
} }
// Usage can be defined by application // Usage can be defined by application.
func (c *Command) SetUsageFunc(f func(*Command) error) { func (c *Command) SetUsageFunc(f func(*Command) error) {
c.usageFunc = f c.usageFunc = f
} }
// Can be defined by Application // Can be defined by Application.
func (c *Command) SetUsageTemplate(s string) { func (c *Command) SetUsageTemplate(s string) {
c.usageTemplate = s c.usageTemplate = s
} }
// Can be defined by Application // Can be defined by Application.
func (c *Command) SetHelpFunc(f func(*Command, []string)) { func (c *Command) SetHelpFunc(f func(*Command, []string)) {
c.helpFunc = f c.helpFunc = f
} }
@ -159,7 +159,7 @@ func (c *Command) SetHelpCommand(cmd *Command) {
c.helpCommand = cmd c.helpCommand = cmd
} }
// Can be defined by Application // Can be defined by Application.
func (c *Command) SetHelpTemplate(s string) { func (c *Command) SetHelpTemplate(s string) {
c.helpTemplate = s c.helpTemplate = s
} }
@ -195,7 +195,7 @@ func (c *Command) getOut(def io.Writer) io.Writer {
} }
// UsageFunc returns either the function set by SetUsageFunc for this command // UsageFunc returns either the function set by SetUsageFunc for this command
// or a parent, or it returns a default usage function // or a parent, or it returns a default usage function.
func (c *Command) UsageFunc() (f func(*Command) error) { func (c *Command) UsageFunc() (f func(*Command) error) {
if c.usageFunc != nil { if c.usageFunc != nil {
return c.usageFunc return c.usageFunc
@ -214,15 +214,15 @@ func (c *Command) UsageFunc() (f func(*Command) error) {
} }
} }
// Output the usage for the command // Usage puts out the usage for the command.
// Used when a user provides invalid input // Used when a user provides invalid input.
// Can be defined by user by overriding UsageFunc // Can be defined by user by overriding UsageFunc.
func (c *Command) Usage() error { func (c *Command) Usage() error {
return c.UsageFunc()(c) return c.UsageFunc()(c)
} }
// HelpFunc returns either the function set by SetHelpFunc for this command // HelpFunc returns either the function set by SetHelpFunc for this command
// or a parent, or it returns a function with default help behavior // or a parent, or it returns a function with default help behavior.
func (c *Command) HelpFunc() func(*Command, []string) { func (c *Command) HelpFunc() func(*Command, []string) {
cmd := c cmd := c
for cmd != nil { for cmd != nil {
@ -240,9 +240,9 @@ func (c *Command) HelpFunc() func(*Command, []string) {
} }
} }
// Output the help for the command // Help puts out the help for the command.
// Used when a user calls help [command] // Used when a user calls help [command].
// Can be defined by user by overriding HelpFunc // Can be defined by user by overriding HelpFunc.
func (c *Command) Help() error { func (c *Command) Help() error {
c.HelpFunc()(c, []string{}) c.HelpFunc()(c, []string{})
return nil return nil
@ -333,7 +333,7 @@ func (c *Command) HelpTemplate() string {
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
} }
// Really only used when casting a command to a commander // Really only used when casting a command to a commander.
func (c *Command) resetChildrensParents() { func (c *Command) resetChildrensParents() {
for _, x := range c.commands { for _, x := range c.commands {
x.parent = c x.parent = c
@ -745,13 +745,13 @@ func (c *Command) initHelpCmd() {
c.AddCommand(c.helpCommand) c.AddCommand(c.helpCommand)
} }
// Used for testing // Used for testing.
func (c *Command) ResetCommands() { func (c *Command) ResetCommands() {
c.commands = nil c.commands = nil
c.helpCommand = nil c.helpCommand = nil
} }
// Sorts commands by their names // Sorts commands by their names.
type commandSorterByName []*Command type commandSorterByName []*Command
func (c commandSorterByName) Len() int { return len(c) } func (c commandSorterByName) Len() int { return len(c) }
@ -831,18 +831,18 @@ main:
} }
} }
// Print is a convenience method to Print to the defined output, fallback to Stderr if not set // Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
func (c *Command) Print(i ...interface{}) { func (c *Command) Print(i ...interface{}) {
fmt.Fprint(c.OutOrStderr(), i...) fmt.Fprint(c.OutOrStderr(), i...)
} }
// Println is a convenience method to Println to the defined output, fallback to Stderr if not set // Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
func (c *Command) Println(i ...interface{}) { func (c *Command) Println(i ...interface{}) {
str := fmt.Sprintln(i...) str := fmt.Sprintln(i...)
c.Print(str) c.Print(str)
} }
// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set // Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
func (c *Command) Printf(format string, i ...interface{}) { func (c *Command) Printf(format string, i ...interface{}) {
str := fmt.Sprintf(format, i...) str := fmt.Sprintf(format, i...)
c.Print(str) c.Print(str)
@ -859,7 +859,7 @@ func (c *Command) CommandPath() string {
return str return str
} }
//The full usage for a given command (including parents) // UseLine puts out the full usage for a given command (including parents).
func (c *Command) UseLine() string { func (c *Command) UseLine() string {
str := "" str := ""
if c.HasParent() { if c.HasParent() {
@ -869,7 +869,7 @@ func (c *Command) UseLine() string {
} }
// For use in determining which flags have been assigned to which commands // For use in determining which flags have been assigned to which commands
// and which persist // and which persist.
func (c *Command) DebugFlags() { func (c *Command) DebugFlags() {
c.Println("DebugFlags called on", c.Name()) c.Println("DebugFlags called on", c.Name())
var debugflags func(*Command) var debugflags func(*Command)
@ -944,18 +944,18 @@ func (c *Command) HasExample() bool {
return len(c.Example) > 0 return len(c.Example) > 0
} }
// Runnable determines if the command is itself runnable // Runnable determines if the command is itself runnable.
func (c *Command) Runnable() bool { func (c *Command) Runnable() bool {
return c.Run != nil || c.RunE != nil return c.Run != nil || c.RunE != nil
} }
// HasSubCommands determines if the command has children commands // HasSubCommands determines if the command has children commands.
func (c *Command) HasSubCommands() bool { func (c *Command) HasSubCommands() bool {
return len(c.commands) > 0 return len(c.commands) > 0
} }
// IsAvailableCommand determines if a command is available as a non-help command // IsAvailableCommand determines if a command is available as a non-help command
// (this includes all non deprecated/hidden commands) // (this includes all non deprecated/hidden commands).
func (c *Command) IsAvailableCommand() bool { func (c *Command) IsAvailableCommand() bool {
if len(c.Deprecated) != 0 || c.Hidden { if len(c.Deprecated) != 0 || c.Hidden {
return false return false
@ -974,7 +974,7 @@ func (c *Command) IsAvailableCommand() bool {
// IsHelpCommand determines if a command is a 'help' command; a help command is // IsHelpCommand determines if a command is a 'help' command; a help command is
// determined by the fact that it is NOT runnable/hidden/deprecated, and has no // determined by the fact that it is NOT runnable/hidden/deprecated, and has no
// sub commands that are runnable/hidden/deprecated // sub commands that are runnable/hidden/deprecated.
func (c *Command) IsHelpCommand() bool { func (c *Command) IsHelpCommand() bool {
// if a command is runnable, deprecated, or hidden it is not a 'help' command // if a command is runnable, deprecated, or hidden it is not a 'help' command
@ -995,7 +995,7 @@ func (c *Command) IsHelpCommand() bool {
// HasHelpSubCommands determines if a command has any available 'help' sub commands // HasHelpSubCommands determines if a command has any available 'help' sub commands
// that need to be shown in the usage/help default template under 'additional help // that need to be shown in the usage/help default template under 'additional help
// topics' // topics'.
func (c *Command) HasHelpSubCommands() bool { func (c *Command) HasHelpSubCommands() bool {
// return true on the first found available 'help' sub command // return true on the first found available 'help' sub command
@ -1010,7 +1010,7 @@ func (c *Command) HasHelpSubCommands() bool {
} }
// HasAvailableSubCommands determines if a command has available sub commands that // HasAvailableSubCommands determines if a command has available sub commands that
// need to be shown in the usage/help default template under 'available commands' // need to be shown in the usage/help default template under 'available commands'.
func (c *Command) HasAvailableSubCommands() bool { func (c *Command) HasAvailableSubCommands() bool {
// return true on the first found available (non deprecated/help/hidden) // return true on the first found available (non deprecated/help/hidden)
@ -1026,17 +1026,18 @@ func (c *Command) HasAvailableSubCommands() bool {
return false return false
} }
// Determine if the command is a child command // HasParent determines if the command is a child command.
func (c *Command) HasParent() bool { func (c *Command) HasParent() bool {
return c.parent != nil return c.parent != nil
} }
// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists // GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.
func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
return c.globNormFunc return c.globNormFunc
} }
// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents) // Flage returns the complete FlagSet that applies
// to this command (local and persistent declared here and by all parents).
func (c *Command) Flags() *flag.FlagSet { func (c *Command) Flags() *flag.FlagSet {
if c.flags == nil { if c.flags == nil {
c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
@ -1048,7 +1049,7 @@ func (c *Command) Flags() *flag.FlagSet {
return c.flags return c.flags
} }
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands // LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
persistentFlags := c.PersistentFlags() persistentFlags := c.PersistentFlags()
@ -1061,7 +1062,7 @@ func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
return out return out
} }
// Get the local FlagSet specifically set in the current command // LocalFlags returns the local FlagSet specifically set in the current command.
func (c *Command) LocalFlags() *flag.FlagSet { func (c *Command) LocalFlags() *flag.FlagSet {
c.mergePersistentFlags() c.mergePersistentFlags()
@ -1079,7 +1080,7 @@ func (c *Command) LocalFlags() *flag.FlagSet {
return local return local
} }
// All Flags which were inherited from parents commands // InheritedFlags returns all flags which were inherited from parents commands.
func (c *Command) InheritedFlags() *flag.FlagSet { func (c *Command) InheritedFlags() *flag.FlagSet {
c.mergePersistentFlags() c.mergePersistentFlags()
@ -1108,12 +1109,12 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
return inherited return inherited
} }
// All Flags which were not inherited from parent commands // NonInheritedFlags returns all flags which were not inherited from parent commands.
func (c *Command) NonInheritedFlags() *flag.FlagSet { func (c *Command) NonInheritedFlags() *flag.FlagSet {
return c.LocalFlags() return c.LocalFlags()
} }
// Get the Persistent FlagSet specifically set in the current command // PersistentFlags returns the persistent FlagSet specifically set in the current command.
func (c *Command) PersistentFlags() *flag.FlagSet { func (c *Command) PersistentFlags() *flag.FlagSet {
if c.pflags == nil { if c.pflags == nil {
c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
@ -1125,7 +1126,7 @@ func (c *Command) PersistentFlags() *flag.FlagSet {
return c.pflags return c.pflags
} }
// For use in testing // ResetFlags is used in testing.
func (c *Command) ResetFlags() { func (c *Command) ResetFlags() {
c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf = new(bytes.Buffer)
c.flagErrorBuf.Reset() c.flagErrorBuf.Reset()
@ -1135,50 +1136,50 @@ func (c *Command) ResetFlags() {
c.pflags.SetOutput(c.flagErrorBuf) c.pflags.SetOutput(c.flagErrorBuf)
} }
// Does the command contain any flags (local plus persistent from the entire structure) // Does the command contain any flags (local plus persistent from the entire structure).
func (c *Command) HasFlags() bool { func (c *Command) HasFlags() bool {
return c.Flags().HasFlags() return c.Flags().HasFlags()
} }
// Does the command contain persistent flags // Does the command contain persistent flags.
func (c *Command) HasPersistentFlags() bool { func (c *Command) HasPersistentFlags() bool {
return c.PersistentFlags().HasFlags() return c.PersistentFlags().HasFlags()
} }
// Does the command has flags specifically declared locally // Does the command has flags specifically declared locally.
func (c *Command) HasLocalFlags() bool { func (c *Command) HasLocalFlags() bool {
return c.LocalFlags().HasFlags() return c.LocalFlags().HasFlags()
} }
// Does the command have flags inherited from its parent command // Does the command have flags inherited from its parent command.
func (c *Command) HasInheritedFlags() bool { func (c *Command) HasInheritedFlags() bool {
return c.InheritedFlags().HasFlags() return c.InheritedFlags().HasFlags()
} }
// Does the command contain any flags (local plus persistent from the entire // Does the command contain any flags (local plus persistent from the entire
// structure) which are not hidden or deprecated // structure) which are not hidden or deprecated.
func (c *Command) HasAvailableFlags() bool { func (c *Command) HasAvailableFlags() bool {
return c.Flags().HasAvailableFlags() return c.Flags().HasAvailableFlags()
} }
// Does the command contain persistent flags which are not hidden or deprecated // Does the command contain persistent flags which are not hidden or deprecated.
func (c *Command) HasAvailablePersistentFlags() bool { func (c *Command) HasAvailablePersistentFlags() bool {
return c.PersistentFlags().HasAvailableFlags() return c.PersistentFlags().HasAvailableFlags()
} }
// Does the command has flags specifically declared locally which are not hidden // Does the command has flags specifically declared locally which are not hidden
// or deprecated // or deprecated.
func (c *Command) HasAvailableLocalFlags() bool { func (c *Command) HasAvailableLocalFlags() bool {
return c.LocalFlags().HasAvailableFlags() return c.LocalFlags().HasAvailableFlags()
} }
// Does the command have flags inherited from its parent command which are // Does the command have flags inherited from its parent command which are
// not hidden or deprecated // not hidden or deprecated.
func (c *Command) HasAvailableInheritedFlags() bool { func (c *Command) HasAvailableInheritedFlags() bool {
return c.InheritedFlags().HasAvailableFlags() return c.InheritedFlags().HasAvailableFlags()
} }
// Flag climbs up the command tree looking for matching flag // Flag climbs up the command tree looking for matching flag.
func (c *Command) Flag(name string) (flag *flag.Flag) { func (c *Command) Flag(name string) (flag *flag.Flag) {
flag = c.Flags().Lookup(name) flag = c.Flags().Lookup(name)
@ -1189,7 +1190,7 @@ func (c *Command) Flag(name string) (flag *flag.Flag) {
return return
} }
// recursively find matching persistent flag // Recursively find matching persistent flag.
func (c *Command) persistentFlag(name string) (flag *flag.Flag) { func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
if c.HasPersistentFlags() { if c.HasPersistentFlags() {
flag = c.PersistentFlags().Lookup(name) flag = c.PersistentFlags().Lookup(name)
@ -1201,7 +1202,7 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
return return
} }
// ParseFlags parses persistent flag tree & local flags // ParseFlags parses persistent flag tree and local flags.
func (c *Command) ParseFlags(args []string) (err error) { func (c *Command) ParseFlags(args []string) (err error) {
if c.DisableFlagParsing { if c.DisableFlagParsing {
return nil return nil
@ -1211,7 +1212,7 @@ func (c *Command) ParseFlags(args []string) (err error) {
return return
} }
// Parent returns a commands parent command // Parent returns a commands parent command.
func (c *Command) Parent() *Command { func (c *Command) Parent() *Command {
return c.parent return c.parent
} }