Browse Source

Add a more helpful message when trying to use an unknown short option

Yves P 8 years ago
parent
commit
f87005bcb9

+ 22 - 1
src/Console/ConsoleOptionParser.php

@@ -848,6 +848,27 @@ class ConsoleOptionParser
     }
 
     /**
+     * Get the message output in the console stating that the short option can not be found. Output a list of available 
+     * short options and what option they refer to as well.
+     *
+     * @param string $option Unknown short option name trying to be used.
+     * @return string The message to be displayed in the console.
+     */
+    protected function getShortOptionError($option)
+    {
+        $out = [sprintf('Unknown short option `%s`', $option)];
+        $out[] = '';
+        $out[] = 'Available short options are :';
+        $out[] = '';
+
+        foreach ($this->_shortOptions as $short => $long) {
+            $out[] = sprintf(' - `%s` (short for `--%s`)', $short, $long);
+        }
+
+        return implode("\n", $out);
+    }
+
+    /**
      * Tries to guess the item name the user originally wanted using the levenshtein algorithm.
      *
      * @param string $needle Unknown item (either a subcommand name or an option for instance) trying to be used.
@@ -919,7 +940,7 @@ class ConsoleOptionParser
             }
         }
         if (!isset($this->_shortOptions[$key])) {
-            throw new ConsoleException(sprintf('Unknown short option `%s`', $key));
+            throw new ConsoleException($this->getShortOptionError($key));
         }
         $name = $this->_shortOptions[$key];
 

+ 5 - 1
tests/TestCase/Console/ConsoleOptionParserTest.php

@@ -375,12 +375,16 @@ class ConsoleOptionParserTest extends TestCase
      * test parsing short options that do not exist.
      *
      * @expectedException \Cake\Console\Exception\ConsoleException
+     * @expectedExceptionMessageRegexp /Unknown short option `f`.\n\nAvailable short options are :\n\n
+     * - `n` (short for `--no-commit`)\n - `c` (short for `--clear`)/
      * @return void
      */
     public function testShortOptionThatDoesNotExist()
     {
         $parser = new ConsoleOptionParser('test', false);
-        $parser->addOption('no-commit', ['boolean' => true]);
+        $parser->addOption('no-commit', ['boolean' => true, 'short' => 'n']);
+        $parser->addOption('construct', ['boolean' => true]);
+        $parser->addOption('clear', ['boolean' => true, 'short' => 'c']);
 
         $parser->parse(['-f']);
     }