urfave / cli

A simple, fast, and fun package for building command line apps in Go

Home Page:https://cli.urfave.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

combining `BoolFlags` into one using v2 does not work as expected

milaniez opened this issue · comments

I have a code that can get arguments of -f/--foo or -b/--bar. Argument parsing is done via v2 package. I can run my program like go run . -f -b but not like go run . -fb Is there a way that I make it work with go run . -fb? If it is not possible, what go module can make this possible?

code:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/urfave/cli/v2"
)

func main() {
    var foo_count, bar_count bool

    app := &cli.App{
        Flags: []cli.Flag{
            &cli.BoolFlag{
                Name:    "foo",
                Usage:   "Foo",
                Aliases: []string{"f"},
                Destination:   &foo_count,
            },
            &cli.BoolFlag{
                Name:    "bar",
                Usage:   "Bar",
                Aliases: []string{"b"},
                Destination:   &bar_count,
            },
        },
        Action: func(cCtx *cli.Context) error {
            fmt.Println("foo_count", foo_count)
            fmt.Println("bar_count", bar_count)
            return nil
        },
    }

    if err := app.Run(os.Args); err != nil {
        log.Fatal(err)
    }
}

tests:

$ go run . -f
foo_count true
bar_count false
$ go run . -b
foo_count false
bar_count true
$ go run . -bf
Incorrect Usage: flag provided but not defined: -bf

NAME:
   main - A new cli application

USAGE:
   main [global options] command [command options] [arguments...]

COMMANDS:
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --foo, -f   Foo (default: false)
   --bar, -b   Bar (default: false)
   --help, -h  show help
2023/03/25 15:54:00 flag provided but not defined: -bf
exit status 1

@milaniez You can set the UseShortOptionHandling flag in App to enable this behaviour.

https://github.com/urfave/cli/blob/v2-maint/app.go#L115