jessevdk / go-flags

go command line option parser
http://godoc.org/github.com/jessevdk/go-flags
BSD 3-Clause "New" or "Revised" License
2.59k stars 308 forks source link

Allowing values to be assigned to bools #366

Closed alexcb closed 4 months ago

alexcb commented 3 years ago

I would like to be able to pass a value to a bool flag. I would like to be able to pass the value of the boolean like:

./my-program --my-flag=true --my-other-flag=false

Which would be equivalent to calling:

./my-program --my-flag

I agree that the current flagging functionality is a lot cleaner than the additional functionality I'm proposing. However my use-case is to support my users who are calling my-program from a script (e.g. bash, python, etc.)

Here's an example of how I would like to use this functionality:


myfunc () {
  myflagvalue=$1
  myotherflagvalue=$2
  ./my-program --my-flag=$myflagvalue --my-other-flag=$myotherflagvalue
}

# then I might call it with the flags set or not:
myfunc "true" "false"
myfunc "false" "false"

Where as currently my users would have to write this instead:


myfunc () {
  myflagvalue=$1
  myotherflagvalue=$2
  if [ "$myflagvalue" = "true" ]; then
    if [ "$myotherflagvalue" = "true" ]; then
      ./my-program --my-flag --my-other-flag
    else
      ./my-program --my-flag
    fi
  else
    if [ "$myotherflagvalue" = "true" ]; then
      ./my-program --my-other-flag
    else
      ./my-program
    fi

  fi
}

# then I might call it with the flags set or not:
myfunc "true" "false"
myfunc "false" "false"

Note that in contrast to https://github.com/jessevdk/go-flags/issues/80 I am not suggesting the ability to change the default value of a bool flag.

If you're open to such a feature, I would be happy to contribute a PR and could make this functionality optional via a:

    // AllowBoolValues allows a user to assign true/false to a boolean value
    // rather than raising an error stating it cannot have an argument.
    AllowBoolValues

option.

(for reference my real use-case is to support https://github.com/earthly/earthly/issues/1109 and not bash, but it covers a very similar use-case).

fusioned commented 4 months ago

This issue has popped up many times in our use of TF and our infrastructure setup. There are many times when we need to be able to switch on and off parameters, but the templating within our systems are rudimentary, and we cannot simply perform an ifblock for applying the flag as-and-when. The workarounds for this affect many layers of configuration and becomes tedious.

jessevdk commented 4 months ago

Merged.

alexcb commented 4 months ago

welcome back @jessevdk, good to see you're still kicking.