-
Notifications
You must be signed in to change notification settings - Fork 8
fix: accept boolean flag values written with a space #1037
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
Open
JonJagger
wants to merge
2
commits into
main
Choose a base branch
from
fix-boolean-flag-space-separator
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "github.com/spf13/cobra" | ||
| "github.com/spf13/pflag" | ||
| ) | ||
|
|
||
| // normalizeBoolFlagArgs rewrites boolean flags written in the space form | ||
| // ("--compliant false") into the "=" form ("--compliant=false"), which is the | ||
| // only form pflag accepts for an explicitly-valued boolean flag. All other | ||
| // tokens are returned unchanged, as is everything following a "--" terminator. | ||
| // | ||
| // The rewrite is positional: it matches on the tokens themselves and does not | ||
| // track which of them pflag will consume as the value of an earlier flag. Two | ||
| // pathological inputs are therefore read differently from the way pflag reads | ||
| // them, and both are accepted. A positional argument literally named "true" or | ||
| // "false" directly after a bare boolean flag becomes that flag's value. And in | ||
| // "--name --compliant false", where pflag gives --name the value "--compliant" | ||
| // and leaves "false" positional, this rewrite instead produces | ||
| // "--compliant=false". Kosli positionals are artifact names, fingerprints and | ||
| // file paths, and flag values are not flag tokens, so both inputs are far | ||
| // enough outside real usage to be worth the plain forms this rescues. | ||
| func normalizeBoolFlagArgs(root *cobra.Command, args []string) []string { | ||
| cmd, _, err := root.Find(args) | ||
| if err != nil { | ||
| return args | ||
| } | ||
| boolFlags := boolFlagTokens(cmd) | ||
| normalized := make([]string, 0, len(args)) | ||
| for i := 0; i < len(args); i++ { | ||
| if args[i] == "--" { | ||
| // pflag stops parsing flags here, so everything left is a | ||
| // positional argument and must be passed through untouched. | ||
| normalized = append(normalized, args[i:]...) | ||
| break | ||
| } | ||
| if boolFlags[args[i]] && i+1 < len(args) && isBoolLiteral(args[i+1]) { | ||
|
JonJagger marked this conversation as resolved.
|
||
| normalized = append(normalized, args[i]+"="+args[i+1]) | ||
| i++ | ||
| continue | ||
| } | ||
| normalized = append(normalized, args[i]) | ||
| } | ||
| return normalized | ||
| } | ||
|
|
||
| // boolFlagTokens returns the command-line tokens ("--compliant", "-C") of every | ||
| // boolean flag known to cmd. | ||
| // | ||
| // Shorthands are listed individually, so a grouped token such as "-qC" is not a | ||
| // key here and "-qC false" is left alone: it keeps failing with the arg-count | ||
| // error and its link to the boolean flags FAQ. That is a deliberate choice. | ||
| // Grouping raises questions this rewrite has no good answer to, such as which | ||
| // member of the group the value belongs to and what to do when a group mixes | ||
| // boolean and non-boolean shorthands. Rescuing the plain forms is worth a | ||
| // low-level rewrite; guessing intent inside a grouped token is not. | ||
| func boolFlagTokens(cmd *cobra.Command) map[string]bool { | ||
| tokens := map[string]bool{} | ||
| cmd.Flags().VisitAll(func(flag *pflag.Flag) { | ||
| if flag.Value.Type() != "bool" { | ||
| return | ||
| } | ||
| tokens["--"+flag.Name] = true | ||
| if flag.Shorthand != "" { | ||
| tokens["-"+flag.Shorthand] = true | ||
| } | ||
| }) | ||
| return tokens | ||
| } | ||
|
|
||
| // isBoolLiteral reports whether token is one of the two values a rewritten | ||
| // boolean flag may be given. | ||
| func isBoolLiteral(token string) bool { | ||
| return token == "true" || token == "false" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "io" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| // TestNormalizeBoolFlagArgsLeavesTrailingBareBoolFlagAlone covers the boundary | ||
| // where a boolean flag is the final token, so there is no following token to | ||
| // consider joining. The bare form keeps its NoOptDefVal of true. | ||
| func TestNormalizeBoolFlagArgsLeavesTrailingBareBoolFlagAlone(t *testing.T) { | ||
| args := []string{ | ||
| "fingerprint", "testdata/person-schema.json", | ||
| "--artifact-type", "file", | ||
| "--debug", | ||
| } | ||
| root, err := newRootCmd(io.Discard, io.Discard, args) | ||
| require.NoError(t, err) | ||
|
|
||
| normalized := normalizeBoolFlagArgs(root, args) | ||
|
|
||
| require.Equal(t, args, normalized) | ||
| } | ||
|
|
||
| // TestNormalizeBoolFlagArgsLeavesGroupedShorthandsAlone pins the deliberate | ||
| // decision not to rewrite a grouped shorthand token, so that "-qC false" keeps | ||
| // failing with the arg-count error and its link to the boolean flags FAQ. See | ||
| // boolFlagTokens for why. This test exists so that widening the rewrite to | ||
| // cover groups is a visible choice rather than a silent one. | ||
| func TestNormalizeBoolFlagArgsLeavesGroupedShorthandsAlone(t *testing.T) { | ||
| args := []string{ | ||
| "attest", "generic", "testdata/file1", | ||
| "--artifact-type", "file", | ||
| "-qC", "false", | ||
| "--name", "foo", | ||
| } | ||
| root, err := newRootCmd(io.Discard, io.Discard, args) | ||
| require.NoError(t, err) | ||
|
|
||
| normalized := normalizeBoolFlagArgs(root, args) | ||
|
|
||
| require.Equal(t, args, normalized) | ||
| } | ||
|
|
||
| // TestNormalizeBoolFlagArgsStopsAtTerminator checks that nothing after the "--" | ||
| // terminator is rewritten. pflag stops parsing flags there, so every later | ||
| // token is a positional argument, however much it looks like a flag. Rewriting | ||
| // past the terminator would alter arguments the flag parser never inspects. | ||
| func TestNormalizeBoolFlagArgsStopsAtTerminator(t *testing.T) { | ||
| args := []string{ | ||
| "fingerprint", "--artifact-type", "file", | ||
| "--", "--debug", "false", | ||
| } | ||
| root, err := newRootCmd(io.Discard, io.Discard, args) | ||
| require.NoError(t, err) | ||
|
|
||
| normalized := normalizeBoolFlagArgs(root, args) | ||
|
|
||
| require.Equal(t, args, normalized) | ||
| } | ||
|
|
||
| // TestNormalizeBoolFlagArgsLeavesUndocumentedBoolLiteralsAlone pins the | ||
| // deliberate restriction to the two literals Kosli documents. pflag's bool | ||
| // values go through strconv.ParseBool, so the "=" form also accepts 1, 0, t, f, | ||
| // TRUE, False and friends, but the space form is rewritten only for "true" and | ||
| // "false". Widening this would capture positionals named "0" or "1", which are | ||
| // far more plausible artifact names than "true", and would mean guessing intent | ||
| // on input no Kosli documentation describes. The undocumented forms therefore | ||
| // keep failing loudly instead of being interpreted. | ||
| func TestNormalizeBoolFlagArgsLeavesUndocumentedBoolLiteralsAlone(t *testing.T) { | ||
| for _, literal := range []string{"TRUE", "True", "FALSE", "False", "1", "0", "t", "f"} { | ||
| t.Run(literal, func(t *testing.T) { | ||
| args := []string{ | ||
| "attest", "generic", "testdata/file1", | ||
| "--artifact-type", "file", | ||
| "--compliant", literal, | ||
| "--name", "foo", | ||
| } | ||
| root, err := newRootCmd(io.Discard, io.Discard, args) | ||
| require.NoError(t, err) | ||
|
|
||
| normalized := normalizeBoolFlagArgs(root, args) | ||
|
|
||
| require.Equal(t, args, normalized) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // TestNormalizeBoolFlagArgsCapturesPositionalNamedTrue pins the one accepted | ||
| // ambiguity of the rewrite: a positional argument whose literal value is "true" | ||
| // or "false" immediately after a bare boolean flag is taken as that flag's | ||
| // value. Here the artifact being fingerprinted is a file named "true", and it | ||
| // is swallowed by --debug. This is deliberate: Kosli positionals are artifact | ||
| // names, fingerprints and file paths, for which such a name is pathological, | ||
| // and distinguishing the two cases would mean predicting each command's | ||
| // expected argument count. | ||
| func TestNormalizeBoolFlagArgsCapturesPositionalNamedTrue(t *testing.T) { | ||
| args := []string{"fingerprint", "--debug", "true", "--artifact-type", "file"} | ||
| root, err := newRootCmd(io.Discard, io.Discard, args) | ||
| require.NoError(t, err) | ||
|
|
||
| normalized := normalizeBoolFlagArgs(root, args) | ||
|
|
||
| require.Equal(t, []string{"fingerprint", "--debug=true", "--artifact-type", "file"}, normalized) | ||
| } | ||
|
|
||
| // TestNormalizeBoolFlagArgsCapturesBoolFlagTokenUsedAsFlagValue pins the second | ||
| // accepted ambiguity of the rewrite: a boolean flag token given as the value of | ||
| // a preceding value-expecting flag is still rewritten. Here pflag would give | ||
| // --name the value "--compliant" and leave "false" as a positional argument, | ||
| // whereas the rewrite reads the same tokens as a space-form boolean. This is | ||
| // deliberate: telling the two apart would mean tracking which tokens pflag | ||
| // consumes as values, and a flag value that is itself a flag token is | ||
| // pathological. | ||
| func TestNormalizeBoolFlagArgsCapturesBoolFlagTokenUsedAsFlagValue(t *testing.T) { | ||
| args := []string{ | ||
| "attest", "generic", "Dockerfile", | ||
| "--artifact-type", "file", | ||
| "--name", "--compliant", "false", | ||
| } | ||
| root, err := newRootCmd(io.Discard, io.Discard, args) | ||
| require.NoError(t, err) | ||
|
|
||
| normalized := normalizeBoolFlagArgs(root, args) | ||
|
|
||
| require.Equal(t, []string{ | ||
| "attest", "generic", "Dockerfile", | ||
| "--artifact-type", "file", | ||
| "--name", "--compliant=false", | ||
| }, normalized) | ||
| } | ||
|
|
||
| // TestNormalizeBoolFlagArgsJoinsInheritedBoolFlag checks that a boolean flag | ||
| // inherited from a parent command is rewritten too, not just one declared on | ||
| // the subcommand itself. | ||
| func TestNormalizeBoolFlagArgsJoinsInheritedBoolFlag(t *testing.T) { | ||
| args := []string{ | ||
| "attest", "generic", "Dockerfile", | ||
| "--artifact-type", "file", | ||
| "--debug", "false", | ||
| "--flow", "my-flow", | ||
| } | ||
| root, err := newRootCmd(io.Discard, io.Discard, args) | ||
| require.NoError(t, err) | ||
|
|
||
| normalized := normalizeBoolFlagArgs(root, args) | ||
|
|
||
| require.Equal(t, []string{ | ||
| "attest", "generic", "Dockerfile", | ||
| "--artifact-type", "file", | ||
| "--debug=false", | ||
| "--flow", "my-flow", | ||
| }, normalized) | ||
| } | ||
|
|
||
| // TestNormalizeBoolFlagArgsJoinsSpaceSeparatedBoolValue checks that a boolean | ||
| // flag written in the space form is rewritten into the "=" form, so that | ||
| // `--compliant false` stops leaving "false" behind as a positional argument. | ||
| func TestNormalizeBoolFlagArgsJoinsSpaceSeparatedBoolValue(t *testing.T) { | ||
| args := []string{ | ||
| "attest", "generic", "Dockerfile", | ||
| "--artifact-type", "file", | ||
| "--compliant", "false", | ||
| "--flow", "my-flow", | ||
| "--trail", "my-trail", | ||
| } | ||
| root, err := newRootCmd(io.Discard, io.Discard, args) | ||
| require.NoError(t, err) | ||
|
|
||
| normalized := normalizeBoolFlagArgs(root, args) | ||
|
|
||
| require.Equal(t, []string{ | ||
| "attest", "generic", "Dockerfile", | ||
| "--artifact-type", "file", | ||
| "--compliant=false", | ||
| "--flow", "my-flow", | ||
| "--trail", "my-trail", | ||
| }, normalized) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.