gpt4 book ai didi

git - 预推 Git 钩子(Hook)以确定分支名称是否有效

转载 作者:太空狗 更新时间:2023-10-29 14:45:37 24 4
gpt4 key购买 nike

我想编写一个 Bash 脚本来使用 Git 预推送 Hook 针对分支名称测试正则表达式。我已阅读推送前文档,但无法将钩子(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

最佳答案

运行上面的脚本会导致各种错误。我也不确定您为什么要执行 ^[a-z0-9-]+$ 并将结果存储在 valid_chars 中。尽管如此:

  • 如果分支名称与正则表达式不匹配,您可能希望退出并报错
  • 您在测试中缺少 valid_chars$ 前缀
  • if [[ "$local_branch"=~ valid_chars]];那么应该在]]
  • 里面有一个空格

一如既往,确保脚本在 .git/hooks/pre-push 下,正确命名,并标记为可执行。

以下对我有用(因为我很懒,我留下了示例钩子(Hook)评论):

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

关于git - 预推 Git 钩子(Hook)以确定分支名称是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29400369/

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