Skip to content

[Command] Add question helper for unknown or ambiguous commands #19282

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
70 changes: 38 additions & 32 deletions src/Symfony/Component/Console/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@

namespace Symfony\Component\Console;

use Symfony\Component\Console\Exception\AmbiguousCommandException;
use Symfony\Component\Console\Exception\AmbiguousNamespaceException;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\UnknownCommandException;
use Symfony\Component\Console\Exception\UnknownNamespaceException;
use Symfony\Component\Console\Helper\DebugFormatterHelper;
use Symfony\Component\Console\Helper\ProcessHelper;
use Symfony\Component\Console\Helper\QuestionHelper;
Expand All @@ -36,6 +41,7 @@
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

Expand Down Expand Up @@ -185,7 +191,30 @@ public function doRun(InputInterface $input, OutputInterface $output)
}

// the command name MUST be the first element of the input
$command = $this->find($name);
do {
try {
$command = $this->find($name);
} catch (CommandNotFoundException $e) {
$alternatives = $e->getAlternatives();
if (0 === count($alternatives) || !$input->isInteractive() || !$this->getHelperSet()->has('question')) {
throw $e;
}

$helper = $this->getHelperSet()->get('question');
$question = new ChoiceQuestion(strtok($e->getMessage(), "\n").' Please select one of these suggested commands:', $alternatives);
$question->setMaxAttempts(1);

try {
$name = $helper->ask($input, $output, $question);
} catch (InvalidArgumentException $ex) {
throw $e;
}

if (null === $name) {
throw $e;
}
}
} while (!isset($command));

$this->runningCommand = $command;
$exitCode = $this->doRunCommand($command, $input, $output);
Expand Down Expand Up @@ -477,7 +506,8 @@ public function getNamespaces()
*
* @return string A registered namespace
*
* @throws CommandNotFoundException When namespace is incorrect or ambiguous
* @throws UnknownNamespaceException When namespace is incorrect
* @throws AmbiguousNamespaceException When namespace is ambiguous
*/
public function findNamespace($namespace)
{
Expand All @@ -486,24 +516,12 @@ public function findNamespace($namespace)
$namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);

if (empty($namespaces)) {
$message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);

if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
if (1 == count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
} else {
$message .= "\n\nDid you mean one of these?\n ";
}

$message .= implode("\n ", $alternatives);
}

throw new CommandNotFoundException($message, $alternatives);
throw new UnknownNamespaceException($namespace, $this->findAlternatives($namespace, $allNamespaces, array()));
}

$exact = in_array($namespace, $namespaces, true);
if (count($namespaces) > 1 && !$exact) {
throw new CommandNotFoundException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
throw new AmbiguousNamespaceException($namespace, $namespaces);
}

return $exact ? $namespace : reset($namespaces);
Expand All @@ -519,7 +537,8 @@ public function findNamespace($namespace)
*
* @return Command A Command instance
*
* @throws CommandNotFoundException When command name is incorrect or ambiguous
* @throws UnknownCommandException When command name is incorrect
* @throws AmbiguousCommandException When command name is ambiguous
*/
public function find($name)
{
Expand All @@ -533,18 +552,7 @@ public function find($name)
$this->findNamespace(substr($name, 0, $pos));
}

$message = sprintf('Command "%s" is not defined.', $name);

if ($alternatives = $this->findAlternatives($name, $allCommands)) {
if (1 == count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
} else {
$message .= "\n\nDid you mean one of these?\n ";
}
$message .= implode("\n ", $alternatives);
}

throw new CommandNotFoundException($message, $alternatives);
throw new UnknownCommandException($name, $this->findAlternatives($name, $allCommands, array()));
}

// filter out aliases for commands which are already on the list
Expand All @@ -559,9 +567,7 @@ public function find($name)

$exact = in_array($name, $commands, true);
if (count($commands) > 1 && !$exact) {
$suggestions = $this->getAbbreviationSuggestions(array_values($commands));

throw new CommandNotFoundException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions), array_values($commands));
throw new AmbiguousCommandException($name, array_values($commands));
}

return $this->get($exact ? $name : reset($commands));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Console\Exception;

