Raja's Exocortex

Git-commit.sh - Automated Git Commit Message Generator using Gemini CLI

Automate git commit message generation with the Gemini CLI. This script analyzes staged changes and generates a concise, descriptive commit message following standard conventions.

#!/bin/bash
# Filename: /usr/local/bin/git-commit.sh
# Automated Git Commit Message Generator
#
# This script uses the Gemini CLI to analyze staged git changes and generate
# a concise, descriptive commit message following standard conventions.
#
# Usage:
#   1. Stage your changes: git add <files>
#   2. Run this script: ./git-commit.sh
#
# Prerequisites:
#   - git
#   - gemini-cli (configured and available in PATH)

set -euo pipefail

# Check if we are in a git repository
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "Error: Not a git repository." >&2
  exit 1
fi

# Check if there are staged changes
if git diff --cached --quiet; then
  echo "No staged changes found. Please stage files before committing."
  exit 0
fi

echo "Generating commit message..."

# Get the diff of staged changes
diff=$(git diff --cached)

# Use gemini-cli to generate a commit message
prompt="Generate a concise and descriptive git commit message for the following changes. 
Use the imperative mood (e.g., 'fix', 'add', 'refactor').
Provide ONLY the commit message text, no explanations or markdown backticks:

$diff"

commit_msg=$(gemini --allowed-mcp-server-names="" --allowed-tools="" --prompt "$prompt")

if [[ -z "${commit_msg//[[:space:]]/}" ]]; then
  echo "Error: Failed to generate a valid commit message." >&2
  exit 1
fi

echo -e "\nProposed commit message:"
echo "--------------------------"
echo "$commit_msg"
echo "--------------------------"

# Prompt for confirmation
read -rp "Do you want to commit with this message? (y/n): " confirm

if [[ "$confirm" =~ ^[Yy]$ ]]; then
  git commit -m "$commit_msg"
  exit 0
fi

echo "Commit aborted."
exit 1