Skip to content

Commit

Permalink
Add a more helpful message when trying to use an unknown short option
Browse files Browse the repository at this point in the history
  • Loading branch information
HavokInspiration committed Aug 1, 2017
1 parent 6e54f57 commit f87005b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
23 changes: 22 additions & 1 deletion src/Console/ConsoleOptionParser.php
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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];

Expand Down
6 changes: 5 additions & 1 deletion tests/TestCase/Console/ConsoleOptionParserTest.php
Expand Up @@ -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']);
}
Expand Down

0 comments on commit f87005b

Please sign in to comment.