用于确定分支名称是否有效的 Git 钩子:Pre-push。

6
我想编写一个 Bash 脚本,用 Git 的 pre-push hook 来测试正则表达式与分支名称匹配。我已经阅读了 pre-push 文档,但是在将 hook 应用于我的应用程序时遇到了麻烦。有人有什么建议吗?
local_branch = $(git rev-parse --abbrev-ref HEAD)
valid_chars = $(^[a-z0-9-]+$)

if [[ "$local_branch" =~ valid_chars]]; then
  echo 'Failed to push.  Branch is using incorrect characters.  Valid        Characters are lower case (a-z), numbers (0-9) and dashes(-).  Please rename branch to continue'
  exit 1
fi

exit 0

1
你具体遇到了什么问题? - Whymarrh
@Whymarrh 我已经添加了我的代码,但似乎无法在我 git push origin <branch> 时触发。 - panda-king
1
ShellCheck 是你未来的好朋友。 - Whymarrh
1个回答

8
运行上面的脚本会导致各种错误。我也不确定为什么要执行 ^ [a-z0-9-] + $ 并将结果存储在 valid_chars 中。尽管如此:
  • 如果分支名称不匹配正则表达式,您可能想要退出并显示错误
  • 在测试中,您忘记了为 valid_chars 添加 $ 前缀
  • if [[ "$local_branch" =~ valid_chars]]; then 应该在]]内部有一个空格

和往常一样,请确保脚本在 .git/hooks/pre-push 下,名称正确,并标记为可执行。

以下是适合我的代码(我因为懒惰而保留了示例钩子注释):

#!/bin/bash

# An example hook script to verify what is about to be pushed.  Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed.  If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
#   <local ref> <local sha1> <remote ref> <remote sha1>
#
# This sample shows how to prevent push of commits where the log message starts
# with "WIP" (work in progress).

local_branch="$(git rev-parse --abbrev-ref HEAD)"
valid_chars="^[a-z0-9-]+$"
message='...'

if [[ ! $local_branch =~ $valid_chars ]]
then
    printf '%s\n' "$message"
    exit 1
fi

exit 0

1
感谢@Whymarrh。我也把我的代码放在了git钩子的脚本文件夹里。最终不得不把它放到其他地方。 - panda-king
感谢@Whymarrh。昨晚我最终得到了它,然后意识到我的主要问题是代码坐落在githooks文件夹内的scripts文件夹中,所以我最终添加了一个pre-push文件,其中包括以下内容:CURRENT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )$CURRENT_DIR/scripts/check-valid-branch-name $@ - panda-king
使用$1代替HEAD。因为推送的分支可能不是当前分支。(传递给git钩子的第一个参数是分支名称) - David

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接