set -e
COMMIT_MSG_FILE=$1
COMMIT_MSG_TYPE=$2
COMMIT_SOURCE=$3
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
if [ -z "$REPO_ROOT" ] || [ ! -d "$REPO_ROOT" ]; then
echo "Error: Not in a valid Git repository."
exit 1
fi
check_aigitcommit() {
if ! command -v aigitcommit >/dev/null 2>&1; then
echo "Error: aigitcommit is not installed."
echo "Please install it first: https://github.com/mingcheng/aigitcommit"
exit 0
fi
}
has_staged_changes() {
git diff --cached --quiet
return $?
}
is_message_empty() {
! grep -Eq '^[[:space:]]*[^#[:space:]]' "$COMMIT_MSG_FILE"
}
get_editor() {
local editor=""
if editor=$(git var GIT_EDITOR 2>/dev/null); then
if [ -n "$editor" ] && [ "$editor" != ":" ]; then
printf '%s' "$editor"
return 0
fi
fi
if [ -n "$VISUAL" ]; then
printf '%s' "$VISUAL"
return 0
fi
if [ -n "$EDITOR" ]; then
printf '%s' "$EDITOR"
return 0
fi
printf '%s' "vi"
return 0
}
generate_commit_message() {
local temp_file
temp_file=$(mktemp)
echo "🚀 Generating commit message using aigitcommit..."
echo "This may take a few seconds..."
if ! aigitcommit "$REPO_ROOT" --save "$temp_file" >/dev/null 2>&1; then
echo "Error: aigitcommit failed to generate commit message."
rm -f "$temp_file"
exit 1
fi
cat "$COMMIT_MSG_FILE" >>"$temp_file"
mv -f "$temp_file" "$COMMIT_MSG_FILE"
}
check_aigitcommit
SHOULD_RUN_AIGITCOMMIT=0
SHOULD_OPEN_EDITOR=0
case "$COMMIT_MSG_TYPE" in
message)
if is_message_empty; then
SHOULD_RUN_AIGITCOMMIT=1
SHOULD_OPEN_EDITOR=1
else
exit 0
fi
;;
template|merge|squash|commit)
exit 0
;;
"")
SHOULD_RUN_AIGITCOMMIT=1
SHOULD_OPEN_EDITOR=0
;;
*)
exit 0
;;
esac
if has_staged_changes; then
echo "No staged changes detected. Aborting commit."
exit 1
fi
if [ "$SHOULD_RUN_AIGITCOMMIT" -eq 1 ]; then
generate_commit_message
fi
if [ "$SHOULD_OPEN_EDITOR" -eq 1 ]; then
editor_cmd=$(get_editor)
if [ -z "$editor_cmd" ] || [ "$editor_cmd" = ":" ]; then
echo "Error: Could not determine editor to use."
exit 1
fi
eval "$editor_cmd" '"$COMMIT_MSG_FILE"' || {
echo "Error: Failed to open editor: $editor_cmd"
exit 1
}
fi
exit 0