Browse Source

Only suggest relevant options based on edit distance.

Mark Story 6 years ago
parent
commit
ddd705c8df

+ 8 - 5
src/Console/Exception/InvalidOptionException.php

@@ -69,12 +69,15 @@ class InvalidOptionException extends ConsoleException
         if ($bestGuess) {
             $out .= " Did you mean: `{$bestGuess}`?";
         }
-        if ($this->suggestions) {
-            $suggestions = array_map(function ($item) {
-                return '- ' . $item;
-            }, $this->suggestions);
+        $good = [];
+        foreach ($this->suggestions as $option) {
+            if (levenshtein($option, $this->requested) < 8) {
+                $good[] = '- ' . $option;
+            }
+        }
 
-            $out .= "\n\nOther valid choices:\n\n" . implode("\n", $suggestions);
+        if ($good) {
+            $out .= "\n\nOther valid choices:\n\n" . implode("\n", $good);
         }
 
         return $out;

+ 2 - 12
tests/TestCase/Console/ConsoleOptionParserTest.php

@@ -375,8 +375,7 @@ class ConsoleOptionParserTest extends TestCase
                 "\n" .
                 "Other valid choices:\n" .
                 "\n" .
-                "- help\n" .
-                "- no-commit",
+                "- help",
                 $e->getFullMessage()
             );
         }
@@ -397,16 +396,7 @@ class ConsoleOptionParserTest extends TestCase
         try {
             $parser->parse(['-f']);
         } catch (InvalidOptionException $e) {
-            $this->assertStringContainsString(
-                "Unknown short option `f`.\n" .
-                "\n" .
-                "Other valid choices:\n" .
-                "\n" .
-                "- c (short for `--clear`)\n" .
-                "- h (short for `--help`)\n" .
-                "- n (short for `--no-commit`)",
-                $e->getFullMessage()
-            );
+            $this->assertStringContainsString("Unknown short option `f`.", $e->getFullMessage());
         }
     }