提问者:小点点

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


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

例如。

git add /some/file

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

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

我想知道我可以用什么钩子来做这件事。我不希望得到关于如何编写钩子的帮助,但更希望得到关于我将使用什么git钩子以及我是否需要在提交后更改提交的帮助(比如我需要在提交后执行此操作)。git提交-修改会是什么样子?

提前谢谢


共3个答案

匿名用户

您可以在pready-comen-msg和comen-msg之间进行选择。前者在git提交打开编辑器以编辑提交消息之前调用,后者在之后调用。两者都应该在适当的位置编辑消息文件(作为第一个参数传递的路径)。第一个总是被调用,第二个可以使用git提交--no-验证绕过。退出时的错误代码中止提交。

匿名用户

这并不能直接解决您的问题,但可能有助于实现上面列出的建议。

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

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

匿名用户

如前所述,您可以使用git钩子来操作提交消息。

我不相信我可以使用其中任何一个,因为我需要用户输入消息。

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

githooks手册页:

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.

因此,要替换消息的标题,您可以使用如下内容:

#!/bin/sh

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

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

注意:后缀(例如:. bak)是可移植性所必需的。

即使这样可行,我也建议不要这样做,或者在询问分支概述时,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="$1"
ticket_id="$(sed -E -ne '1s/^#\[([0-9]+)\]/\1/p' <"$file")"
ticket_title="$(call_my_api "ticket_id")"

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

我们的团队通常使用提交消息正文中的部分工单标题来添加一些上下文,并且它运行良好。

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

如何提供准备好的git提交消息?