@@ -11,6 +11,7 @@ import (
1111
1212 "github.com/boyter/scc/v3/processor"
1313 "github.com/spf13/cobra"
14+ "github.com/spf13/pflag"
1415)
1516
1617func printShellCompletion (cmd * cobra.Command , command string ) error {
@@ -28,6 +29,23 @@ func printShellCompletion(cmd *cobra.Command, command string) error {
2829 }
2930}
3031
32+ func printFlagSuggestion (flagSet * pflag.FlagSet , unknownFlag string ) {
33+ flags := processor .GetMostSimilarFlags (flagSet , unknownFlag )
34+ if len (flags ) == 0 {
35+ return
36+ }
37+
38+ if len (flags ) > 1 {
39+ _ , _ = fmt .Fprintf (os .Stderr , "The most similar flags of --%s are:\n " , unknownFlag )
40+ } else {
41+ _ , _ = fmt .Fprintf (os .Stderr , "The most similar flag of --%s is:\n " , unknownFlag )
42+ }
43+
44+ for _ , flag := range flags {
45+ _ , _ = fmt .Fprintf (os .Stderr , "\t --%s\n " , flag )
46+ }
47+ }
48+
3149//go:generate go run scripts/include.go
3250func main () {
3351 // f, _ := os.Create("scc.pprof")
@@ -448,12 +466,16 @@ func main() {
448466 if len (args ) == 4 && args [1 ] == "completion" && args [2 ] == "--shell" {
449467 err := printShellCompletion (rootCmd , args [3 ])
450468 if err != nil {
451- fmt .Printf ( "Error printing shell completion: %s\n " , err )
469+ _ , _ = fmt .Fprintf ( os . Stderr , "Error printing shell completion: %s\n " , err )
452470 }
453471 return
454472 }
455473
456474 if err := rootCmd .Execute (); err != nil {
475+ // If a flag does not exist and is not a shorthand, it may be a spelling error. Search for and print possible options.
476+ if notExistError , ok := err .(* pflag.NotExistError ); ok && len (notExistError .GetSpecifiedName ()) > 1 {
477+ printFlagSuggestion (flags , notExistError .GetSpecifiedName ())
478+ }
457479 os .Exit (1 )
458480 }
459481}
0 commit comments