最近在使用一个支付相关的 composer 包时,因为某种原因想要看一下它的 composer.json 文件,发现在它的 composer.json 底部有一个 scripts 属性。是这样的!
"scripts": {
"test": "./vendor/bin/phpunit -c phpunit.xml --colors=always",
"cs-fix": "php-cs-fixer fix --dry-run --diff 1>&2",
"analyse": "phpstan analyse --memory-limit 300M -l 5 -c phpstan.neon ./src"
}
原来这里还能放置脚本在里面,但是具体是怎么用呢?
composer 的 scripts 脚本是通过 KV 键值对来存的,前面的部分是 key,后面的部分是 value,key 是给脚本命名,value 是具体要执行的内容。 想要运行 scripts 中的脚本,可以通过 composer 命令来进行运行,举例如下:
% composer run-script -l
scripts:
test Runs the test script as defined in composer.json
cs-fix Runs the cs-fix script as defined in composer.json
analyse Runs the analyse script as defined in composer.json
通过上面的方式先来查看 composer.json 有什么脚本,然后通过具体的脚本名字就可以运行了,如下:
% composer run-script test
上面的命令就可以运行 scripts 中的脚本内容了。 更多的命令可以参看 composer 的帮助,如下:
% composer run-script -h
Description:
Runs the scripts defined in composer.json
Usage:
run-script [options] [--] [<script> [<args>...]]
run
Arguments:
script Script name to run.
args
Options:
--timeout=TIMEOUT Sets script timeout in seconds, or 0 for never.
--dev Sets the dev mode.
--no-dev Disables the dev mode.
-l, --list List scripts.
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
--profile Display timing and memory usage information
--no-plugins Whether to disable plugins.
--no-scripts Skips the execution of all scripts defined in composer.json file.
-d, --working-dir=WORKING-DIR If specified, use the given directory as working directory.
--no-cache Prevent use of the cache
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Help:
The run-script command runs scripts defined in composer.json:
php composer.phar run-script post-update-cmd
Read more at https://getcomposer.org/doc/03-cli.md#run-script
对于 composer 来说,scripts 可以是 PHP 回调,也可以是任何命令行的可执行命令;对于在 composer 执行过程中执行包的自定义代码或特定于包的命令非常有用。
scripts 中的 key 其实称为 key 不是特别的准确,composer 提供了一些在 composer 执行过程中触发的事件。截图如下:
举几个例子:
详细的学习还是离不开文档,这个文档还是非常详细的,不过我没细看。
文档地址:https://getcomposer.org/doc/articles/scripts.md
评论