/**
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class AmbiguousCommandException extends CommandNotFoundException
{
private $command;

public function __construct($command, $alternatives = array(), $code = null, $previous = null)
{
$this->command = $command;
$message = sprintf('Command "%s" is ambiguous (%s).', $command, $this->getAbbreviationSuggestions($alternatives));

parent::__construct($message, $alternatives, $code, $previous);
}

/**
* @return string
*/
public function getCommand()
{
return $this->command;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Console\Exception;

/**
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class AmbiguousNamespaceException extends CommandNotFoundException
{
private $namespace;

public function __construct($namespace, $alternatives = array(), $code = null, $previous = null)
{
$this->command = $namespace;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo $this->namespace = $namespace;


$message = sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions($alternatives));

parent::__construct($message, $alternatives, $code, $previous);
}

/**
* @return string
*/
public function getNamespace()
{
return $this->namespace;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,16 @@ public function getAlternatives()
{
return $this->alternatives;
}

/**
* Returns abbreviated suggestions in string format.
*
* @param array $abbrevs Abbreviated suggestions to convert
*
* @return string A formatted string of abbreviated suggestions
*/
protected function getAbbreviationSuggestions($abbrevs)
{
return sprintf('%s, %s%s', reset($abbrevs), next($abbrevs), count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Console\Exception;

/**
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class UnknownCommandException extends CommandNotFoundException
{
private $command;

public function __construct($command, $alternatives = array(), $code = null, $previous = null)
{
$this->command = $command;

$message = sprintf('Command "%s" is not defined.', $command);

if ($alternatives) {
if (1 == count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
Copy link
Contributor

@ogizanagi ogizanagi Jul 11, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I doubt the exception should format the message rendered in the console itself. Instead, consumers should build the formatted message IMO.

} else {
$message .= "\n\nDid you mean one of these?\n ";
}

$message .= implode("\n ", $alternatives);
}

parent::__construct($message, $alternatives, $code, $previous);
}

/**
* @return string
*/
public function getCommand()
{
return $this->command;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Console\Exception;

/**
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class UnknownNamespaceException extends CommandNotFoundException
{
private $namespace;

public function __construct($namespace, $alternatives = array(), $code = null, $previous = null)
{
$this->namespace = $namespace;

$message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);

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

$message .= implode("\n ", $alternatives);
}

parent::__construct($message, $alternatives, $code, $previous);
}

/**
* @return string
*/
public function getNamespace()
{
return $this->namespace;
}
}
27 changes: 27 additions & 0 deletions src/Symfony/Component/Console/Tests/ApplicationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,33 @@ public function testFindAlternativeCommands()
}
}

public function testFindAlternativeCommandsWithQuestion()
{
$application = new Application();
$application->setAutoExit(false);
putenv('COLUMNS=120');
putenv('SHELL_INTERACTIVE=1');
$application->add(new \FooCommand());
$application->add(new \Foo1Command());
$application->add(new \Foo2Command());

$input = new ArrayInput(array('command' => 'foo'));

$inputStream = fopen('php://memory', 'r+', false);
fwrite($inputStream, "1\n");
rewind($inputStream);
$input->setStream($inputStream);

$output = new StreamOutput(fopen('php://memory', 'w', false), StreamOutput::VERBOSITY_NORMAL, false);

$application->run($input, $output);

rewind($output->getStream());
$display = str_replace(PHP_EOL, "\n", stream_get_contents($output->getStream()));

$this->assertStringEqualsFile(self::$fixturesPath.'/application_unknown_command_question.txt', $display);
}

public function testFindAlternativeCommandsWithAnAlias()
{
$fooCommand = new \FooCommand();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "foo" is not defined.

[Symfony\Component\Console\Exception\UnknownCommandException]
Command "foo" is not defined.


Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "foo" is not define
d.

[Symfony\Component\Console\Exception\UnknownCommandException]
Command "foo" is not define
d.


Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Command "foo" is not defined. Please select one of these suggested commands:
[0] foo:bar1
[1] foo:bar
[2] foo1:bar
[3] afoobar
[4] afoobar1
[5] afoobar2
> 1
interact called
called