From f4a89b14abc7df8633fce47fd05dd150f5c411df Mon Sep 17 00:00:00 2001 From: Guilherme Branco Stracini Date: Fri, 13 Dec 2024 15:50:10 +0000 Subject: [PATCH] Create prepare-commit-msg --- .githooks/prepare-commit-msg | 60 ++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 .githooks/prepare-commit-msg diff --git a/.githooks/prepare-commit-msg b/.githooks/prepare-commit-msg new file mode 100644 index 0000000..5c78620 --- /dev/null +++ b/.githooks/prepare-commit-msg @@ -0,0 +1,60 @@ +#!/usr/bin/env sh + +# This script generates an AI-powered commit message using dotnet-aicommitmessage. +# It can be bypassed by setting the GIT_AICOMMIT_SKIP environment variable. + +# Exit immediately if GIT_AICOMMIT_SKIP is set +if [ -n "$GIT_AICOMMIT_SKIP" ]; then + exit 0 +fi + +# Check if dotnet-aicommitmessage is installed and in PATH +if ! command -v dotnet-aicommitmessage >/dev/null 2>&1; then + echo "Error: dotnet-aicommitmessage is not installed or not in PATH" >&2 + echo "Please install it by running 'dotnet tool install -g aicommitmessage'" >&2 + exit 1 +fi + +# Ensure the commit message file is provided +if [ -z "$1" ]; then + echo "Error: Commit message file not provided" >&2 + exit 1 +fi + +COMMIT_MSG_FILE="$1" + +# Check if the commit message file exists +if [ ! -f "$COMMIT_MSG_FILE" ]; then + echo "Error: Commit message file '$COMMIT_MSG_FILE' not found" >&2 + exit 1 +fi + +# Read the current commit message +CURRENT_MESSAGE=$(cat "$COMMIT_MSG_FILE") + +# Backup the commit message file +cp "$COMMIT_MSG_FILE" "${COMMIT_MSG_FILE}.bak" + +# Generate the AI commit message +if ! AI_MESSAGE=$(dotnet-aicommitmessage generate-message -m "$CURRENT_MESSAGE" 2>/dev/null); then + echo "Error: Failed to generate AI commit message. Using original message." >&2 + exit 0 +fi + +# Check if the generated message is empty +if [ -z "$AI_MESSAGE" ] || echo "$AI_MESSAGE" | grep -q '^[[:space:]]*$'; then + echo "Error: Generated commit message is empty." >&2 + exit 1 +fi + +# Write the new commit message back to the file +if ! echo "$AI_MESSAGE" > "$COMMIT_MSG_FILE" 2>/dev/null; then + echo "Error: Failed to write new commit message" >&2 + cp "${COMMIT_MSG_FILE}.bak" "$COMMIT_MSG_FILE" + rm "${COMMIT_MSG_FILE}.bak" + exit 1 +fi + +# Remove the backup file +rm "${COMMIT_MSG_FILE}.bak" +exit 0