Search code examples
gitpushcommitgit-commitgit-push

Git - programatically prevent ability to commit or push


My use case:
I have a project where I have to add one line of code so it runs on my machine. Before committing and pushing it I have to remove this line of code again.
I often forget this so I was wondering if I could write a tool where I can "raise a flag", which prevents me to commit or to push a commit until I "remove" the flag again.
Is there a way to create some kind of lock file or set a setting so that git bash refuses my commit/push?


Solution

  • You can create a pre-commit hook by placing a file with execute permissions in .git/hook/pre-commit.

    This script could check if the line exists, and if so, return a non zero exit code and thus abort the commit:

    #!/bin/sh
    
    if grep -q '^Line to remove$' myfile.txt; then
      echo 'You forgot to remove the line from myfile.txt'
      exit 1
    fi
    

    You could similarly do this in pre-push hook by placing the file at .git/hook/pre-push.

    You could also have the hook forcefully remove this line and add then git add this file, although I personally wouldn't like a hook automatically staging files I didn't intend to.