git - 当我根据提交消息提交时,如何更改 package.json 版本?

标签 git typescript gulp githooks husky

我尝试在提交时更改 package.json 文件的版本,但前提是提交消息的前缀正确:MJ 前缀会触发补丁更改,^ 前缀会触发轻微的碰撞。我编写了一个 gulp 任务来执行此操作并且它有效,唯一的问题是我无法获取当前提交的消息,执行任务,然后将 package.json 添加到提交并继续。

我尝试在这两个 git hook 上运行我的任务:

预提交

问题:

  • 我只能访问此 Hook 中的上一个提交消息,而不能访问我们现在正在执行的提交消息。

什么有效

  • 我可以更改版本,但只能基于之前的提交消息
  • 我可以暂存 package.json
  • 然后可以将 package.json 与其余内容一起添加到提交中

准备提交消息

问题:

  • 暂存 package.json 不会将其添加到提交

什么有效

  • 我可以根据当前提交消息更改版本
  • 我可以暂存 package.json

这是我用两个钩子(Hook)尝试过的 gulp 任务。我消除了一些噪音以尽量减少噪音。

import * as fs from "fs";
import gulp from "gulp";
import * as shell from "shelljs";
import pkg from "./package.json";

const getCommitMsg = () => fs.readFileSync(".git/COMMIT_EDITMSG", "utf8");
gulp.task(
    BUMP_VERSION.task,
        (done) => {

            const message = getCommitMsg();
            const isMinor = message.startsWith(MINOR_PREFIX);
            const isPatch = message.startsWith(PATCH_PREFIX);

            if (!isMinor && !isPatch) {
                done();
                return exit(EC.NOT_VERSION);
            }

            const newPatch = isPatch ? parseInt(patch) + 1 : 0;
            const newMinor = isMinor ? parseInt(minor) + 1 : minor;

            const newVersion = `${major}.${newMinor}.${newPatch}`;
            const newPkg = Object.assign({}, pkg, { version: newVersion }); // update version
            fs.writeFileSync("./package.json", JSON.stringify(newPkg, null, 4));

            shell.exec("git add ./package.json");

            done();
        },
);

几乎所有事情都依赖于提交消息,该消息是使用 getCommitMsg 函数获取的。也许 fs.readFileSync(".git/COMMIT_EDITMSG", "utf8"); 不是正确的方法?也许我可以运行另一个命令(使用 shelljs)来获取 pre-commit Hook 中的当前提交消息?否则,如果我使用 prepare-commit-msg Hook ,那么我可以获得正确的消息,但是如何将其与其他暂存文件一起添加到当前提交中?

最佳答案

您可以使用 commit-msg Hook 来读取提交消息、根据该消息采取操作、暂存文件并提交

.git/hooks/commit-msg

COMMIT_MSG_FILE=$1

node bump.js
git add package.json
git commit -m "`cat $COMMIT_MSG_FILE`" --no-verify
false

node Bump.js 将增加 package.json 中的版本(类似于您的 gulp 任务)

git add package.json 将暂存修改后的文件

git commit -m "cat $COMMIT_MSG_FILE"--no-verify 将提交暂存文件,但跳过 Hook (预提交和提交消息)

false 将停止原始提交,因为我们已经在最后一行提交了

关于git - 当我根据提交消息提交时,如何更改 package.json 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55427220/

相关文章:

Angular 6 - 如何在服务中使用 Observable 等待本地存储中存在 Okta token

typescript - Angular2 将@Inputs 与<router-outlet> 一起使用

node.js - 如何在 Gulp 中从字符串创建文件?

Git,必须pull,知道会有冲突,但是本地版本无关

git refs/pull/... 与 pull/

typescript - 如何在 typescript 中覆盖合并命名空间中的函数

node.js - gulp 咖啡 watch 永远不会因错误而结束

git - '致命的 : HTTP request failed' error when pulling from git repository

Git 按文件类型 merge

javascript - 使用 gulp 缩小 es2017