Skip to content

Commit f3f8603

Browse files
committed
feat: add support for command name aliases
1 parent 6ca3195 commit f3f8603

18 files changed

Lines changed: 506 additions & 16 deletions

File tree

‎system/CLI/AbstractCommand.php‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ abstract class AbstractCommand
4040
private readonly string $description;
4141
private readonly string $group;
4242

43+
/**
44+
* @var list<non-empty-string>
45+
*/
46+
private readonly array $aliases;
47+
4348
/**
4449
* @var list<non-empty-string>
4550
*/
@@ -138,6 +143,7 @@ public function __construct(private readonly Commands $commands)
138143
$this->name = $attribute->name;
139144
$this->description = $attribute->description;
140145
$this->group = $attribute->group;
146+
$this->aliases = $attribute->aliases;
141147

142148
$this->configure();
143149
$this->provideDefaultOptions();
@@ -165,6 +171,14 @@ public function getGroup(): string
165171
return $this->group;
166172
}
167173

174+
/**
175+
* @return list<non-empty-string>
176+
*/
177+
public function getAliases(): array
178+
{
179+
return $this->aliases;
180+
}
181+
168182
/**
169183
* @return list<non-empty-string>
170184
*/

‎system/CLI/Attributes/Command.php‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,57 @@
2222
#[Attribute(Attribute::TARGET_CLASS)]
2323
final readonly class Command
2424
{
25+
private const NAME_PATTERN = '/^[^\s\:]++(\:[^\s\:]++)*$/';
26+
2527
/**
2628
* @var non-empty-string
2729
*/
2830
public string $name;
2931

3032
/**
33+
* @var list<non-empty-string>
34+
*/
35+
public array $aliases;
36+
37+
/**
38+
* @param list<string> $aliases
39+
*
3140
* @throws LogicException
3241
*/
3342
public function __construct(
3443
string $name,
3544
public string $description = '',
3645
public string $group = '',
46+
array $aliases = [],
3747
) {
3848
if ($name === '') {
3949
throw new LogicException(lang('Commands.emptyCommandName'));
4050
}
4151

42-
if (preg_match('/^[^\s\:]++(\:[^\s\:]++)*$/', $name) !== 1) {
52+
if (preg_match(self::NAME_PATTERN, $name) !== 1) {
4353
throw new LogicException(lang('Commands.invalidCommandName', [$name]));
4454
}
4555

4656
$this->name = $name;
57+
58+
$seen = [];
59+
60+
foreach ($aliases as $alias) {
61+
if ($alias === '' || preg_match(self::NAME_PATTERN, $alias) !== 1) {
62+
throw new LogicException(lang('Commands.invalidCommandAlias', [$alias]));
63+
}
64+
65+
if ($alias === $name) {
66+
throw new LogicException(lang('Commands.commandAliasSameAsName', [$alias]));
67+
}
68+
69+
if (isset($seen[$alias])) {
70+
throw new LogicException(lang('Commands.duplicateCommandAlias', [$alias]));
71+
}
72+
73+
$seen[$alias] = true;
74+
}
75+
76+
$this->aliases = array_values($aliases);
4777
}
4878
}

‎system/CLI/Commands.php‎

Lines changed: 73 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
* Command discovery and execution class.
2828
*
2929
* @phpstan-type legacy_commands array<string, array{class: class-string<BaseCommand>, file: string, group: string, description: string}>
30-
* @phpstan-type modern_commands array<string, array{class: class-string<AbstractCommand>, file: string, group: string, description: string}>
30+
* @phpstan-type modern_commands array<string, array{class: class-string<AbstractCommand>, file: string, group: string, description: string, aliases: list<string>}>
3131
*/
3232
class Commands
3333
{
@@ -49,6 +49,13 @@ class Commands
4949
*/
5050
private array $modernCommands = [];
5151

52+
/**
53+
* Maps an alias name to the canonical modern command name it resolves to.
54+
*
55+
* @var array<string, string>
56+
*/
57+
private array $aliases = [];
58+
5259
/**
5360
* Guards {@see discoverCommands()} from re-scanning the filesystem on repeat calls.
5461
*/
@@ -153,6 +160,16 @@ public function getModernCommands(): array
153160
return $this->modernCommands;
154161
}
155162

163+
/**
164+
* Provide access to the alias map of modern commands.
165+
*
166+
* @return array<string, string> Alias name mapped to its canonical command name.
167+
*/
168+
public function getCommandAliases(): array
169+
{
170+
return $this->aliases;
171+
}
172+
156173
/**
157174
* Checks if a legacy command with the given name has been discovered.
158175
*/
@@ -162,15 +179,16 @@ public function hasLegacyCommand(string $name): bool
162179
}
163180

