gpt4 book ai didi

git - 在pre-push hook中,获取 "git push"命令的全部内容?

转载 作者:太空狗 更新时间:2023-10-29 13:12:00 26 4
gpt4 key购买 nike

当 Git pre-push hooks 脚本运行时,如何获取完整的 git push 命令内容?

例如,当我运行:git push origin master 时,执行了预推 Hook 。
我想在这个钩子(Hook)中获取 origin & master

如何获取参数列表?

最佳答案

TL;DR 总结:你需要一个 while 循环

你的钩子(Hook)脚本(假设是 sh/bash)应该包含一个如下形式的循环:

while read localname localhash remotename remotehash; do
... code here using $localname etc ...
done

描述

the githooks page 中描述了所有 Git 钩子(Hook). pre-push 钩子(Hook)描述开始于:

This hook is called by git push and can be used to prevent a push from taking place. The hook is called with two parameters which provide the name and location of the destination remote, if a named remote is not being used both values will be the same.

Information about what is to be pushed is provided on the hook’s standard input with lines of the form:

<local ref> SP <local sha1> SP <remote ref> SP <remote sha1> LF

For instance, if the command git push origin master:foreign were run the hook would receive a line like the following:

refs/heads/master 67890 refs/heads/foreign 12345

although the full, 40-character SHA-1s would be supplied. ...

第一段表示在 shell 脚本中,$1$2 是远程的名称——例如,origin——及其URL,或者在用户运行时重复两次的 URL:

git push https://some.host.name/some/path ...

第二重要git push 命令可以推送多个分支。例如,我可以运行:

git push origin feature-A feature-B

同时推送feature-A feature-B。您必须阅读所有 输入行,一次一行,以发现要推送的内容。存储库中的当前 分支并不重要:读取HEAD 会给您错误的答案,除非用户恰好推送当前分支。另一方面,大多数用户大多只是推送当前分支。这会给你一种错觉,以为你的钩子(Hook)是 100% 可靠的,而实际上它只有 92.37% 可靠。1

如文档所述, Hook 获取每个引用的全名。如果你推送一个分支,全名以 refs/heads/ 开头,但你可以推送一个标签,在这种情况下,全名以 refs/tags/ 开头.要编写可靠的 Hook ,您必须检查全名,而不是简单地剥离前两个部分。2


1像38.61%的统计​​,这个是当场编造的。 :-)

2有很多糟糕的示例 Hook (并非所有都是预推 Hook )使用:

branch=$(echo $ref | cut -d/ -f3)

如果您正在推送标签 v2.3,此 Hook 将认为您正在推送一个名为 v2.3分支。如果你正在推送一个名为 bugfix/1234 的分支,它会认为你正在推送一个名为 bugfix 的分支! cut 技术是错误的,但后者的快速修复是使用 -f3-,它至少会产生 bugfix/1234。最好验证 ref 的第一个组件——即,执行如下操作:

case $ref in
refs/heads/*) ... it's a branch ...;;
refs/tags/*) ... it's a tag ...;;
*) ... it's something else entirely, such as refs/notes/* ...;;
esac

一旦知道了前缀,就可以使用${ref#refs/heads/}${ref#refs/tags/}去除已知的前缀并获取完整但不合格的分支或标记名称。但是,如果很多情况,您可以直接使用完整的引用名称。

关于git - 在pre-push hook中,获取 "git push"命令的全部内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42455506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com