Skip to content

Commit f87005b

Browse files
Add a more helpful message when trying to use an unknown short option
1 parent 6e54f57 commit f87005b

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/Console/ConsoleOptionParser.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,27 @@ protected function getOptionError($option)
847847
return implode("\n", $out);
848848
}
849849

850+
/**
851+
* Get the message output in the console stating that the short option can not be found. Output a list of available
852+
* short options and what option they refer to as well.
853+
*
854+
* @param string $option Unknown short option name trying to be used.
855+
* @return string The message to be displayed in the console.
856+
*/
857+
protected function getShortOptionError($option)
858+
{
859+
$out = [sprintf('Unknown short option `%s`', $option)];
860+
$out[] = '';
861+
$out[] = 'Available short options are :';
862+
$out[] = '';
863+
864+
foreach ($this->_shortOptions as $short => $long) {
865+
$out[] = sprintf(' - `%s` (short for `--%s`)', $short, $long);
866+
}
867+
868+
return implode("\n", $out);
869+
}
870+
850871
/**
851872
* Tries to guess the item name the user originally wanted using the levenshtein algorithm.
852873
*
@@ -919,7 +940,7 @@ protected function _parseShortOption($option, $params)
919940
}
920941
}
921942
if (!isset($this->_shortOptions[$key])) {
922-
throw new ConsoleException(sprintf('Unknown short option `%s`', $key));
943+
throw new ConsoleException($this->getShortOptionError($key));
923944
}
924945
$name = $this->_shortOptions[$key];
925946

tests/TestCase/Console/ConsoleOptionParserTest.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,12 +375,16 @@ public function testOptionThatDoesNotExist()
375375
* test parsing short options that do not exist.
376376
*
377377
* @expectedException \Cake\Console\Exception\ConsoleException
378+
* @expectedExceptionMessageRegexp /Unknown short option `f`.\n\nAvailable short options are :\n\n
379+
* - `n` (short for `--no-commit`)\n - `c` (short for `--clear`)/
378380
* @return void
379381
*/
380382
public function testShortOptionThatDoesNotExist()
381383
{
382384
$parser = new ConsoleOptionParser('test', false);
383-
$parser->addOption('no-commit', ['boolean' => true]);
385+
$parser->addOption('no-commit', ['boolean' => true, 'short' => 'n']);
386+
$parser->addOption('construct', ['boolean' => true]);
387+
$parser->addOption('clear', ['boolean' => true, 'short' => 'c']);
384388

385389
$parser->parse(['-f']);
386390
}

0 commit comments

Comments
 (0)