164181
/**
165-
* Checks if a modern command with the given name has been discovered.
182+
* Checks whether the given name resolves to a modern command, either as a
183+
* command name or as one of its aliases.
166184
*
167-
* A name present in both registries signals a collision; legacy wins
168-
* at runtime. Callers can combine this with {@see hasLegacyCommand()}
169-
* to detect that case.
185+
* A name present in both registries signals a collision. Legacy wins at
186+
* runtime. Callers can combine this with `hasLegacyCommand()` to detect
187+
* that case.
170188
*/
171189
public function hasModernCommand(string $name): bool
172190
{
173-
return array_key_exists($name, $this->modernCommands);
191+
return $this->resolveCommand($name) !== null;
174192
}
175193

176194
/**
@@ -186,15 +204,33 @@ public function getCommand(string $command, bool $legacy = false): AbstractComma
186204
return new $className($this->logger, $this);
187205
}
188206

189-
if (! $legacy && isset($this->modernCommands[$command])) {
190-
$className = $this->modernCommands[$command]['class'];
207+
if (! $legacy) {
208+
$resolved = $this->resolveCommand($command);
191209

192-
return new $className($this);
210+
if ($resolved !== null) {
211+
$className = $this->modernCommands[$resolved]['class'];
212+
213+
return new $className($this);
214+
}
193215
}
194216

195217
throw new CommandNotFoundException($command);
196218
}
197219

220+
/**
221+
* Resolves a modern command name or alias to its canonical command name,
222+
* or `null` when neither matches. The command name takes precedence so an
223+
* alias can never shadow a real command.
224+
*/
225+
private function resolveCommand(string $name): ?string
226+
{
227+
if (isset($this->modernCommands[$name])) {
228+
return $name;
229+
}
230+
231+
return $this->aliases[$name] ?? null;
232+
}
233+
198234
/**
199235
* Discovers all commands in the framework and within user code,
200236
* and collects instances of them to work with.
@@ -247,6 +283,31 @@ public function discoverCommands()
247283
'yellow',
248284
);
249285
}
286+
287+
$this->registerAliases();
288+
}
289+
290+
/**
291+
* Builds the alias map from the discovered modern commands. Fails hard when
292+
* an alias collides with an existing command name or another alias.
293+
*
294+
* @throws LogicException
295+
*/
296+
private function registerAliases(): void
297+
{
298+
foreach ($this->modernCommands as $name => $details) {
299+
foreach ($details['aliases'] as $alias) {
300+
if (isset($this->commands[$alias]) || isset($this->modernCommands[$alias])) {
301+
throw new LogicException(lang('Commands.aliasClashesWithCommandName', [$alias, $name]));
302+
}
303+
304+
if (isset($this->aliases[$alias])) {
305+
throw new LogicException(lang('Commands.aliasClashesWithAlias', [$alias, $name, $this->aliases[$alias]]));
306+
}
307+
308+
$this->aliases[$alias] = $name;
309+
}
310+
}
250311
}
251312

252313
/**
@@ -264,7 +325,7 @@ public function verifyCommand(string $command, array $commands = [], bool $legac
264325
return true;
265326
}
266327

267-
if (isset($this->modernCommands[$command]) && ! $legacy) {
328+
if (! $legacy && $this->resolveCommand($command) !== null) {
268329
return true;
269330
}
270331

@@ -302,7 +363,7 @@ protected function getCommandAlternatives(string $name, array $collection = []):
302363
/** @var array<string, int> */
303364
$alternatives = [];
304365

305-
foreach (array_keys($this->commands + $this->modernCommands) as $commandName) {
366+
foreach (array_keys($this->commands + $this->modernCommands + $this->aliases) as $commandName) {
306367
$lev = levenshtein($name, $commandName);
307368

308369
if ($lev <= strlen($commandName) / 3 || str_contains($commandName, $name)) {
@@ -370,6 +431,7 @@ private function registerModernCommand(ReflectionClass $class, string $file): vo
370431
'file' => $file,
371432
'group' => $attribute->group,
372433
'description' => $attribute->description,
434+
'aliases' => $attribute->aliases,
373435
];
374436
}
375437
}

‎system/Commands/Help.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,15 @@ private function describeHelp(AbstractCommand $command): void
7070
CLI::write($this->addPadding($command->getDescription()));
7171
}
7272

73+
if ($command->getAliases() !== []) {
74+
CLI::newLine();
75+
CLI::write(lang('CLI.helpAliases'), 'yellow');
76+
77+
foreach ($command->getAliases() as $alias) {
78+
CLI::write($this->addPadding($alias));
79+
}
80+
}
81+
7382
$maxPadding = $this->getMaxPadding($command);
7483

