Search code examples
bashfile-permissionsgithooks

Git pre-commit hook: Prevent commits that contain executable files


I'm trying to avoid accidentally committing binaries into my repo. I considered a hook that detects filesizes above some threshold but I think it will be more useful to fail the pre-commit hook anytime my commit changes a file with an executable permission bit.

I know how to tackle this with python/ruby/other scripting languages but ideally I can do it with just bash. Any ideas?


Solution

  • I ended up with this. It lists the filenames being committed relative to REPO_ROOT. It passes those to ls with -1 flag for one-per-line and -F flag that appends * to executables. It greps for trailing *. Any matching grep fails the hook.

    cd $REPO_ROOT
    STAGED_EXECUTABLES=$(git diff --diff-filter=ACMRTUXB --cached HEAD --name-only | xargs ls -1F | egrep '\*$')
    EXECUTABLES_MISSING=$?
    if [ $EXECUTABLES_MISSING -eq 0 ]; then
        echo "You tried to commit an executable file. Override with \`git commit --no-verify\` if required." > /dev/stderr
        exit 1
    fi