2015-04-01 39 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