spf13 / pflag

Drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.
BSD 3-Clause "New" or "Revised" License
2.38k stars 345 forks source link

Return an error if the same flag is provided twice with different values #72

Open ncw opened 8 years ago

ncw commented 8 years ago

In ncw/rclone#506 a user is rightly complaining about the fact that two --exclude flags don't work in rclone and it didn't warn him.

Could pflag return an error if you provide the same flag twice with different values?

Thanks

Nick

eparis commented 7 years ago

I feel like that is a custom flag type. I don't know of any unix command that complains when the same flag is given twice. All of them I know of either use both values or the last value, depending on the type of flag...

ncw commented 7 years ago

Now that pflag supports StringArray and friends I'm now using those in rclone so this issue is less important for me personally now.

However duplicated flags especially with arguments, when the parser can't cope with them, should make an error. Just because getopt(3) is lazy doesn't mean we have to be!

dixudx commented 6 years ago

I think we should apply this as default for all non-sliced types.

PTAL #151. I introduced a new method AllowingMultipleSet() to Flag. For all sliced/array types, this function is enforced as default.

normanr commented 4 years ago

I feel like that is a custom flag type. I don't know of any unix command that complains when the same flag is given twice. All of them I know of either use both values or the last value, depending on the type of flag...

here's an example (not a core unix command, but it's on most systems these days)

$ ssh localhost -W host:1234 -W host:1235
stdio forward already specified
niamster commented 3 months ago

I upvote this feature request.

Here's my use case: depending on the context of a sub-command, some flags might have different meaning. In one case --foo can be given only once, while in other cases --foo might be given multiple times. It might be confusing for a user if it's allowed to specify multiple --foo but only the last value is used. I agree that it's reasonable to argue that it might be a bad design, but in some cases reworking an application to add a new flag --foos or converting all --foo to array and checking the length manually and failing if len(foo) != 1 might not be acceptable either.

The other use case is that the users might copy/paste or reuse commands from history and modify some of the arguments. It might happen that the command looks like --foo --bar ..... --zoo=A and the user wants to replace --bar with --bin --zoo=B. The user might be surprised by the result.

I'm happy to help designing this feature and working on PRs. It seems like it's a reasonably small change, it's possible to reuse existing Changed field https://github.com/spf13/pflag/blob/d5e0c0615acee7028e1e2740a11102313be88de1/flag.go#L481