npm - 将 git commit 消息传递给 npm 脚本并附加到预定义的字符串
问题描述
在 NPM 项目中,我希望每个构建版本都有一个提交。这将允许我回到当前的构建版本,修复一个错误,而无需通过新版本的所有 QA。
我们可以使用这样的 npm 脚本提交(参见这个答案):
包.json
"scripts": {
"git": "git add . && git commit -m",
}
然后通过运行调用脚本:
npm run git -- "Message of the commit"
我想在 npm run build 之后自动运行它。为此,我们可以创建一个新命令。
包.json
"scripts": {
"buildAndCommit": "npm run build && git add . && git commit -m",
}
这可以使用npm run buildAndCommit -- "commit for a new build"
剩下的唯一一件事是我想将此提交标识为可以链接到提交的提交。是否可以使用“”自动启动消息BUILD -
并添加在命令行中传递的唯一消息?就像是:
包.json
"scripts": {
"buildAndCommit": "npm run build && git add . && git commit -'Build' + $uniqueMessageFromTheCommandLine`",
}
如果无法在package.json中对字符串进行模板化,我如何使用命令行脚本来实现它?(Powershell 是我的命令行工具)。
解决方案
在 *nix 平台上运行
在*nix平台上,npmsh
默认使用来执行 npm 脚本。在这种情况下,您可以简单地使用shell 函数并使用$1
位置参数引用通过 CLI 传递的 git 消息参数。
您的 npm 脚本将像这样重新定义:
"scripts": {
"build": "...",
"buildAndCommit": "func() { npm run build && git add . && git commit -m \"BUILD - $1\"; }; func"
}
跨平台
不幸的是,通过 Windows Powershell 解决方案并不那么简单和简洁。
使用 Powershell 时,npmcmd
默认利用执行 npm 脚本。同样,默认情况下 npmcmd
也通过其他 Windows 控制台使用,例如Command Prompt。
实现您的要求的一种方法是通过您的 npm 脚本调用 node.js。下面提供两种不同的方法,它们本质上是相同的。两者都将成功跨平台运行(在您的情况下通过 Powershell)。
方法 A - 使用单独的 node.js 脚本
创建以下 node.js 脚本。让我们将文件命名为script.js并将其保存在项目目录的根目录下,即与package.json所在的目录相同。
脚本.js
const execSync = require('child_process').execSync; const mssg = 'BUILD - ' + process.argv[2]; execSync('npm run build && git add . && git commit -m \"' + mssg + '\"', { stdio:[0, 1, 2] });
解释
内置的 node.js
process.argv
捕获索引 2 处的参数,即通过 CLI 提供的 git 提交消息。git 提交消息与子字符串连接BUILD -
以形成所需的提交消息。结果字符串被分配给变量mssg
。然后我们利用 node.js 内置
execSync()
来执行你给定的 npm 脚本。如您所见,mssg
变量的值用作 git commit 消息。该
stdio
选项用于确保在父进程和子进程之间建立管道的正确配置,即stdin
, “stderr”。stdout
定义你的 npm 脚本,命名
buildAndCommit
如下:包.json
"scripts": { "build": "...", "buildAndCommit": "node script" }
上面
node
调用script.js
.
方法 B - 在 npm 脚本中内联 node.js 脚本
或者,可以在您的 npm 脚本中内联提供上述 node.js 脚本(即script.js) - 因此否定使用单独的.js
文件。
包.json
"scripts": {
"build": "...",
"buildAndCommit": "node -e \"const mssg = 'BUILD - ' + process.argv[1]; require('child_process').execSync('npm run build && git add . && git commit -m \\\"' + mssg + '\\\"', { stdio:[0, 1, 2] })\""
}
这使用了方法 A中的相同代码,尽管它略有重构。显着的区别是:
- nodejs 命令行选项
-e
用于评估内联 JavaScript。 process.argv
这一次将在参数数组的索引 1 处捕获参数,即 git 提交消息。- 双引号的额外转义是必要的,即
\\\"
运行 npm 脚本
使用方法 A或方法 B根据需要通过 CLI 运行命令:例如:
$ npm run buildAndCommit -- "commit for a new build"
这将产生以下 git commit 消息:
BUILD - commit for a new build
推荐阅读
- twilio - Twilio Taskrouter - 如何向自定义任务添加信息?
- python - 使用 PIP 安装后,Windows 上的 Visual Code 找不到模块。在终端窗口中使用错误的 Python?
- postgresql - 如何将decrypt_iv() 函数的输出格式转换为postgres 中的文本?
- c - 在具有二维数组的程序中调试 SIGABRT 错误
- sas - 按 ID 在多行上对 SAS 中的成功进行分组,其中至少 1 次成功算作成功
- node.js - typedi + fastify - 异步初始化服务
- javascript - 猫鼬检查 id 是否存在,但该 id 嵌套在数组中
- swift - Swift 和 Curl 和 SAML
- r - 使用 != 和 == 在 filter() 中不匹配
- hybris - 如何从 hybris 的本地化 .properties 文件中向属性添加参数?