Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git pre-commit hook: Prevent commits that change particular files

Tags:

git

githooks

I have a few .json files under my project that contain several keys. These keys must not be under version control. I replaced those actual keys with fake ones in my project in order to prevent build fails on continuous integration.

However, developers need to copy/paste these files on their laptop before they are able to test the app.

Now, the problem is a developer might forget and mistakenly commit them into git. I want to run a pre-commit script that checks modified files and fails the commit if one of them is being added.

Is there any way I can do that?

like image 710
Hesam Avatar asked Jan 25 '23 20:01

Hesam


1 Answers

Prevent it on the developer side with a pre-commit hook. Note that git commit --no-verify will bypass this safety mechanism.

The code below blocks any changes at all to files dir/key1.json and key2.json.

#!/bin/sh

# full paths from the repo root separated by newlines
MUST_NOT_CHANGE='dir/key1.json
key2.json'

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

exec 1>&2

if git diff --cached --name-only $against |
   grep --quiet --line-regexp --fixed-strings "$MUST_NOT_CHANGE"
then
  echo Commit would modify one or more files that must not change.
  exit 1
else
  exit 0
fi

The pre-receive hook below that must be installed on your central repository rejects any push that would modify the protected files.

#!/bin/sh

# full paths from the repo root separated by newlines
MUST_NOT_CHANGE='dir/key1.json
key2.json'

z40=0000000000000000000000000000000000000000

while read old_value new_value ref_name
do
  if [ "$old_value" = $z40 ]; then
    # New branch: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
  else
    against=$old_value
  fi

  if git diff --name-only $against..$new_value |
     grep --quiet --line-regexp --fixed-strings "$MUST_NOT_CHANGE"
  then
    echo "$ref_name" may commit key, rejected ... >&2
    exit 1
  fi
done

In action:

$ git push origin master
Counting objects: 10, done.
Delta compression using up to 40 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (10/10), 820 bytes | 410.00 KiB/s, done.
Total 10 (delta 1), reused 0 (delta 0)
remote: refs/heads/master may commit key, rejected ...
To '<URL>'
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to '<URL>'
like image 180
Greg Bacon Avatar answered Jan 28 '23 10:01

Greg Bacon