Skip to content

Commit f99191e

Browse files
committed
Enable setting an alias for an extension command
1 parent 1ec47d8 commit f99191e

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

pkg/cmd/alias/set/set.go

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ type SetOptions struct {
2020
Name string
2121
Expansion string
2222
IsShell bool
23-
RootCmd *cobra.Command
23+
24+
validCommand func(string) bool
2425
}
2526

2627
func NewCmdSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command {
@@ -78,11 +79,29 @@ func NewCmdSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command
7879
`),
7980
Args: cobra.ExactArgs(2),
8081
RunE: func(cmd *cobra.Command, args []string) error {
81-
opts.RootCmd = cmd.Root()
82-
8382
opts.Name = args[0]
8483
opts.Expansion = args[1]
8584

85+
opts.validCommand = func(args string) bool {
86+
split, err := shlex.Split(args)
87+
if err != nil {
88+
return false
89+
}
90+
91+
rootCmd := cmd.Root()
92+
cmd, _, err := rootCmd.Traverse(split)
93+
if err == nil && cmd != rootCmd {
94+
return true
95+
}
96+
97+
for _, ext := range f.ExtensionManager.List() {
98+
if ext.Name() == split[0] {
99+
return true
100+
}
101+
}
102+
return false
103+
}
104+
86105
if runF != nil {
87106
return runF(opts)
88107
}
@@ -143,11 +162,11 @@ func setRun(opts *SetOptions) error {
143162
}
144163
isShell = strings.HasPrefix(expansion, "!")
145164

146-
if validCommand(opts.RootCmd, opts.Name) {
165+
if opts.validCommand(opts.Name) {
147166
return fmt.Errorf("could not create alias: %q is already a gh command", opts.Name)
148167
}
149168

150-
if !isShell && !validCommand(opts.RootCmd, expansion) {
169+
if !isShell && !opts.validCommand(expansion) {
151170
return fmt.Errorf("could not create alias: %s does not correspond to a gh command", expansion)
152171
}
153172

@@ -173,16 +192,6 @@ func setRun(opts *SetOptions) error {
173192
return nil
174193
}
175194

176-
func validCommand(rootCmd *cobra.Command, expansion string) bool {
177-
split, err := shlex.Split(expansion)
178-
if err != nil {
179-
return false
180-
}
181-
182-
cmd, _, err := rootCmd.Traverse(split)
183-
return err == nil && cmd != rootCmd
184-
}
185-
186195
func getExpansion(opts *SetOptions) (string, error) {
187196
if opts.Expansion == "-" {
188197
stdin, err := ioutil.ReadAll(opts.IO.In)

0 commit comments

Comments
 (0)