2017-08-07 29 views
3

我想要求SVGs從一切分別致力於保持一切吸塵器的DIFF產量政策。例如,我想禁止提交像這樣的:git的承諾,用於隔離更改特定文件作爲單獨提交

$ git status 
On branch master 
Changes to be committed: 
    (use "git reset HEAD <file>..." to unstage) 

     new file: src/css/main.css 
     modified: src/images/example.svg 
     modified: src/index.html 

可以這樣用一個pre-commit鉤子做了什麼?這將如何寫?

編輯:我認爲git ls-files -dmo將在這裏很有用,但我不知道怎麼寫的腳本來分析它的輸出。

+0

請不要追加_solved_的標題。相反,請考慮將答案標記爲已接受。這會告訴其他人現在問題已經解決了。謝謝。 – Bugs

回答

2

可以這樣用一個pre-commit鉤子做了什麼?

是的。 (但是,請注意,這樣的掛鉤可以被旁路。)

這將如何寫?

取決於你想用把它寫什麼語言。

Shell腳本往往是最簡單的,因爲你可以直接運行的Git工具。在這裏,你可能會遇到git diff-index --name-status到索引(建議提交)比較當前即HEAD提交,然後通過文件中讀取被添加,修改或刪除,以查看是否有任何與.svg結尾的名稱,如果任何有名字結束與其他任何東西。這可以讓你調整規則,允許刪除 .svg文件,同時進行其他更改。或者,如果文件的狀態(添加/刪除/修改)是不相關的,這是一個有點簡單:

# straight from the sample pre-commit hook 
if git rev-parse --verify HEAD >/dev/null 2>&1 
then 
     against=HEAD 
else 
     # Initial commit: diff against an empty tree object 
     against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 
fi 

# create a temp file to hold diff output 
tmpfile=$(mktemp) 
trap "rm -f $tmpfile; exit" 0 1 2 3 15 
git diff-index --cached --name-only --diff-filter=ADM $against > $tmpfile 

# read the status and names from the temp file. 
# we use a temp file simply because "| while read ..." runs 
# a sub-shell which means that variable changes don't make 
# it back to the parent shell. there are other workarounds 
# but this one is simple. 
num_svg=0 
num_nonsvg=0 
while read name; do 
    case "$name" in 
    *.svg) num_svg=$((num_svg + 1));; 
    *) num_nonsvg=$((num_nonsvg + 1));; 
    esac 
done < $tmpfile 

# now disallow commit if there are mixed svg and non-svg files 
if [ $num_svg -gt 0 -a $num_nonsvg -gt 0 ]; then 
    echo "this commit affects both .svg files and non-svg files" 1>&2 
    exit 1 
fi 
# run any other checks here too 
exit 0 

(注:這是完全未經測試)

+0

上述腳本將阻止提交,如果它有一個svg文件。但是,我們是否可以允許不使用svg文件的提交,並將svg文件添加到鉤子腳本本身的新提交中?注意:這可能不是OP要求的。但我正在尋找這樣的解決方案 – karthick

+0

@ karthick:理論上可以讓一個鉤子做出自己的單獨提交,但這是一個壞主意。不要這樣做:寫一個腳本來完成提交。該腳本可以禁用任何鉤子(使用'--no-verify')或設置控制鉤子的環境變量(使用你喜歡的任何代碼)。 – torek

+0

'git ls-files -dmo -exclude-standard'會產生與你的'git diff-index'命令相同的結果嗎? –

相關問題