Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ $application = new Application;
$application->execute();
```

#### Finding commands

The command name given on the command line may be abbreviated, as with Symfony's console: each part of a namespaced
name can be shortened as long as the result is unique, so `c:c` runs `cache:clear` and `li` runs `list`. An ambiguous
abbreviation fails with a list of the matching commands, an unknown name with the similar names it found
("Did you mean this?"). Hidden commands are not suggested and can only be run by their full name or an alias.

The same lookup is available as `Application::findCommand()`. `getCommand()` and `hasCommand()` only accept exact
names and aliases.

### Console Commands

The `AbstractCommand` defines the base API for console command classes, largely based on `Symfony\Component\Console\Command\Command`.
Expand Down
184 changes: 183 additions & 1 deletion src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ protected function doExecute(): int
try {
$this->runningCommand = null;

$command = $this->getCommand($name);
$command = $this->findCommand($name);
} catch (\Throwable $e) {
if ($e instanceof CommandNotFoundException && !($e instanceof NamespaceNotFoundException)) {
(new SymfonyStyle($input, $output))->block(sprintf("\nCommand \"%s\" is not defined.\n", $name), null, 'error');
Expand Down Expand Up @@ -452,6 +452,108 @@ public function execute()
}
}

/**
* Finds a command by name or alias, accepting an abbreviation of the name.
*
* Each part of a namespaced name can be abbreviated as long as the result is unique, `c:c` finds `cache:clear` for example.
* Contrary to `getCommand()`, the exception thrown for an unknown name lists similar command names.
*
* @param string $name The command name, alias or abbreviation
*
* @return AbstractCommand
*
* @since __DEPLOY_VERSION__
* @throws CommandNotFoundException When the name is unknown or ambiguous
* @throws NamespaceNotFoundException When the namespace of the name is unknown or ambiguous
*/
public function findCommand(string $name): AbstractCommand
{
$this->initCommands();

if ($this->hasCommand($name)) {
return $this->getCommand($name);
}

$allCommands = array_keys($this->commands);

if ($this->commandLoader) {
$allCommands = array_values(array_unique(array_merge($this->commandLoader->getNames(), $allCommands)));
}

$expr = implode('[^:]*:', array_map('preg_quote', explode(':', $name))) . '[^:]*';
$commands = preg_grep('{^' . $expr . '}', $allCommands);

if (!$commands) {
$commands = preg_grep('{^' . $expr . '}i', $allCommands);
}

// If no commands matched or only namespaces matched, the name is unknown
if (!$commands || \count(preg_grep('{^' . $expr . '$}i', $commands)) < 1) {
if (($pos = strrpos($name, ':')) !== false) {
// Check if the namespace exists and contains commands
$this->findNamespace(substr($name, 0, $pos));
}

$message = sprintf('The command "%s" does not exist.', $name);
$alternatives = array_values(
array_filter(
$this->findAlternatives($name, $allCommands),
function (string $alternative): bool {
$command = $this->loadCommand($alternative);

return $command !== null && !$command->isHidden();
}
)
);

if ($alternatives) {
$message .= \count($alternatives) === 1 ? "\n\nDid you mean this?\n " : "\n\nDid you mean one of these?\n ";
$message .= implode("\n ", $alternatives);
}

throw new CommandNotFoundException($message, $alternatives);
}

// Reduce the matches to visible commands, dropping aliases of commands which are already in the list
$matches = [];

foreach ($commands as $nameOrAlias) {
$command = $this->loadCommand($nameOrAlias);

if ($command === null || $command->isHidden()) {
continue;
}

$commandName = $command->getName();

if (\in_array($commandName, $commands, true) && $commandName !== $nameOrAlias) {
continue;
}

$matches[$commandName] = $command;
}

if (!$matches) {
throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
}

if (\count($matches) > 1) {
$maxLength = max(array_map([StringHelper::class, 'strlen'], array_keys($matches)));
$suggestions = [];

foreach ($matches as $commandName => $command) {
$suggestions[] = rtrim(str_pad($commandName, $maxLength) . ' ' . $command->getDescription());
}

throw new CommandNotFoundException(
sprintf("The command \"%s\" is ambiguous.\nDid you mean one of these?\n %s", $name, implode("\n ", $suggestions)),
array_keys($matches)
);
}

return $this->getCommand(array_key_first($matches));
}

/**
* Finds a registered namespace by a name.
*
Expand Down Expand Up @@ -1255,6 +1357,68 @@ private function extractNamespace(string $name, ?int $limit = null): string
return implode(':', $limit === null ? $parts : \array_slice($parts, 0, $limit));
}

/**
* Finds command names which are similar to the given name.
*
* @param string $name The name to find alternatives for
* @param string[] $collection The names to search
*
* @return string[]
*
* @since __DEPLOY_VERSION__
*/
private function findAlternatives(string $name, array $collection): array
{
$threshold = 1e3;
$alternatives = [];
$collectionParts = [];

foreach ($collection as $item) {
$collectionParts[$item] = explode(':', $item);
}

foreach (explode(':', $name) as $i => $subname) {
foreach ($collectionParts as $collectionName => $parts) {
$exists = isset($alternatives[$collectionName]);

if (!isset($parts[$i])) {
if ($exists) {
$alternatives[$collectionName] += $threshold;
}

continue;
}

$lev = levenshtein($subname, $parts[$i]);

if ($lev <= \strlen($subname) / 3 || ($subname !== '' && str_contains($parts[$i], $subname))) {
$alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
} elseif ($exists) {
$alternatives[$collectionName] += $threshold;
}
}
}

foreach ($collection as $item) {
$lev = levenshtein($name, $item);

if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) {
$alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
}
}

$alternatives = array_filter(
$alternatives,
function ($lev) use ($threshold): bool {
return $lev < 2 * $threshold;
}
);

ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE);

return array_map('strval', array_keys($alternatives));
}

/**
* Internal function to initialise the command store, this allows the store to be lazy loaded only when needed.
*
Expand All @@ -1274,4 +1438,22 @@ private function initCommands(): void
$this->addCommand($command);
}
}

/**
* Loads a command by its exact name or alias without processing a help request.
*
* @param string $name The command name or alias
*
* @return AbstractCommand|null The command, or null if it is not available
*
* @since __DEPLOY_VERSION__
*/
private function loadCommand(string $name): ?AbstractCommand
{
if (!isset($this->commands[$name]) && $this->commandLoader && $this->commandLoader->has($name)) {
$this->addCommand($this->commandLoader->get($name));
}

return $this->commands[$name] ?? null;
}
}
109 changes: 109 additions & 0 deletions tests/ApplicationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,115 @@ public function testGetCommandForUnknownCommand()
$this->object->getCommand('test');
}

public function testFindCommandByExactName()
{
$command = new NamespacedCommand();
$this->object->addCommand($command);

$this->assertSame($command, $this->object->findCommand('test:namespaced'));
}

public function testFindCommandByAbbreviation()
{
$command = new NamespacedCommand();
$this->object->addCommand($command);

$this->assertInstanceOf(ListCommand::class, $this->object->findCommand('li'));
$this->assertSame($command, $this->object->findCommand('t:n'));
$this->assertSame($command, $this->object->findCommand('TEST:NAME'), 'The lookup falls back to a case-insensitive match');
}

public function testFindCommandIgnoresAliasesOfAMatchedCommand()
{
$command = new AliasedCommand();
$this->object->addCommand($command);

// "test:a" matches both "test:aliased" and its alias "test:alias"
$this->assertSame($command, $this->object->findCommand('test:a'));
}

public function testFindCommandWithCommandLoader()
{
$container = $this->buildStubContainer();
$container->set(
'command.namespaced',
function (ContainerInterface $container) {
return new NamespacedCommand();
}
);

$this->object->setCommandLoader(new ContainerLoader($container, ['test:namespaced' => 'command.namespaced']));

$this->assertInstanceOf(NamespacedCommand::class, $this->object->findCommand('t:name'));
}

public function testFindAmbiguousCommand()
{
$this->object->addCommand(new NamespacedCommand());
$this->object->addCommand(new AliasedCommand());

try {
$this->object->findCommand('test:');
$this->fail('An ambiguous abbreviation should throw a CommandNotFoundException');
} catch (CommandNotFoundException $exception) {
$this->assertStringStartsWith('The command "test:" is ambiguous.', $exception->getMessage());
$this->assertEqualsCanonicalizing(['test:aliased', 'test:namespaced'], $exception->getAlternatives());
}
}

public function testFindUnknownCommandSuggestsAlternatives()
{
try {
$this->object->findCommand('lisst');
$this->fail('An unknown command should throw a CommandNotFoundException');
} catch (CommandNotFoundException $exception) {
$this->assertSame("The command \"lisst\" does not exist.\n\nDid you mean this?\n list", $exception->getMessage());
$this->assertSame(['list'], $exception->getAlternatives());
}
}

public function testFindUnknownCommandWithoutAlternatives()
{
$this->expectException(CommandNotFoundException::class);
$this->expectExceptionMessage('The command "foo" does not exist.');

$this->object->findCommand('foo');
}

public function testFindCommandInUnknownNamespace()
{
$this->expectException(NamespaceNotFoundException::class);
$this->expectExceptionMessage('There are no commands defined in the "foo" namespace.');

$this->object->findCommand('foo:bar');
}

public function testFindCommandDoesNotExpandAbbreviationsToHiddenCommands()
{
$command = new NamespacedCommand();
$command->setHidden(true);
$this->object->addCommand($command);

$this->assertSame($command, $this->object->findCommand('test:namespaced'), 'A hidden command can still be run by its full name');

$this->expectException(CommandNotFoundException::class);
$this->expectExceptionMessage('The command "test:n" does not exist.');

$this->object->findCommand('test:n');
}

public function testTheApplicationIsExecutedWithAnAbbreviatedCommand()
{
$input = new ArrayInput(['command' => 'li']);
$output = new BufferedOutput();

$app = new Application($input, $output);
$app->setAutoExit(false);
$app->execute();

$this->assertStringContainsString('Available commands:', $output->fetch());
}

public function testGetNamespaces()
{
$this->object->addCommand(new NamespacedCommand());
Expand Down
Loading