Skip to content

Instantly share code, notes, and snippets.

@basilfx
Last active May 31, 2023 08:36
Show Gist options
  • Save basilfx/c1573358117fe3363a60 to your computer and use it in GitHub Desktop.
Save basilfx/c1573358117fe3363a60 to your computer and use it in GitHub Desktop.
Git add-then-commit confirmation
# Git commit protection
check_git() {
python ~/.shell/git-check-add.py $* && $GIT_BIN $*
}
GIT_BIN=`which git`
alias git=check_git
compdef check_git=git

Git add-then-commit confirmation

Confirm git commit -am before you accidentally commit everything.

Note: git-hooks would have been an option if they were system-wide.

Installation

  • Store git-check-add.py somewhere
  • Add the contents of .profile to your .profile. Adapt path to git-check-add.py

Tested with zsh only.

Example

Example session where it prevents you from accidentally committing all files.

> git add file*.txt
> git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   fileA.txt
        modified:   fileB.txt
        modified:   fileC.txt
        modified:   fileD.txt
        modified:   fileE.txt

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   IDontWantThisFileYetA.txt
        modified:   IDontWantThisFileYetB.txt
        modified:   IDontWantThisFileYetC.txt
> git commit -am "Added files A-E"
Confirm add-then-commit [Yn]: n
> git commit -m "Added files A-E"
[master] Added files A-E
 5 files changed, 100 insertion(+), 0 deletions(-)
#!/usr/bin/env python
import sys
def main():
command = " ".join(sys.argv)
if "commit -am" in command:
sys.stdout.write("Confirm add-then-commit [yN]: ")
if sys.stdin.read(1).lower() != "y":
return 1
# Execute original command
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment