ogier/pflag

Use default value for non-bool flag when there's no value supplied

Opened this issue · 7 comments

Currently only flag.Bool can be used as --flag without supplying a value. There's some situation when non-bool flag should be able to use default value when no value was supplied.

E.g. the ls command in coreutils have a --color string flag. When there's no value supplied, it assume to be always. Right now there's no way to do the same using pflag

First, http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/ls.c#n542 seems to indicate that color_never is default. Regardless...

var color = flag.String("color", "always", "print with color!")
...
if *color != "always" {
    // handle properly
}

...works as intended.

No it's not the intended behaviour.

With ls you can do ls --color and it will interpret as ls --color=always.

To be more specific, I want to be able to mark a flag as optional_argument provided in getopt.h, like how color flag was handled in ls http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/ls.c#n845

Yeah, you're right. I went over this earlier today (not at 1 AM like last night 😄) and realized what you meant.

I think there are some hacky workarounds, but they're just that -- hacky.

If I understand correctly, you'd like to be able to specify the value of a flag provided without an argument, in the same way that a bool flag without an argument is assumed to be true.

Can I ask, do you need to know after parsing whether an argument was provided or not? Or is it enough just to have some implicit default the way we do with bool flags. For example, it looks like with getopt one can check whether there is an argument supplied at all: http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/ls.c#n1869

I'm trying to do everything getopt_long can do to be used in go-coreutils project. It's nice to distinguish between "flag present without argument" and "flag not present" but for now I'm fine to assume "flag not present" is equal to "flag present without argument".

If there's any workaround without radical change to pflag project I'm happy to use as well

spf13/pflag (a fork of ogier) has this support. See https://github.com/spf13/pflag#setting-no-option-default-values-for-flags