-
Notifications
You must be signed in to change notification settings - Fork 6
fix: resolve abbreviations of native commands #176
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7f456ce
fix: resolve abbreviations of native commands
pjcdawkins 41b28dc
fix: only skip boolean root flags before an abbreviated command
pjcdawkins 03c393a
fix: address review findings on abbreviation resolution
pjcdawkins 7811cf0
fix: treat hidden legacy aliases and disabled commands like the legac…
pjcdawkins 7711c9f
fix: define the root help flag before command lookup
pjcdawkins 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| package commands | ||
|
|
||
| import ( | ||
| "regexp" | ||
| "slices" | ||
| "strings" | ||
|
|
||
| "github.com/spf13/cobra" | ||
| "github.com/spf13/pflag" | ||
|
|
||
| "github.com/upsun/cli/internal/config" | ||
| "github.com/upsun/cli/internal/legacy" | ||
| ) | ||
|
|
||
| // abbrevCandidate is a command that an abbreviation may resolve to. | ||
| type abbrevCandidate struct { | ||
| names []string // The command name, followed by its aliases. | ||
| hidden bool | ||
| native bool | ||
| } | ||
|
|
||
| // expandAbbreviation replaces an abbreviated native command name in args (e.g. "p:init") with the full name. | ||
| // | ||
| // Abbreviations are resolved the same way as the legacy CLI (Symfony Console's Application::find()), across both | ||
| // native and legacy commands. Only a unique match to a native command is expanded, as anything else is handled by the | ||
| // legacy CLI. The legacy commands are only loaded if needed. | ||
| func expandAbbreviation( | ||
| root *cobra.Command, | ||
| loadLegacyCmds func() ([]legacy.Command, error), | ||
| args []string, | ||
| ) (expanded []string, ok bool, err error) { | ||
| // Only boolean root flags may precede the command, so that a flag's value is not mistaken for it. | ||
| pos := slices.IndexFunc(args, func(a string) bool { return !isRootBoolFlag(root, a) }) | ||
| if pos == -1 || strings.HasPrefix(args[pos], "-") { | ||
| return nil, false, nil | ||
| } | ||
| name := args[pos] | ||
|
|
||
| var candidates []abbrevCandidate | ||
| nativeNames := map[string]bool{} | ||
| for _, c := range root.Commands() { | ||
| names := append([]string{c.Name()}, c.Aliases...) | ||
| for _, n := range names { | ||
| nativeNames[n] = true | ||
| } | ||
| candidates = append(candidates, abbrevCandidate{names: names, hidden: c.Hidden, native: true}) | ||
| } | ||
| if nativeNames[name] || resolveAbbreviation(name, candidates) == nil { | ||
| return nil, false, nil | ||
| } | ||
|
|
||
| legacyCmds, err := loadLegacyCmds() | ||
| if err != nil { | ||
| return nil, false, err | ||
| } | ||
| for _, c := range legacyCmds { | ||
| if nativeNames[c.Name] { | ||
| // Overridden by a native command. | ||
| continue | ||
| } | ||
| names := append([]string{c.Name}, c.Aliases...) | ||
| if slices.Contains(names, name) || slices.Contains(c.HiddenAliases, name) { | ||
| return nil, false, nil | ||
| } | ||
| candidates = append(candidates, abbrevCandidate{names: names, hidden: c.Hidden}) | ||
| } | ||
|
|
||
| target := resolveAbbreviation(name, candidates) | ||
| if target == nil || !target.native { | ||
| return nil, false, nil | ||
| } | ||
| expanded = slices.Clone(args) | ||
| expanded[pos] = target.names[0] | ||
| return expanded, true, nil | ||
| } | ||
|
|
||
| // isRootBoolFlag tests if arg consists of boolean root flags, e.g. "--yes" or "-vq". | ||
| func isRootBoolFlag(root *cobra.Command, arg string) bool { | ||
| flagSets := []*pflag.FlagSet{root.Flags(), root.PersistentFlags()} | ||
| isBool := func(lookup func(*pflag.FlagSet) *pflag.Flag) bool { | ||
| for _, fs := range flagSets { | ||
| if f := lookup(fs); f != nil { | ||
| return f.Value.Type() == "bool" | ||
| } | ||
| } | ||
| return false | ||
| } | ||
| if name, ok := strings.CutPrefix(arg, "--"); ok { | ||
| name, _, _ = strings.Cut(name, "=") | ||
| return isBool(func(fs *pflag.FlagSet) *pflag.Flag { return fs.Lookup(name) }) | ||
| } | ||
| shorthands, ok := strings.CutPrefix(arg, "-") | ||
| if !ok || shorthands == "" { | ||
| return false | ||
| } | ||
| for _, c := range shorthands { | ||
| if !isBool(func(fs *pflag.FlagSet) *pflag.Flag { return fs.ShorthandLookup(string(c)) }) { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| // enabledLegacyCommands returns a loader for the legacy commands that are not disabled by config. | ||
| func enabledLegacyCommands(cnf *config.Config, load func() ([]legacy.Command, error)) func() ([]legacy.Command, error) { | ||
| return func() ([]legacy.Command, error) { | ||
| cmds, err := load() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return slices.DeleteFunc(slices.Clone(cmds), func(c legacy.Command) bool { | ||
| return slices.Contains(cnf.Application.DisabledCommands, c.Name) || | ||
| slices.Contains(cnf.Application.WrappedDisabledCommands, c.Name) | ||
| }), nil | ||
| } | ||
| } | ||
|
|
||
| // resolveAbbreviation follows Symfony Console's rules to find the command abbreviated by name, if it is unique. | ||
| func resolveAbbreviation(name string, candidates []abbrevCandidate) *abbrevCandidate { | ||
| parts := strings.Split(name, ":") | ||
| for i, p := range parts { | ||
| parts[i] = regexp.QuoteMeta(p) | ||
| } | ||
| expr := "^" + strings.Join(parts, "[^:]*:") + "[^:]*" | ||
|
|
||
| matchAll := func(re *regexp.Regexp) (matched []int, fullMatch bool) { | ||
| for i, c := range candidates { | ||
| isMatch := false | ||
| for _, n := range c.names { | ||
| if loc := re.FindStringIndex(n); loc != nil { | ||
| isMatch = true | ||
| fullMatch = fullMatch || loc[1] == len(n) | ||
| } | ||
| } | ||
| if isMatch { | ||
| matched = append(matched, i) | ||
| } | ||
| } | ||
| return matched, fullMatch | ||
| } | ||
|
|
||
| // Try a case-sensitive match first, then case-insensitive. | ||
| matched, fullMatch := matchAll(regexp.MustCompile(expr)) | ||
| if len(matched) == 0 { | ||
| matched, fullMatch = matchAll(regexp.MustCompile("(?i)" + expr)) | ||
| } | ||
| // Prefix-only matches (e.g. "project" for "project:variable:get") count toward ambiguity, but at least one | ||
| // command must match fully. | ||
| if !fullMatch { | ||
| return nil | ||
| } | ||
|
|
||
| // Hidden commands still count toward ambiguity: the legacy CLI's lazy-loaded commands do not reliably report | ||
| // whether they are hidden, so it can resolve to them. | ||
| if len(matched) != 1 || candidates[matched[0]].hidden { | ||
| return nil | ||
| } | ||
| return &candidates[matched[0]] | ||
| } | ||
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,94 @@ | ||
| package commands | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/spf13/cobra" | ||
| "github.com/stretchr/testify/assert" | ||
|
|
||
| "github.com/upsun/cli/internal/config" | ||
| "github.com/upsun/cli/internal/legacy" | ||
| ) | ||
|
|
||
| func TestExpandAbbreviation(t *testing.T) { | ||
| root := &cobra.Command{Use: "upsun"} | ||
| root.PersistentFlags().BoolP("verbose", "v", false, "") | ||
| root.PersistentFlags().BoolP("yes", "y", false, "") | ||
| root.PersistentFlags().String("context", "", "") | ||
| root.InitDefaultHelpFlag() | ||
| root.AddCommand( | ||
| &cobra.Command{Use: "init", Aliases: []string{"project:init", "ify"}}, | ||
| &cobra.Command{Use: "project:convert", Aliases: []string{"convert"}}, | ||
| &cobra.Command{Use: "app:config-validate", Aliases: []string{"validate", "lint"}}, | ||
| &cobra.Command{Use: "list"}, | ||
| &cobra.Command{Use: "version"}, | ||
| &cobra.Command{Use: "_complete", Hidden: true}, | ||
| ) | ||
| legacyCmds := []legacy.Command{ | ||
| {Name: "list"}, | ||
| {Name: "project:info", Aliases: []string{"pinfo"}, HiddenAliases: []string{"p:in", "project:initx"}}, | ||
| {Name: "project:create", Aliases: []string{"create"}}, | ||
| {Name: "project:curl", Hidden: true}, | ||
| {Name: "app:list", Aliases: []string{"apps"}}, | ||
| {Name: "app:config-get"}, | ||
| {Name: "integration:list"}, | ||
| {Name: "version:list", Aliases: []string{"versions"}, Hidden: true}, | ||
| } | ||
|
|
||
| cases := []struct { | ||
| name string | ||
| args []string | ||
| want []string | ||
| }{ | ||
| {"namespace abbreviation", []string{"p:init"}, []string{"init"}}, | ||
| {"both parts abbreviated", []string{"pro:ini", "--yes"}, []string{"init", "--yes"}}, | ||
| {"case-insensitive fallback", []string{"P:Init"}, []string{"init"}}, | ||
| {"after flags", []string{"-v", "--yes", "-vy", "p:conv"}, []string{"-v", "--yes", "-vy", "project:convert"}}, | ||
| {"after a flag with a value", []string{"--context", "p:init", "init"}, nil}, | ||
| {"after a flag with a separate value", []string{"--context", "foo", "p:init"}, nil}, | ||
| {"after an unknown flag", []string{"--foo", "p:init"}, nil}, | ||
| {"after a shorthand with a value", []string{"-vc", "p:init"}, nil}, | ||
| {"multi-word part", []string{"a:config-v"}, []string{"app:config-validate"}}, | ||
| {"unique abbreviation", []string{"p:con"}, []string{"project:convert"}}, | ||
| {"ambiguous with a hidden legacy command", []string{"ver"}, nil}, | ||
| {"after help flag", []string{"--help", "p:init"}, []string{"--help", "init"}}, | ||
| {"ambiguous with a legacy command", []string{"p:c"}, nil}, | ||
| {"ambiguous between legacy commands", []string{"a:c"}, nil}, | ||
| {"prefix of a longer legacy name", []string{"in"}, nil}, | ||
| {"legacy command", []string{"p:info"}, nil}, | ||
| {"exact native command", []string{"init"}, nil}, | ||
| {"exact legacy command", []string{"pinfo"}, nil}, | ||
| {"exact hidden legacy alias", []string{"p:in"}, nil}, | ||
| {"hidden legacy alias not abbreviated", []string{"project:ini"}, []string{"init"}}, | ||
| {"unknown command", []string{"p:nope"}, nil}, | ||
| {"hidden native command", []string{"_comp"}, nil}, | ||
| {"no command", []string{"--version"}, nil}, | ||
| {"after double dash", []string{"--", "p:init"}, nil}, | ||
| {"empty", nil, nil}, | ||
| } | ||
| for _, c := range cases { | ||
| t.Run(c.name, func(t *testing.T) { | ||
| got, ok, err := expandAbbreviation(root, func() ([]legacy.Command, error) { return legacyCmds, nil }, c.args) | ||
| assert.NoError(t, err) | ||
| if c.want == nil { | ||
| assert.False(t, ok) | ||
| return | ||
| } | ||
| assert.True(t, ok) | ||
| assert.Equal(t, c.want, got) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestEnabledLegacyCommands(t *testing.T) { | ||
| cnf := &config.Config{} | ||
| cnf.Application.DisabledCommands = []string{"self:install"} | ||
| cnf.Application.WrappedDisabledCommands = []string{"self:update"} | ||
| load := func() ([]legacy.Command, error) { | ||
| return []legacy.Command{{Name: "self:install"}, {Name: "self:update"}, {Name: "self:stats"}}, nil | ||
| } | ||
|
|
||
| cmds, err := enabledLegacyCommands(cnf, load)() | ||
| assert.NoError(t, err) | ||
| assert.Equal(t, []legacy.Command{{Name: "self:stats"}}, cmds) | ||
| } |
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
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.