2015-04-01 38 views
2

我想编写一个Bash脚本来使用Git预推钩针对分支名称测试正则表达式。我已经阅读了预推文档,但是我无法将钩子插入到我的应用程序中。任何人有任何建议。预推Git挂钩以确定分支名称是否有效

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 2015-04-01 22:12:31

+0

@Whymarrh我已经添加了我的代码,但我似乎无法得到它当我混帐推动起源 2015-04-01 22:19:19

+1

[ShellCheck](http://www.shellcheck.net/)是你的朋友在未来。 – Whymarrh 2015-04-01 23:13:11

回答

2

运行上面的脚本会导致各种错误。我也不确定你为什么执行^[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 
    echo "$message" 
    exit 1 
fi 

exit 0 
+1

谢谢@Whymarrh。我的代码也放在我的git钩子里的脚本文件夹中。最后不得不把 – 2015-04-02 23:22:49

+0

谢谢@Whymarrh。我最终得到了昨晚深夜,然后意识到我的主要问题是代码坐在我的githooks文件夹内的脚本文件夹,所以我最终添加了一个预推文件,其中包括这个 CURRENT_DIR = $(cd“$ (dirname“$ {BASH_SOURCE [0]}”)“&& pwd) $ CURRENT_DIR/scripts/check-valid-branch-name $ @ – 2015-04-02 23:24:28