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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ Behind the scenes, cpx will install the package into a separate directory and ru

For example, `cpx php-cs-fixer` is an alias for `cpx friendsofphp/php-cs-fixer`, and `cpx laravel` is an alias for `cpx laravel/installer`.

### cpx alias

`cpx alias` lets you create your own shortcut for a package, so you don't have to remember or type its full vendor/package name every time.

```
cpx alias laravel/pint pint
```

Both arguments are optional — if you leave either one out, cpx will prompt you for it. Leaving out the name defaults it to the package's short name, so `cpx alias laravel/pint` alone is enough to create the `pint` alias above.

Your aliases are saved under `~/.cpx/` and shown alongside the built-in ones under `cpx aliases`. They take priority over the built-in aliases, so you can also use `cpx alias` to point an existing alias like `pint` at a different package.

Use `cpx forget <name>` to remove one of your aliases, e.g. `cpx forget pint`. Leave off the name and cpx will prompt you for it.

### cpx list

`cpx list` shows all the packages you have run via cpx and have installed.
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@
},
"require": {
"php": "^8.3",
"laravel/prompts": "^0.3.21",
"symfony/console": "^7.4|^8.0"
},
"require-dev": {
"laravel/pao": "^1.1",
"laravel/pint": "^1.29",
"laravel/prompts": "^0.3.21",
"mockery/mockery": "^1.6",
"pestphp/pest": "^4.7",
"pestphp/pest-plugin-type-coverage": "^4.0",
Expand Down
4 changes: 4 additions & 0 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

namespace Cpx;

use Cpx\Commands\AliasCommand;
use Cpx\Commands\AliasesCommand;
use Cpx\Commands\CleanCommand;
use Cpx\Commands\ExecCommand;
use Cpx\Commands\ForgetCommand;
use Cpx\Commands\ListCommand;
use Cpx\Commands\RunPackageCommand;
use Cpx\Commands\TinkerCommand;
Expand Down Expand Up @@ -52,7 +54,9 @@ private function registerCommands(PackageCommandRunner $packageCommandRunner): v
{
$this->addCommands([
new ListCommand,
new AliasCommand,
new AliasesCommand,
new ForgetCommand,
new CleanCommand,
new UpdateCommand,
new UpgradeCommand,
Expand Down
112 changes: 112 additions & 0 deletions src/Commands/AliasCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

declare(strict_types=1);

namespace Cpx\Commands;

use Cpx\Packages\Package;
use Cpx\Packages\UserAliases;
use InvalidArgumentException;
use Laravel\Prompts\Exceptions\NonInteractiveValidationException;
use Laravel\Prompts\Prompt;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use function Laravel\Prompts\error;
use function Laravel\Prompts\info;
use function Laravel\Prompts\text;

#[AsCommand(
name: 'alias',
description: 'Create a shortcut command for a Composer package',
)]
class AliasCommand extends Command
{
protected function configure(): void
{
$this->addArgument('package', InputArgument::OPTIONAL, 'The package to alias, e.g. <vendor>/<package>[:version]');
$this->addArgument('name', InputArgument::OPTIONAL, 'The alias name to run the package as, e.g. "cpx <name>"');
}

protected function execute(InputInterface $input, OutputInterface $output): int

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should we display a warning/confirmation when user is overriding an existing alias?

{
Prompt::setOutput($output);

try {
$package = $this->resolvePackage($input);
$name = $this->resolveName($input, $package);
} catch (InvalidArgumentException|NonInteractiveValidationException $e) {
Comment thread
TitasGailius marked this conversation as resolved.
error($e->getMessage());

return self::FAILURE;
}

UserAliases::open()->put($name, $package)->save();

info("Alias created: cpx {$name} now runs {$package}.");

return self::SUCCESS;
}

private function resolvePackage(InputInterface $input): Package
{
if ($package = $input->getArgument('package')) {
if ($error = $this->validatePackage($package)) {
throw new InvalidArgumentException($error);
}

return Package::parse($package);
}

return Package::parse(text(
Comment thread
TitasGailius marked this conversation as resolved.
label: 'Which package would you like to alias?',
placeholder: '<vendor>/<package>[:version]',
required: 'A package name must be provided.',
validate: $this->validatePackage(...),
));
}

private function validatePackage(string $value): ?string
{
try {
Package::parse($value);

return null;
} catch (InvalidArgumentException $e) {
return $e->getMessage();
}
}

private function resolveName(InputInterface $input, Package $package): string
{
if ($name = $input->getArgument('name')) {
if ($error = $this->validateName($name)) {
throw new InvalidArgumentException($error);
}

return $name;
}

return text(
label: 'What should the alias be called?',
default: $package->name,
validate: $this->validateName(...),
);
}

private function validateName(string $name): ?string
{
if (preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $name) !== 1) {
return 'An alias name may only contain letters, numbers, dots, dashes and underscores.';
}

if ($this->getApplication()?->has($name) === true) {
return "\"{$name}\" is already a cpx command and cannot be used as an alias name.";
}

return null;
}
}
14 changes: 14 additions & 0 deletions src/Commands/AliasesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Cpx\Packages\PackageAlias;
use Cpx\Packages\PackageAliases;
use Cpx\Packages\UserAliases;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
Expand All @@ -28,6 +29,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$output->writeln(' <info>cpx '.$paddedCommand.'</info> '.$package->description);
}

$userAliases = UserAliases::open()->all();

if ($userAliases !== []) {
ksort($userAliases);

$output->writeln(PHP_EOL.'Your aliases:'.PHP_EOL);

foreach ($userAliases as $name => $package) {
$paddedCommand = str_pad($name, 15);
$output->writeln(' <info>cpx '.$paddedCommand.'</info> '.$package->fullPackageString());
}
}

return self::SUCCESS;
}
}
86 changes: 86 additions & 0 deletions src/Commands/ForgetCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

declare(strict_types=1);

namespace Cpx\Commands;

use Cpx\Packages\UserAliases;
use InvalidArgumentException;
use Laravel\Prompts\Exceptions\NonInteractiveValidationException;
use Laravel\Prompts\Prompt;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use function Laravel\Prompts\error;
use function Laravel\Prompts\info;
use function Laravel\Prompts\select;

#[AsCommand(
name: 'forget',
description: 'Remove a user-defined alias',
)]
class ForgetCommand extends Command
Comment thread
TitasGailius marked this conversation as resolved.
{
protected function configure(): void
{
$this->addArgument('name', InputArgument::OPTIONAL, 'The alias name to remove');
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
Prompt::setOutput($output);

$aliases = UserAliases::open();

if ($aliases->all() === []) {
info('You have no aliases to forget.');

return self::SUCCESS;
}

try {
$name = $this->resolveName($input, $aliases);
} catch (InvalidArgumentException|NonInteractiveValidationException $e) {
error($e->getMessage());

return self::FAILURE;
}

$aliases->forget($name)->save();

info("Alias \"{$name}\" removed.");

return self::SUCCESS;
}

private function resolveName(InputInterface $input, UserAliases $aliases): string
{
if ($name = $input->getArgument('name')) {
if ($error = $this->validateName($name, $aliases)) {
throw new InvalidArgumentException($error);
}

return $name;
}

return (string) select(
label: 'Which alias would you like to forget?',
options: array_keys($aliases->all()),
required: 'An alias name must be provided.',
validate: fn (string $name): ?string => $this->validateName($name, $aliases),
info: fn (string $name): string => (string) $aliases->find($name),
);
}

private function validateName(string $name, UserAliases $aliases): ?string
{
if (! $aliases->has($name)) {
return "No alias named \"{$name}\" was found.";
}

return null;
}
}
6 changes: 6 additions & 0 deletions src/Packages/PackageCommandRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ public function run(PackageInvocation $invocation, OutputInterface $output): int
return (new ExecCommand)->run($this->fileInput($invocation), $output);
}

$userAlias = UserAliases::open()->find($invocation->target);

if ($userAlias !== null) {
return $userAlias->runCommand($invocation, $output);
}

$aliases = PackageAliases::all();

if (array_key_exists($invocation->target, $aliases)) {
Expand Down
79 changes: 79 additions & 0 deletions src/Packages/UserAliases.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

namespace Cpx\Packages;

use Cpx\Support\Filesystem;

class UserAliases
{
private const FILE = 'aliases.json';

/**
* @param array<string, Package> $aliases
*/
protected function __construct(
protected array $aliases = [],
) {}

public static function open(): self
{
$file = cpx_path(self::FILE);

if (! file_exists($file)) {
return new self;
}

$json = json_decode((string) file_get_contents($file), true);

return new self(array_map(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A malformed ~/.cpx/aliases.json (invalid JSON, non-array root, or one bad value) throws and breaks every cpx command, including cpx forget, which is how a user would fix it. Let's mirror the is_array() guard already used in Application::resolveVersion(), bail to an empty state otherwise, and skip individual unparseable entries.

fn (string $value): Package => Package::parse($value),
$json,
));
}

/** @return array<string, Package> */
public function all(): array
{
return $this->aliases;
}

public function has(string $name): bool
{
return array_key_exists($name, $this->aliases);
}

public function find(string $name): ?Package
{
return $this->aliases[$name] ?? null;
}

public function put(string $name, Package $package): self
{
$this->aliases[$name] = $package;

return $this;
}

public function forget(string $name): self
{
unset($this->aliases[$name]);

return $this;
}

public function save(): void
Comment thread
TitasGailius marked this conversation as resolved.
{
Filesystem::writeAtomic(cpx_path(self::FILE), (string) json_encode($this->toArray(), JSON_PRETTY_PRINT));
}

/** @return array<string, string> */
public function toArray(): array
{
return array_map(
fn (Package $package): string => $package->fullPackageString(),
$this->aliases,
);
}
}
Loading