Combine bool short names

Adds the ability to allow the combination of bool
short-name options.  For example,

cmd foobar -ov

This is done through a bool "UseShortOptionHandler" set in
the command struct.

Built upon PR #621

Signed-off-by: baude <bbaude@redhat.com>
This commit is contained in:
baude
2017-11-13 15:28:23 -06:00
parent 43c8c02cf5
commit fd5382e7a5
4 changed files with 82 additions and 26 deletions

View File

@@ -55,6 +55,10 @@ type Command struct {
HideHelp bool
// Boolean to hide this command from help or completion
Hidden bool
// Boolean to enable short-option handling so user can combine several
// single-character bool arguements into one
// i.e. foobar -o -v -> foobar -ov
UseShortOptionHandling bool
// Full name of command for help, defaults to full command name, including parent commands.
HelpName string
@@ -141,20 +145,22 @@ func (c Command) Run(ctx *Context) (err error) {
} else {
flagArgs = args[firstFlagIndex:]
}
// separate combined flags
var flagArgsSeparated []string
for _, flagArg := range flagArgs {
if strings.HasPrefix(flagArg, "-") && strings.HasPrefix(flagArg, "--") == false && len(flagArg) >2 {
for _, flagChar := range flagArg[1:] {
flagArgsSeparated = append(flagArgsSeparated, "-" + string(flagChar))
if c.UseShortOptionHandling {
var flagArgsSeparated []string
for _, flagArg := range flagArgs {
if strings.HasPrefix(flagArg, "-") && strings.HasPrefix(flagArg, "--") == false && len(flagArg) > 2 {
for _, flagChar := range flagArg[1:] {
flagArgsSeparated = append(flagArgsSeparated, "-"+string(flagChar))
}
} else {
flagArgsSeparated = append(flagArgsSeparated, flagArg)
}
} else {
flagArgsSeparated = append(flagArgsSeparated, flagArg)
}
err = set.Parse(append(flagArgsSeparated, regularArgs...))
} else {
err = set.Parse(append(flagArgs, regularArgs...))
}
err = set.Parse(append(flagArgsSeparated, regularArgs...))
} else {
err = set.Parse(ctx.Args().Tail())
}