pflag icon indicating copy to clipboard operation
pflag copied to clipboard

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

Open yegle opened this issue 9 years ago • 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

yegle avatar Feb 26 '15 05:02 yegle

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.

ericlagergren avatar Feb 26 '15 07:02 ericlagergren

No it's not the intended behaviour.

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

yegle avatar Feb 26 '15 15:02 yegle

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

yegle avatar Feb 27 '15 01:02 yegle

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

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

ericlagergren avatar Feb 27 '15 01:02 ericlagergren

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

ogier avatar Feb 28 '15 10:02 ogier

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

yegle avatar Feb 28 '15 17:02 yegle

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

eparis avatar Aug 15 '15 05:08 eparis