Skip to content
Snippets Groups Projects

Common pre-commit.sh

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Alexander Wellbrock

    A common pre-commit script that uses git stash to prepare a clean environment to execute commit tests before opening the commit message editor.

    Activate locally with ln -s ../../pre-commit.sh .git/hooks/pre-commit

    Edited
    pre-commit.sh 458 B
    #!/bin/sh
    
    restoreStash() {
        # Restore stash
        if git stash list | grep -w "$STASH_NAME" >/dev/null; then
            git stash pop -q
        fi
    }
    
    trap restoreStash EXIT
    
    # Stash unstaged changes before running tests
    STASH_NAME="pre-commit-$(date +%s)"
    git stash save -q --keep-index "$STASH_NAME"
    
    # Test prospective commit
    ./test.sh
    RESULT="$?"
    if [ "$RESULT" -ne 0 ]; then 
        echo "Error: commit has errors, rejected."
        exit 1
    fi
    
    restoreStash
    exit 0
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment