2010-04-20 39 views
3

這是怎麼回事在this pre-commit hook?我認爲更改文件會導致它們被重新整理。這個預提交鉤子如何修復尾隨空格?

#!/bin/sh 
# 
# A git hook script to find and fix trailing whitespace 
# in your commits. Bypass it with the --no-verify option 
# to git-commit 
# 

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 
# Find files with trailing whitespace 
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -r 's/:[0-9]+:.*//' | uniq` ; do 
    # Fix them! 
    sed -i 's/[[:space:]]*$//' "$FILE" 
done 

# Now we can commit 
exit 

我認爲這個想法是去掉結尾的空白在這次提交觸及的所有文件。

回答

2

的關鍵是提交正確的內容,那就是:

  • 只什麼一直階段(和添加到索引)
  • 加上由引入了一些修改pre-commit鉤子

第一點是通過git diff-index

實現比較的內容和模式O ˚F經由樹對象與當前索引的內容和,任選地忽略磁盤上的文件的統計狀態中發現的斑點。

exec git diff-index --check --cached $against -- 

與選項--cached

不考慮在所有

任何修改磁盤上的文件,然後考慮是新的一部分提交。

你可以看看source of commit.c

static int prepare_to_commit(const char *index_file, const char *prefix, 
       struct wt_status *s) 
{ 
... 

    if (!no_verify && run_hook(index_file, "pre-commit", NULL)) 
     return 0; 
... 


/* 
* Re-read the index as pre-commit hook could have updated it, 
* and write it out as a tree. We must do this before we invoke 
* the editor and after we invoke run_status above. 
*/ 
discard_cache(); 
read_cache_from(index_file); 
+0

對索引*進行的任何修改都會被考慮到,是的。儘管如此,您仍然需要在'pre-commit'鉤子中'git add'修改任何文件。 – sschuberth 2014-08-27 21:55:15

3

除了這行不通。我試着做我的預提交掛鉤的末尾以下內容:

exec git diff-index --check --cached $against -- 

但在那些掛鉤所做的更改仍然沒有真正得到承諾(至少在Git的1.7.3.4)。

如果你真的想改變進去,必須明確

git add "$file" 

爲您在改變的每個文件提交前的階段。

0

這是可能做到這一點,但需要一個棘手的腳本。

在這裏你可以找到解決同樣的問題。在那裏,它會在每次提交時更新文件版本,而不是查詢空間。這是完全正常工作: https://github.com/addonszz/Galileo/tree/master/githooks

然後你只需替換該文件的「版本文件替換」算法「updateVersion.sh」,你的「特里林空間」算法。也許你需要改變喜歡的幾件事情,去掉分公司的限制,因爲在那裏,如果你在「發展」分支腳本只運行。

而且,它只會改變文件,如果上演。如果文件沒有上演,那麼它什麼都不會做。更準確地說,它會打印出每一步所做的事情。