Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bool should be able to be set false. #80

Closed
hfern opened this issue Jun 24, 2014 · 3 comments
Closed

Bool should be able to be set false. #80

hfern opened this issue Jun 24, 2014 · 3 comments

Comments

@hfern
Copy link

hfern commented Jun 24, 2014

If you have a bool option that defaults to true, there is no way of disabling it from the command line.

You should be able to do this by ./somecommand --boolflag=0

Right now running this results in: "bool flag boolflag cannot have an argument"

@GeertJohan
Copy link

When I need a bool that defaults to true, I inverted the meaning/name for the flag and still default to false.

For instance, at one point enabling TLS in a piece of software was optional:
EnableTLS bool long:"enable-tls" At a certain point I decided to make it enabled by default, and so the flag was inverted: `DisableTLS bool `long:"disable-tls"

This way, the bool always defaults to false and command line arguments are more descriptive (imo):
someCommand --disable-tls
versus
someCommand --enable-tls=0

@jessevdk
Copy link
Owner

I agree with GeertJohan here. bool flags are equivalent to flags without arguments in getopt, which simply turn things on. Apart from inverting the meaning of the flag, you can also just create your own boolean derived type which allows for what you want (if you really want to insist):

type Bool bool

func (b *Bool) UnmarshalFlag(value string) error {
    if value == "true" {
        *b = true
    } else if value == "false" {
        *b = false
    } else {
        return fmt.Errorf("only `true' and `false' are valid values, not `%s'", value)
    }

    return nil
}

func (b Bool) MarshalFlag() string {
    if b {
        return "true"
    }

    return "false"
}

@dmitshur
Copy link

When I need a bool that defaults to true, I inverted the meaning/name for the flag and still default to false.

I agree that's a better practice.

In that case, shouldn't go-flags detect it as an error (at init time) and refuse to work? A user of this package should not be able apply default:"true" to a bool flag if it renders the flag completely unfit for its purpose (i.e., able to have more than 1 different value).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants