diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a3aa700 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Force LF +* text eol=lf diff --git a/.php-commitizen.php b/.php-commitizen.php new file mode 100644 index 0000000..8c77023 --- /dev/null +++ b/.php-commitizen.php @@ -0,0 +1,41 @@ + [ + 'lengthMin' => 3, + 'lengthMax' => 8, + 'acceptExtra' => false, + 'values' => [ + 'feat', + 'fix', + 'docs', + 'chore', + 'test', + 'refactor', + 'revert', + 'ci', + ] + ], + 'scope' => [ + 'lengthMin' => 0, + 'lengthMax' => 10, + 'acceptExtra' => true, + 'values' => [], + ], + 'description' => [ + 'lengthMin' => 1, + 'lengthMax' => 47, + ], + 'subject' => [ + 'lengthMin' => 1, + 'lengthMax' => 69, + ], + 'body' => [ + 'wrap' => 72, + ], + 'footer' => [ + 'wrap' => 72, + ], +]; diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..563c415 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,59 @@ + + +For the full copyright and license information, please view the LICENCE +file that was distributed with this source code. +EOF; + +return (new PhpCsFixer\Config()) + ->setUsingCache(true) + ->setRiskyAllowed(true) + ->setFinder( + (new PhpCsFixer\Finder()) + ->files() + ->name('*.php') + ->in(__DIR__) + ->exclude(__DIR__.'/vendor') + ) + ->setRules([ + '@PSR2' => true, + '@Symfony' => true, + 'is_null' => true, + 'blank_line_before_statement' => ['statements' => ['continue', 'declare', 'return', 'throw', 'try']], + 'cast_spaces' => ['space' => 'single'], + 'header_comment' => ['header' => $header], + 'include' => true, + 'class_attributes_separation' => ['elements' => ['const' => 'one', 'method' => 'one', 'property' => 'one']], + 'no_blank_lines_after_class_opening' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_empty_statement' => true, + 'no_extra_blank_lines' => true, + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_unused_imports' => true, + 'no_whitespace_in_blank_line' => true, + 'object_operator_without_whitespace' => true, + 'phpdoc_align' => true, + 'phpdoc_indent' => true, + 'phpdoc_no_access' => true, + 'phpdoc_no_package' => true, + 'phpdoc_order' => true, + 'phpdoc_scalar' => true, + 'phpdoc_trim' => true, + 'phpdoc_types' => true, + 'psr_autoloading' => true, + 'array_syntax' => ['syntax' => 'short'], + 'declare_strict_types' => true, + 'single_blank_line_before_namespace' => true, + 'standardize_not_equals' => true, + 'ternary_operator_spaces' => true, + 'trailing_comma_in_multiline' => true, + ]) +; diff --git a/CHANGELOG.md b/CHANGELOG.md index 12fd545..07d8b3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). +## [1.1.10][] +#### Added +- Added `which()` function + +#### Changed +- Refactor of `run_command()` function to return an exit code + ## [1.1.9][] #### Added - Added `run_command()` function diff --git a/LICENCE b/LICENCE index cb582d5..d91ed67 100644 --- a/LICENCE +++ b/LICENCE @@ -3,7 +3,7 @@ unless otherwise specified, released under the MIT licence as follows: ----- begin license block ----- -Copyright 2019-2020 Alannah Kearney +Copyright 2019-2021 Alannah Kearney Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index bf596c6..5de4990 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # PHP Helpers: Command-line Functions -- Version: v1.1.9 -- Date: April 06 2020 +- Version: v1.1.10 +- Date: July 29 2021 - [Release notes](https://github.com/pointybeard/helpers-functions-cli/blob/master/CHANGELOG.md) - [GitHub repository](https://github.com/pointybeard/helpers-functions-cli) @@ -28,6 +28,8 @@ This library is a collection convenience function for command-line tasks. They a The following functions are provided: +- `run_command()` +- `which()` - `can_invoke_bash()` - `is_su()` - `run_command()` @@ -48,6 +50,9 @@ use pointybeard\Helpers\Cli\Input; use pointybeard\Helpers\Cli\Colour\Colour; use pointybeard\Helpers\Functions\Cli; +var_dump(Cli\which("ls")); +// string(11) "/usr/bin/ls" + var_dump(Cli\can_invoke_bash()); // bool(true) diff --git a/composer.json b/composer.json index e61fcd0..87779c7 100644 --- a/composer.json +++ b/composer.json @@ -3,6 +3,11 @@ "description": "A collection of functions relating to the command-line", "homepage": "https://github.com/pointybeard/helpers-functions-cli", "license": "MIT", + "minimum-stability": "stable", + "support": { + "issues": "https://github.com/pointybeard/helpers-functions-cli/issues", + "wiki": "https://github.com/pointybeard/helpers-functions-cli/wiki" + }, "authors": [ { "name": "Alannah Kearney", @@ -21,11 +26,13 @@ "pointybeard/helpers-functions-debug": "~1.0", "pointybeard/helpers-exceptions-readabletrace": "~1.0.0" }, - "support": { - "issues": "https://github.com/pointybeard/helpers-functions-cli/issues", - "wiki": "https://github.com/pointybeard/helpers-functions-cli/wiki" + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.0", + "squizlabs/php_codesniffer": "^3.0", + "damianopetrungaro/php-commitizen": "^0.1.0", + "php-parallel-lint/php-parallel-lint": "^1.0", + "php-parallel-lint/php-console-highlighter": "^0.5.0" }, - "minimum-stability": "stable", "autoload": { "psr-4": { "pointybeard\\Helpers\\Functions\\": "src/" @@ -33,5 +40,12 @@ "files": [ "src/Cli/Cli.php" ] + }, + "scripts": { + "tidy": "php-cs-fixer fix -v --using-cache=no", + "tidyDry": "@tidy --dry-run", + "test": [ + "parallel-lint . --exclude vendor" + ] } } diff --git a/src/Cli/Cli.php b/src/Cli/Cli.php index dfa54fd..79e4f9f 100644 --- a/src/Cli/Cli.php +++ b/src/Cli/Cli.php @@ -2,14 +2,116 @@ declare(strict_types=1); +/* + * This file is part of the "PHP Helpers: Command-line Functions" repository. + * + * Copyright 2019-2021 Alannah Kearney + * + * For the full copyright and license information, please view the LICENCE + * file that was distributed with this source code. + */ + namespace pointybeard\Helpers\Functions\Cli; -use pointybeard\Helpers\Cli\Input; +use Exception; use pointybeard\Helpers\Cli\Colour; -use pointybeard\Helpers\Functions\Flags; -use pointybeard\Helpers\Functions\Strings; +use pointybeard\Helpers\Cli\Input; use pointybeard\Helpers\Functions\Arrays; use pointybeard\Helpers\Functions\Debug; +use pointybeard\Helpers\Functions\Flags; +use pointybeard\Helpers\Functions\Strings; + +/* + * Uses proc_open() to run a command on the shell. Output and errors are captured + * and returned. If the command "fails" to run (i.e. return code is != 0), this + * function will throw an exception. + * + * Note that some commands will return a non-zero status code to signify, for + * example, no results found. This function is unable to tell the difference and + * will trigger an exception regardless. In this instance, It is advised to trap + * that exception and inspect both $stderr and $stdout to decide if it was + * actually due to failed command execution. + * + * @param string $command the full bash command to run + * @param string $stdout (optional) reference to capture output from STDOUT + * @param string $stderr (optional) reference to capture output from STDERR + * #param string $exitCode (options) reference to capture the command exit code + * + * @throws RunCommandFailedException + */ +if (!function_exists(__NAMESPACE__.'\run_command')) { + function run_command(string $command, string &$stdout = null, string &$stderr = null, int &$exitCode = null): void + { + $pipes = null; + $exitCode = null; + + $proc = proc_open( + "{$command};echo $? >&3", + [ + 0 => ['pipe', 'r'], // STDIN + 1 => ['pipe', 'w'], // STDOUT + 2 => ['pipe', 'w'], // STDERR + 3 => ['pipe', 'w'], // Used to capture the exit code + ], + $pipes, + getcwd(), + null + ); + + // Close STDIN stream + fclose($pipes[0]); + + // (guard) proc_open failed to return a resource + if (false == is_resource($proc)) { + throw new Exceptions\RunCommandFailedException($command, 'proc_open() returned FALSE.'); + } + + // Get contents of STDOUT and close stream + $stdout = trim(stream_get_contents($pipes[1])); + fclose($pipes[1]); + + // Get contents od STDERR and close stream + $stderr = trim(stream_get_contents($pipes[2])); + fclose($pipes[2]); + + // Grab the exit code then close the stream + if (false == feof($pipes[3])) { + $exitCode = (int) trim(stream_get_contents($pipes[3])); + } + fclose($pipes[3]); + + // Close the process we created + proc_close($proc); + + // (guard) proc_close return indiciated a failure + if (0 != $exitCode) { + // There was some kind of error. Throw an exception. + // If STDERR is empty, in effort to give back something + // meaningful, grab contents of STDOUT instead + throw new Exceptions\RunCommandFailedException($command, true == empty(trim($stderr)) ? $stdout : $stderr); + } + } +} + +/* + * Returns the pathname for a specified command (or null if it cannot be found) + * + * @params $command the name of the command to look for + * + * @returns string|null + */ +if (!function_exists(__NAMESPACE__.'\which')) { + function which(string $command): ?string + { + try { + run_command("which {$command}", $output); + } catch (Exception $ex) { + $output = null; + } + + return $output; + } +} /* * Checks if bash can be invoked. @@ -67,7 +169,7 @@ if (!function_exists(__NAMESPACE__.'usage')) { : $a->name() ); } - $arguments = trim(implode($arguments, ' ')); + $arguments = trim(implode(' ', $arguments)); return sprintf( 'Usage: %s [OPTIONS]... %s%s', @@ -115,13 +217,13 @@ if (!function_exists(__NAMESPACE__.'manpage')) { // Add the arguments, if there are any. if (false === empty($arguments)) { $sections[] = $heading('Arguments:'); - $sections[] = $colourise(implode($arguments, PHP_EOL)).PHP_EOL; + $sections[] = $colourise(implode(PHP_EOL, $arguments)).PHP_EOL; } // Add the options, if there are any. if (false === empty($options)) { $sections[] = $heading('Options:'); - $sections[] = $colourise(implode($options, PHP_EOL)).PHP_EOL; + $sections[] = $colourise(implode(PHP_EOL, $options)).PHP_EOL; } // Iterate over all additional items and add them as new sections @@ -130,7 +232,7 @@ if (!function_exists(__NAMESPACE__.'manpage')) { $sections[] = $colourise($contents).PHP_EOL; } - return implode($sections, PHP_EOL); + return implode(PHP_EOL, $sections); } } @@ -144,7 +246,7 @@ if (!function_exists(__NAMESPACE__."\display_error_and_exit")) { $edgePadding = str_repeat($padCharacter, $edgePaddingLength); // Convenience function for adding the background to a line. - $add_background = function (string $string, bool $bold = false) use ($padCharacter, $edgePadding, $background): string { + $add_background = function (string $string, bool $bold = false) use ($edgePadding, $background): string { $string = $edgePadding.$string.$edgePadding; return Colour\Colour::colourise( @@ -210,54 +312,3 @@ if (!function_exists(__NAMESPACE__."\display_error_and_exit")) { exit(1); } } - -/* - * Uses proc_open() to run a command on the shell. Output and errors are captured - * and returned. If the command "fails" to run (i.e. return code is != 0), this - * function will throw an exception. - * - * Note that some commands will return a non-zero status code to signify, for - * example, no results found. This function is unable to tell the difference and - * will trigger an exception regardless. In this instance, It is advised to trap - * that exception and inspect both $stderr and $stdout to decide if it was - * actually due to failed command execution. - * - * @param string $command the full bash command to run - * @param string $stdout (optional) reference to capture output from STDOUT - * @param string $stderr (optional) reference to capture output from STDERR - * - * @throws RunCommandFailedException - */ -if (!function_exists(__NAMESPACE__.'\run_command')) { - function run_command(string $command, string &$stdout = null, string &$stderr = null): void - { - $pipes = null; - $return = null; - - $proc = proc_open( - $command, - [ - ['pipe', 'r'], // STDIN - ['pipe', 'w'], // STDOUT - ['pipe', 'w'], // STDERR - ], - $pipes, - getcwd(), - null - ); - - if (true == is_resource($proc)) { - $stdout = trim(stream_get_contents($pipes[1])); - $stderr = trim(stream_get_contents($pipes[2])); - - // Check the return code. If it's not 0, then the command failed. - if (0 != proc_close($proc)) { - throw new Exceptions\RunCommandFailedException($command, (string) $stderr); - } - } else { - // Something went horribly wrong with proc_open(). This should - // nearly never happen, but, accounting for it regardless. - throw new Exceptions\RunCommandFailedException($command, 'proc_open() returned FALSE'); - } - } -} diff --git a/src/Cli/Exceptions/RunCommandFailedException.php b/src/Cli/Exceptions/RunCommandFailedException.php index 492900f..3665808 100644 --- a/src/Cli/Exceptions/RunCommandFailedException.php +++ b/src/Cli/Exceptions/RunCommandFailedException.php @@ -2,6 +2,15 @@ declare(strict_types=1); +/* + * This file is part of the "PHP Helpers: Command-line Functions" repository. + * + * Copyright 2019-2021 Alannah Kearney + * + * For the full copyright and license information, please view the LICENCE + * file that was distributed with this source code. + */ + namespace pointybeard\Helpers\Functions\Cli\Exceptions; use pointybeard\Helpers\Exceptions\ReadableTrace; @@ -9,6 +18,7 @@ use pointybeard\Helpers\Exceptions\ReadableTrace; class RunCommandFailedException extends ReadableTrace\ReadableTraceException { private $command; + private $error; public function __construct(string $command, string $error, int $code = 0, \Exception $previous = null)