-
-
Save sirbrillig/16e36c8ea0a0f1b49171a2cb81a7df2e to your computer and use it in GitHub Desktop.
Shortcut to run commands in vendor/bin for PHP Composer projects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
$vendorBinDirectory = './vendor/bin'; | |
$helpMessage = "Shortcut to run commands in vendor/bin for Composer projects | |
Usage: cpx <command> | |
<command> must be an executable file in the vendor/bin directory. | |
Read about vendor binaries here: | |
https://getcomposer.org/doc/articles/vendor-binaries.md | |
"; | |
function printCommand($command) { | |
echo $command . "\n"; | |
} | |
function getCommands($directory) { | |
if (! file_exists($directory)) { | |
return []; | |
} | |
return array_diff((scandir($directory) ?: []), ['..', '.']); | |
} | |
function getCommandArgs($argv) { | |
// From: http://php.net/manual/en/function.getopt.php | |
$optind = null; | |
$opts = getopt('', [], $optind); | |
$commandArgs = array_slice($argv, $optind + 1); | |
return $commandArgs; | |
} | |
// ------ | |
if (empty($argv[1])) { | |
echo $helpMessage; | |
$commands = getCommands($vendorBinDirectory); | |
if (empty($commands)) { | |
echo "No commands are currently installed. Use Composer to install packages to this directory.\n"; | |
} else { | |
echo "Currently available commands:\n\n"; | |
array_map('printCommand', $commands); | |
} | |
die(1); | |
} | |
$command = $argv[1]; | |
$pathToCommand = $vendorBinDirectory . '/' . $command; | |
$commandArgsString = implode(' ', getCommandArgs($argv)); | |
$fullCommand = $pathToCommand . ' ' . $commandArgsString; | |
echo "Running command: $fullCommand\n"; | |
echo shell_exec($fullCommand); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This command does not capture stderr, nor returns the exit code of the command, nor pass the stdin to the command. It seems crucial for me :-).
Modulo the help message and errors, the following shell script should do the job: