0
理想情況下,我想向.gitignore文件添加特定的文件類型,而不是通過查看擴展名,而是查看文件類型。如何配置git忽略ELF文件類型?
我可以例如從
file some/file | grep -q ELF
檢查返回代碼,如果返回代碼爲零,我不希望將文件添加到提交。有沒有辦法通過編輯.gitignore文件或編寫某種類型的git鉤子來實現這一點?
理想情況下,我想向.gitignore文件添加特定的文件類型,而不是通過查看擴展名,而是查看文件類型。如何配置git忽略ELF文件類型?
我可以例如從
file some/file | grep -q ELF
檢查返回代碼,如果返回代碼爲零,我不希望將文件添加到提交。有沒有辦法通過編輯.gitignore文件或編寫某種類型的git鉤子來實現這一點?
使用pre-commit
掛鉤,您可以防止添加這樣的文件,即使提交失敗,甚至可以靜默地從索引中刪除它們(使用git rm --cached "$filename"
)。你也可以用.gitignore
或.git/info/exclude
填充所有這些文件的列表,以便它們不再以git狀態出現,但這有點危險 - 如果以後將文件更改爲您希望保留在歷史中的腳本你應該記得從忽略列表中刪除它。
PS:如評論建議,添加鉤子的例子。它應該是.git/hooks/pre-commit
中的可執行文件。請注意,這僅僅是一個例子,我沒有對它進行徹底的測試。
#!/bin/sh
# --porcelain prints filenames either plain, or quoted with
# double-quotes and all special symbols as backspash sequences.
# another option is to add also '-z' which uses NUL delimiters
# and no quoting but handling such format with shell is complicated
git status --porcelain | while read -r st qfile; do
if test "$st" != "A"; then
# the operation is not adding; let it pass
continue
fi
case "$qfile" in
*\\*) # for special symbol handling, probably shell is really not a reasonable choice
printf "Unsupported filename: %s\n" "$qfile"
exit 1;;
*' "') # trailing spaces need special care in gitignore; do not worth efforts
printf "Unsupported filename: %s\n" "$qfile"
exit 1;;
'"'*'"') # we excluded all quoting, what's left are spaces only, just bite them off
qfile1="${qfile%\"}"
file="${qfile1#\"}";;
*) # simple case
file="$qfile";;
esac
type=$(file -b -i "$file")
# the value to compare to is what file from Debian wheezy prints for binaries,
# I don't know how portable this value is
if test "$type" = "application/x-executable; charset=binary"; then
git rm --cached "$file"
printf "/%s\n" "$file" >>.git/info/exclude
fi
done
執行張貼在討論的要求,以及如何安裝它會改善這個答案有很多的質量信息的pre-commit鉤子的簡單例子(並使其更切合票; - )) – axiac
@axiac謝謝,增加了這個例子 – max630