From f87005bcb96f88b8cca8f0deada62cfe18321547 Mon Sep 17 00:00:00 2001 From: Yves P Date: Tue, 1 Aug 2017 13:34:47 +0200 Subject: [PATCH] Add a more helpful message when trying to use an unknown short option --- src/Console/ConsoleOptionParser.php | 23 ++++++++++++++++++- .../Console/ConsoleOptionParserTest.php | 6 ++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/Console/ConsoleOptionParser.php b/src/Console/ConsoleOptionParser.php index 0a235f989eb..d9b565fc2ae 100644 --- a/src/Console/ConsoleOptionParser.php +++ b/src/Console/ConsoleOptionParser.php @@ -847,6 +847,27 @@ protected function getOptionError($option) return implode("\n", $out); } + /** + * 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. * @@ -919,7 +940,7 @@ protected function _parseShortOption($option, $params) } } if (!isset($this->_shortOptions[$key])) { - throw new ConsoleException(sprintf('Unknown short option `%s`', $key)); + throw new ConsoleException($this->getShortOptionError($key)); } $name = $this->_shortOptions[$key]; diff --git a/tests/TestCase/Console/ConsoleOptionParserTest.php b/tests/TestCase/Console/ConsoleOptionParserTest.php index fda9f2b7509..7951cf6aa29 100644 --- a/tests/TestCase/Console/ConsoleOptionParserTest.php +++ b/tests/TestCase/Console/ConsoleOptionParserTest.php @@ -375,12 +375,16 @@ public function testOptionThatDoesNotExist() * 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']); }