Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save klondikemarlen/042039a7061077573141dbf237962335 to your computer and use it in GitHub Desktop.
Save klondikemarlen/042039a7061077573141dbf237962335 to your computer and use it in GitHub Desktop.
README, Setting Up Better Context for GPT Agent via Global Git Hooks, 2025-02-19.md

Setting Up Better Context for GPT Agent via Global Git Hooks

Follow these steps to configure a global Git hooks directory and set up a prepare-commit-msg hook that appends diffs to commit messages.

Step 1: Create a Global Hooks Directory

  1. Create a directory ~/.git/hooks to store your global hooks.
    mkdir -p ~/.git/hooks

Step 2: Configure Git to Use the Global Hooks Directory

  1. Configure Git to use ~/.git/hooks as the global hooks directory.
    git config --global core.hooksPath ~/.git/hooks

Step 3: Create the commit-msg Hook

  1. Create the commit-msg hook file and make it executable.
    touch ~/.git/hooks/commit-msg
    chmod +x ~/.git/hooks/commit-msg
  2. Edit and add the following to the file.
    #!/bin/bash
    
    # The commit message file
    COMMIT_MSG_FILE="$1"
    
    # Remove lines starting with #
    sed -i '/^#/d' "$COMMIT_MSG_FILE"
    
    exit 0

Step 4: Create the prepare-commit-msg Hook

  1. Create the prepare-commit-msg hook file and make it executable.
    touch ~/.git/hooks/prepare-commit-msg
    chmod +x ~/.git/hooks/prepare-commit-msg
  2. Edit the prepare-commit-msg file and add the following script:
    #!/bin/sh
    
    # The first argument is the path to the commit message file
    commit_msg_file="$1"
    commit_source="$2"  # The second argument indicates the source (e.g., commit, merge, cherry-pick)
    
    # Exit if a rebase is in progress
    if [ -d "$(git rev-parse --git-dir)/rebase-merge" ] || [ -d "$(git rev-parse --git-dir)/rebase-apply" ]; then
      exit 0
    fi
    
    # Exit if this is a cherry-pick
    if [ -f "$(git rev-parse --git-dir)/CHERRY_PICK_HEAD" ]; then
      exit 0
    fi
    
    # Append the diff to the commit message file as comments without overriding the existing message
    git diff --cached | sed 's/^/# /' >> "$commit_msg_file"

Verification

To verify that your global hook is working:

  1. Stage some changes:

    git add <your-files>
  2. Commit the changes:

    git commit

When the commit message editor opens, you should see the default commit message template followed by the diff of the staged changes commented out at the bottom.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment