@@ -10,9 +10,36 @@ import (
1010 "strings"
1111)
1212
13- func runCommandAction (c * cli.Context ) error {
14- if c .NArg () == 0 {
15- return newUsageError (c )
13+ func commandsMap (cfg * config.SanicConfig , env * config.Environment ) map [string ]config.Command {
14+ commands := make (map [string ]config.Command )
15+ for _ , globalCommand := range cfg .Commands {
16+ commands [globalCommand .Name ] = globalCommand
17+ }
18+ for _ , envCommand := range env .Commands {
19+ commands [envCommand .Name ] = envCommand
20+ }
21+ return commands
22+ }
23+
24+ func mostSimilarCommands (commands map [string ]config.Command , requestedCommand string , num int ) []string {
25+ var commandList []string
26+ for _ , cmd := range commands {
27+ commandList = append (commandList , cmd .Name )
28+ }
29+ sort .Slice (commandList , func (i , j int ) bool {
30+ distI := levenshtein .ComputeDistance (commandList [i ], requestedCommand )
31+ distJ := levenshtein .ComputeDistance (commandList [j ], requestedCommand )
32+ return distI < distJ
33+ })
34+ if len (commandList ) <= num {
35+ return commandList
36+ }
37+ return commandList [:num ]
38+ }
39+
40+ func runCommandAction (cliCtx * cli.Context ) error {
41+ if cliCtx .NArg () == 0 {
42+ return newUsageError (cliCtx )
1643 }
1744
1845 s , err := shell .Current ()
@@ -30,31 +57,22 @@ func runCommandAction(c *cli.Context) error {
3057 return cli .NewExitError (err .Error (), 1 )
3158 }
3259
33- commandName := c .Args ().First ()
34- var commandNames []string
35- for _ , command := range env .Commands {
36- if command .Name == commandName {
37- code , err := s .ShellExec (command .Command , c .Args ().Tail ())
38- if err == nil {
39- return nil
40- }
41- return cli .NewExitError (err .Error (), code )
60+ commands := commandsMap (& cfg , env )
61+ commandName := cliCtx .Args ().First ()
62+
63+ if cmd , ok := commands [commandName ]; ok {
64+ code , err := s .ShellExec (cmd .Command , cliCtx .Args ().Tail ())
65+ if err == nil {
66+ return nil
4267 }
43- commandNames = append (commandNames , command .Name )
44- }
45- sort .Slice (commandNames , func (i , j int ) bool {
46- distI := levenshtein .ComputeDistance (commandNames [i ], commandName )
47- distJ := levenshtein .ComputeDistance (commandNames [j ], commandName )
48- return distI < distJ
49- })
50- if len (commandNames ) > 6 {
51- commandNames = commandNames [:6 ]
68+ return cli .NewExitError (err .Error , code )
5269 }
70+
5371 return cli .NewExitError (
5472 fmt .Sprintf ("Command %s was not found in environment %s. Did you mean one of [%s]?" ,
5573 commandName ,
5674 s .GetSanicEnvironment (),
57- strings .Join (commandNames , "|" ),
75+ strings .Join (mostSimilarCommands ( commands , commandName , 6 ) , "|" ),
5876 ), 1 )
5977
6078}
0 commit comments