Git 挂钩以使用来自 API 的数据更新提交消息

Git hook to update commit message with data from an API

我正在尝试使用我们的票务 API 中的详细信息更新 git 提交。我想获取开发人员添加到 git 提交中的票号的标题,并使用该标题更新提交。

例如

git add /some/file

git commit -am "#[id]
Did some work
Other stuff I Did"

此时我想获取他们使用的 Id,在 bash 中调用我的 API,然后将标题附加到提交,因此生成的提交消息实际上是“#[id ] 票标题。

我想知道我可以使用什么钩子来做到这一点。我不希望获得有关如何编写挂钩的帮助,但更重要的是我会使用什么 git 挂钩,以及是否需要在提交后更改提交(比如我需要在 post 犯罪)。 git commit --amend 会是什么样子?

提前致谢

您可以选择prepare-commit-msg and commit-msg。前者在 git commit 打开编辑器编辑提交消息之前调用,后者在之后调用。两者都应该就地编辑消息文件(作为第一个参数传递的路径)。第一个总是被调用,第二个可以用 git commit --no-verify 绕过。退出时的错误代码中止提交。

As mentioned,你可以使用githooks来操作commit message

I don't believe I can use either of those as I need the user to enter message.

commit-msg 钩子在用户写入消息并退出 编辑器,但在提交之前。

来自githooks man page:

commit-msg
    This hook is invoked by git-commit(1) and git-merge(1), and can be
    bypassed with the --no-verify option. It takes a single parameter, the
    name of the file that holds the proposed commit log message. Exiting
    with a non-zero status causes the command to abort.

    The hook is allowed to edit the message file in place, and can be used
    to normalize the message into some project standard format. It can also
    be used to refuse the commit after inspecting the message file.

    The default commit-msg hook, when enabled, detects duplicate
    "Signed-off-by" lines, and aborts the commit if one is found.

所以对于 replace the title 的消息,你可以使用这样的东西:

#!/bin/sh

file=""
ticket_id="$(sed -E -ne '1s/^#([0-9]+)//p' <"$file")"
ticket_title="$(call_my_api "ticket_id")"

sed -i.bak -e "1s/.*/#$ticket_id $ticket_title/" "$file"

注意:后缀(例如:.bak)is required是为了便于移植。


即使这样可行,我还是建议不要这样做,或者在要求 分支概览,git log --oneline 会给你这个:

#123 Foo is returning error 418
#123 Foo is returning error 418
#123 Foo is returning error 418
#123 Foo is returning error 418
#123 Foo is returning error 418

这在一个有几十个相关提交的分支上会特别糟糕 一张票。

相反,您可以留下提交消息标题来描述 提交确实,并且只是将票证标题附加到 留言:

#!/bin/sh

file=""
ticket_id="$(sed -E -ne '1s/^#\[([0-9]+)\]//p' <"$file")"
ticket_title="$(call_my_api "ticket_id")"

printf -- '\n%s\n' "$ticket_title" >>"$file"

我们的团队通常在提交消息中使用部分工单标题 body 添加一些上下文,效果很好。


更新:发现了类似的尝试(但基于分支名称):

How to provide a prepared git commit message?

这并不能直接解决您的问题,但也许可以帮助实施上面列出的建议。

我写了一个小工具来帮助 git 挂钩管理。

https://pypi.org/project/hooks4git/