首页 > 解决方案 > 将 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 是我的命令行工具)。

标签: npmcommand-linenpm-scripts

解决方案


在 *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 脚本

  1. 创建以下 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.jsprocess.argv捕获索引 2 处的参数,即通过 CLI 提供的 git 提交消息。git 提交消息与子字符串连接BUILD -以形成所需的提交消息。结果字符串被分配给变量mssg

    • 然后我们利用 node.js 内置execSync()来执行你给定的 npm 脚本。如您所见,mssg变量的值用作 git commit 消息。

    • stdio选项用于确保在父进程和子进程之间建立管道的正确配置,即stdin, “stderr”。stdout

  2. 定义你的 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


推荐阅读