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

时间:2018-08-01 20:52:09

标签: bash git githooks ticket-system

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

例如

git add /some/file

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

这时,我想获取他们使用的ID,用bash调用我的API,然后将其标题附加到提交中,以便最终得到的提交消息实际上是“#[id] Ticket Title”。

我想知道可以使用哪个钩子来执行此操作。我不是在寻求有关如何编写该钩子的帮助,而是要寻求更多有关我将使用的git钩子的信息,以及在完成后是否需要更改提交的方法(例如,我需要在提交后进行修改)。 git commit --amend会是什么样子?

预先感谢

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

这不能直接解决您的问题,但也许可以帮助实现上述建议。

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

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

答案 2 :(得分:0)

As mentioned,您可以使用git 钩子操作提交消息。

  

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

用户写完消息并退出后,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="$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)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

这在分支上有数十个与 一张票。

相反,您可以保留 commit消息标题来描述what the commit does,而只需将 ticket标题附加到 讯息:

#!/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"

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


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

How to provide a prepared git commit message?