7584
if ($command->getArgumentsDefinition() !== []) {

‎system/Commands/ListCommands.php‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,9 @@ private function describeCommandsSimple(): int
4545
{
4646
// Legacy takes precedence on key collision so the listing reflects the
4747
// command that would actually be invoked.
48+
$runner = $this->getCommandRunner();
4849
$commands = array_keys(
49-
$this->getCommandRunner()->getCommands() + $this->getCommandRunner()->getModernCommands(),
50+
$runner->getCommands() + $runner->getModernCommands() + $runner->getCommandAliases(),
5051
);
5152
sort($commands);
5253

@@ -67,14 +68,23 @@ private function describeCommandsDetailed(): int
6768

6869
// Legacy takes precedence on key collision so the listing reflects the
6970
// command that would actually be invoked.
70-
$all = $this->getCommandRunner()->getCommands() + $this->getCommandRunner()->getModernCommands();
71+
$runner = $this->getCommandRunner();
72+
$modern = $runner->getModernCommands();
73+
$all = $runner->getCommands() + $modern;
7174

7275
foreach ($all as $command => $details) {
7376
$maxPad = max($maxPad, strlen($command) + 4);
7477

7578
$entries[] = [$details['group'], $command, $details['description']];
7679
}
7780

81+
// Aliases are listed as their own rows under the group of the command they resolve to.
82+
foreach ($runner->getCommandAliases() as $alias => $canonical) {
83+
$maxPad = max($maxPad, strlen($alias) + 4);
84+
85+
$entries[] = [$modern[$canonical]['group'], $alias, lang('CLI.commandAlias', [$canonical])];
86+
}
87+
7888
usort($entries, static function (array $a, array $b): int {
7989
$cmp = strcmp($a[0], $b[0]);
8090

‎system/Language/en/CLI.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
return [
1616
'altCommandPlural' => 'Did you mean one of these?',
1717
'altCommandSingular' => 'Did you mean this?',
18+
'commandAlias' => '[alias of {0}]',
1819
'commandNotFound' => 'Command "{0}" not found.',
1920
'generator' => [
2021
'cancelOperation' => 'Operation has been cancelled.',
@@ -48,6 +49,7 @@
4849
'cell' => 'Cell view name',
4950
],
5051
],
52+
'helpAliases' => 'Aliases:',
5153
'helpArguments' => 'Arguments:',
5254
'helpAvailableCommands' => 'Available commands:',
5355
'helpDescription' => 'Description:',

‎system/Language/en/Commands.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,17 @@
1313

1414
// Commands language settings
1515
return [
16+
'aliasClashesWithAlias' => 'Command alias "{0}" of the "{1}" command is already used as an alias of the "{2}" command.',
17+
'aliasClashesWithCommandName' => 'Command alias "{0}" of the "{1}" command clashes with an existing command of the same name.',
1618
'arrayArgumentInvalidDefault' => 'Array argument "{0}" must have an array default value or null.',
1719
'arrayArgumentCannotBeRequired' => 'Array argument "{0}" cannot be required.',
1820
'arrayOptionInvalidDefault' => 'Array option "--{0}" must have an array default value or null.',
1921
'arrayOptionMustRequireValue' => 'Array option "--{0}" must require a value.',
2022
'arrayOptionEmptyArrayDefault' => 'Array option "--{0}" cannot have an empty array as the default value.',
2123
'argumentAfterArrayArgument' => 'Argument "{0}" cannot be defined after array argument "{1}".',
24+
'commandAliasSameAsName' => 'Command alias "{0}" cannot be the same as the command name.',
2225
'duplicateArgument' => 'An argument with the name "{0}" is already defined.',
26+
'duplicateCommandAlias' => 'Command alias "{0}" is defined more than once.',
2327
'duplicateCommandName' => 'Warning: The "{0}" command is defined as both legacy ({1}) and modern ({2}). The legacy command will be executed. Please rename or remove one.',
2428
'duplicateOption' => 'An option with the name "--{0}" is already defined.',
2529
'duplicateShortcut' => 'Shortcut "-{0}" cannot be used for option "--{1}"; it is already assigned to option "--{2}".',
@@ -28,6 +32,7 @@
2832
'emptyOptionName' => 'Option name cannot be empty.',
2933
'emptyShortcutName' => 'Shortcut name cannot be empty.',
3034
'flagOptionPassedMultipleTimes' => 'Option "--{0}" is passed multiple times.',
35+
'invalidCommandAlias' => 'Command alias "{0}" is not valid.',
3136
'invalidCommandName' => 'Command name "{0}" is not valid.',
3237
'invalidArgumentName' => 'Argument name "{0}" is not valid.',
3338
'invalidOptionName' => 'Option name "--{0}" is not valid.',
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace Tests\Support\Commands\Modern;
15+
16+
use CodeIgniter\CLI\AbstractCommand;
17+
use CodeIgniter\CLI\Attributes\Command;
18+
use CodeIgniter\CLI\CLI;
19+
20+
#[Command(
21+
name: 'fixture:aliased',
22+
description: 'Fixture command exercising command aliases.',
23+
group: 'Fixtures',
24+
aliases: ['fixture:alias', 'fa'],
25+
)]
26+
final class AliasedCommand extends AbstractCommand
27+
{
28+
protected function execute(array $arguments, array $options): int
29+
{
30+
CLI::write('Ran fixture:aliased.');
31+
32+
return EXIT_SUCCESS;
33+
}
34+
}

0 commit comments

Comments
 (0)