spf13 / pflag

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

Keep hold of unknown flags if they are allowed #186

Open NearlyUnique opened 6 years ago

NearlyUnique commented 6 years ago

When FlagSet::ParseErrorsWhitelist.UnknownFlags = true unknown flags are thrown away.

I propose adding a map of UnknownFlags to FlagSet which is populated when the option (above) is set

The map would be keyed on flag name and keep any and all values found as strings (given there is no sensible way to try and guess their type)

The use case (for me) is an capturing name value pairs that are dependent on dynamic templates.

I have a work in progress version for which I will submit a PR

eparis commented 6 years ago

Initial thought, I'm not sure a map[string]string is a good storage type as it would lose repeated entries. Aka if you had --unknownflag=1 --unknownflag=2 your map would overwrite the first unknown flag with the second, right? Also, I'm not sure how you tell any and all values with unknown flags. But I guess anyone using unknown flags already knows they are riding on the edge of failure/brittleness.

NearlyUnique commented 6 years ago

I actually have (so far, it's just an experiment) a map of slices containing Value + IsShort pairs. Storing the empty value and the short or long-ness of the flag is just because the information was there. The only addition I considered we the index they were read from, however I'm not sure that is readily available (and it's not something I need) . I will tidy up my fork and submit the PR for review

The scenario I am thinking about is for developers thinking;

pflags has gone to the effort of parsing the command line args, and allowing unknown flags to be ignored but some some reason I've like to collect these flags and values and I'll take full responsibility for dealing with them.


type struct UnknownValue{Value string, isShort bool}

type FlagSet struct { // snip ... UnknownValues map[string][]UnknownValue }

NearlyUnique commented 5 years ago

PR https://github.com/spf13/pflag/pull/187 is solving my issue. I'm not sure if/how it'll get merged

amterp commented 1 week ago

Would be interested in this, and there appears to be quite a lot of interest over on #160 as well. Looks like the PR never got looked at unfortunately?