如何配置git忽略ELF文件类型?

How to configure git to ignore the ELF file type?

理想情况下,我想将特定文件类型添加到 .gitignore 文件,而不是通过查看扩展名,而是查看文件类型。

例如,我可以检查来自

的return代码
file some/file | grep -q ELF

如果 return 代码为零,我不想将文件添加到提交中。有没有办法通过编辑 .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