-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-commit-message.sh
More file actions
executable file
·335 lines (291 loc) · 10.4 KB
/
generate-commit-message.sh
File metadata and controls
executable file
·335 lines (291 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PS1_SCRIPT="$SCRIPT_DIR/generate-commit-message.ps1"
SCRIPT_NAME="$(basename "$0")"
usage() {
cat >&2 <<EOF
Usage: $SCRIPT_NAME [COMMIT_HASH] [COMMIT_HASH2] [--amend] [-o OUTPUT_FILE] [-a AGENT] [-m MAX_DIFF_LENGTH]
Examples:
$SCRIPT_NAME
$SCRIPT_NAME abc1234
$SCRIPT_NAME abc1234 def5678
$SCRIPT_NAME HEAD~1 -o commit-msg.txt
$SCRIPT_NAME -a copilot
$SCRIPT_NAME --amend
EOF
}
if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
usage
exit 0
fi
# Detect platform - use native bash on macOS/Linux, PowerShell on Windows
USE_NATIVE=0
case "$(uname -s)" in
Darwin|Linux)
USE_NATIVE=1
;;
CYGWIN*|MINGW*|MSYS*)
USE_NATIVE=0
;;
esac
COMMIT_HASH=""
COMMIT_HASH2=""
OUTPUT_FILE=""
AGENT_CMD="${AGENT:-agent}"
MAX_DIFF_LENGTH=12000
AMEND=0
# First non-flag argument is the optional commit hash
if [ $# -gt 0 ] && [ "${1#-}" = "$1" ]; then
COMMIT_HASH="$1"
shift
fi
# Second non-flag argument is the optional second commit hash (for range)
if [ $# -gt 0 ] && [ "${1#-}" = "$1" ]; then
COMMIT_HASH2="$1"
shift
fi
while [ $# -gt 0 ]; do
case "$1" in
--amend) AMEND=1; shift ;;
-o) OUTPUT_FILE="$2"; shift 2 ;;
-a) AGENT_CMD="$2"; shift 2 ;;
-m) MAX_DIFF_LENGTH="$2"; shift 2 ;;
*) echo "Unknown option: $1" >&2; usage; exit 1 ;;
esac
done
# ============================================================================
# NATIVE BASH IMPLEMENTATION (macOS/Linux)
# ============================================================================
if [ $USE_NATIVE -eq 1 ]; then
# --- Validate prerequisites ---
if ! command -v git >/dev/null 2>&1; then
echo "Error: git is not installed or not in PATH." >&2
exit 127
fi
if ! command -v "$AGENT_CMD" >/dev/null 2>&1; then
echo "Error: '$AGENT_CMD' command not found in PATH." >&2
exit 127
fi
# --- Ensure we're in a git repo ---
if ! git rev-parse --show-toplevel >/dev/null 2>&1; then
echo "Error: Not inside a git repository." >&2
exit 1
fi
# --- Resolve source mode ---
if [ $AMEND -eq 1 ]; then
if ! git rev-parse --verify HEAD >/dev/null 2>&1; then
echo "Error: No commits to amend." >&2
exit 1
fi
MODE="amend"
SOURCE_LABEL="amend HEAD (HEAD changes + staged)"
elif [ -n "$COMMIT_HASH" ] && [ -n "$COMMIT_HASH2" ]; then
if ! RESOLVED1=$(git rev-parse --verify "$COMMIT_HASH" 2>&1); then
echo "Error: Invalid commit reference: $COMMIT_HASH" >&2
exit 1
fi
if ! RESOLVED2=$(git rev-parse --verify "$COMMIT_HASH2" 2>&1); then
echo "Error: Invalid commit reference: $COMMIT_HASH2" >&2
exit 1
fi
MODE="range"
SOURCE_LABEL="range ${RESOLVED1:0:8}..${RESOLVED2:0:8}"
elif [ -n "$COMMIT_HASH" ]; then
if ! RESOLVED=$(git rev-parse --verify "$COMMIT_HASH" 2>&1); then
echo "Error: Invalid commit reference: $COMMIT_HASH" >&2
exit 1
fi
MODE="commit"
SOURCE_LABEL="commit ${RESOLVED:0:8}"
else
if git diff --cached --quiet 2>&1; then
echo "Error: No staged changes found. Stage files with 'git add' first, or pass a commit hash." >&2
exit 1
fi
MODE="staged"
SOURCE_LABEL="staged changes"
fi
# --- Parse file status ---
parse_file_status() {
local status="$1"
local file="$2"
case "$status" in
A) echo "added: $file" ;;
M) echo "modified: $file" ;;
D) echo "deleted: $file" ;;
R*) echo "renamed: $file" ;;
C*) echo "copied: $file" ;;
*) echo "$status: $file" ;;
esac
}
# --- Gather context ---
echo "Collecting $SOURCE_LABEL ..." >&2
if [ "$MODE" = "amend" ]; then
DIFF=$(git diff --cached HEAD~1 | tr -d '\0')
STAT=$(git diff --cached HEAD~1 --stat)
FILE_LIST=$(git diff --cached HEAD~1 --name-status | while IFS=$'\t' read -r status file; do
parse_file_status "$status" "$file"
done)
EXISTING_MSG=$(git log -1 --format="%B" HEAD | sed '/^$/d')
elif [ "$MODE" = "range" ]; then
DIFF=$(git diff "$COMMIT_HASH" "$COMMIT_HASH2")
STAT=$(git diff "$COMMIT_HASH" "$COMMIT_HASH2" --stat)
FILE_LIST=$(git diff "$COMMIT_HASH" "$COMMIT_HASH2" --name-status | while IFS=$'\t' read -r status file; do
parse_file_status "$status" "$file"
done)
EXISTING_MSG=$(git log --oneline "$COMMIT_HASH..$COMMIT_HASH2" 2>/dev/null || true)
elif [ "$MODE" = "commit" ]; then
DIFF=$(git diff "$COMMIT_HASH~1" "$COMMIT_HASH" | tr -d '\0')
STAT=$(git diff "$COMMIT_HASH~1" "$COMMIT_HASH" --stat)
FILE_LIST=$(git diff "$COMMIT_HASH~1" "$COMMIT_HASH" --name-status | while IFS=$'\t' read -r status file; do
parse_file_status "$status" "$file"
done)
EXISTING_MSG=$(git log -1 --format="%B" "$COMMIT_HASH" | sed '/^$/d')
else
DIFF=$(git diff --cached | tr -d '\0')
STAT=$(git diff --cached --stat)
FILE_LIST=$(git diff --cached --name-status | while IFS=$'\t' read -r status file; do
parse_file_status "$status" "$file"
done)
EXISTING_MSG=""
fi
BRANCH=$(git branch --show-current 2>/dev/null || echo "(detached HEAD)")
RECENT_LOG=$(git log --oneline -10 2>/dev/null || echo "(no commits yet)")
# Truncate diff if needed
if [ ${#DIFF} -gt $MAX_DIFF_LENGTH ]; then
DIFF="${DIFF:0:$MAX_DIFF_LENGTH}"$'\n'"... [diff truncated at $MAX_DIFF_LENGTH chars] ..."
fi
# --- Build prompt ---
EXISTING_MSG_SECTION=""
if [ -n "$EXISTING_MSG" ]; then
if [ "$MODE" = "range" ]; then
EXISTING_MSG_HEADER="## Commits in Range"
else
EXISTING_MSG_HEADER="## Existing Commit Message"
fi
EXISTING_MSG_SECTION=$'\n\n'"$EXISTING_MSG_HEADER"$'\n\n'"$EXISTING_MSG"
fi
PROMPT=$(cat <<EOF
Generate a git commit message. Format:
<type>: <short description>
- bullet 1
- bullet 2
Rules:
- type is one of: feat, fix, refactor, docs, test, chore, style, perf, ci, build
- Subject line: capitalize first letter, imperative mood, no period, max 50 characters
- Body: 1-3 short bullet points summarizing key changes, separated from subject by a blank line
- Wrap body lines at 72 characters; break mid-sentence if needed to stay within the limit
- Output ONLY the commit message, nothing else — no explanation, no quotes, no markdown fences
# Context
- Source: $SOURCE_LABEL
- Branch: $BRANCH
- Recent commits (for style reference):
$RECENT_LOG$EXISTING_MSG_SECTION
## Changed Files
$FILE_LIST
## Diff Summary
$STAT
## Full Diff
$DIFF
EOF
)
# --- Call agent ---
echo "Generating commit message via $AGENT_CMD ..." >&2
echo "" >&2
# Handle different agent command formats
if [[ "$AGENT_CMD" == *"copilot"* ]]; then
if ! RAW_OUTPUT=$("$AGENT_CMD" -p "$PROMPT" 2>&1); then
echo "Error: Agent call failed." >&2
exit 1
fi
# Clean copilot output: remove stats, tool execution output, and headers
MESSAGE=$(echo "$RAW_OUTPUT" | awk '
BEGIN { in_message = 0; message = ""; }
# Skip usage stats and tool execution lines
/^Total usage est:|^API time spent:|^Total session time:|^Total code changes:|^Breakdown by AI model:|^ claude-|^ gpt-|^●|^ \$|^ └/ { next; }
# Skip empty lines before the message starts
/^[[:space:]]*$/ && in_message == 0 { next; }
# Once we hit content (commit type or already in message), start collecting
/^(feat|fix|refactor|docs|test|chore|style|perf|ci|build):/ { in_message = 1; }
in_message == 1 {
if (message != "") message = message "\n";
message = message $0;
}
END { print message; }
')
else
# Default format for agent.cmd and similar
if ! MESSAGE=$(echo "$PROMPT" | "$AGENT_CMD" -p --trust); then
echo "Error: Agent call failed." >&2
exit 1
fi
fi
# --- Output ---
if [ -n "$EXISTING_MSG" ]; then
if [ "$MODE" = "range" ]; then
EXISTING_LABEL="Existing Commits in Range"
else
EXISTING_LABEL="Existing Commit Message"
fi
echo "" >&2
echo "--- $EXISTING_LABEL ---" >&2
echo "" >&2
echo "$EXISTING_MSG" >&2
fi
echo "" >&2
echo "--- Generated Commit Message ---" >&2
echo "" >&2
echo "$MESSAGE" >&2
if [ -n "$OUTPUT_FILE" ]; then
echo "$MESSAGE" > "$OUTPUT_FILE"
echo "" >&2
echo "Saved to $OUTPUT_FILE" >&2
else
# Try to copy to clipboard (macOS/Linux)
if command -v pbcopy >/dev/null 2>&1; then
echo "$MESSAGE" | pbcopy
echo "" >&2
echo "Copied to clipboard." >&2
elif command -v xclip >/dev/null 2>&1; then
echo "$MESSAGE" | xclip -selection clipboard
echo "" >&2
echo "Copied to clipboard." >&2
fi
fi
exit 0
fi
# ============================================================================
# POWERSHELL FALLBACK (Windows)
# ============================================================================
if [ ! -f "$PS1_SCRIPT" ]; then
echo "Error: $PS1_SCRIPT not found." >&2
exit 1
fi
# Convert Cygwin/MSYS paths to Windows paths for PowerShell
to_win_path() {
if command -v cygpath >/dev/null 2>&1; then
cygpath -w "$1"
else
echo "$1"
fi
}
POWERSHELL=""
for cmd in pwsh powershell.exe powershell; do
if command -v "$cmd" >/dev/null 2>&1; then
POWERSHELL="$cmd"
break
fi
done
if [ -z "$POWERSHELL" ]; then
echo "Error: PowerShell not found (tried pwsh, powershell.exe, powershell)." >&2
exit 1
fi
ARGS=(-ExecutionPolicy Bypass -File "$(to_win_path "$PS1_SCRIPT")")
[ -n "$COMMIT_HASH" ] && ARGS+=("$COMMIT_HASH")
[ -n "$COMMIT_HASH2" ] && ARGS+=("$COMMIT_HASH2")
[ $AMEND -eq 1 ] && ARGS+=(-Amend)
[ -n "$OUTPUT_FILE" ] && ARGS+=(-OutputFile "$(to_win_path "$OUTPUT_FILE")")
[ -n "$AGENT_CMD" ] && [ "$AGENT_CMD" != "agent" ] && ARGS+=(-Agent "$AGENT_CMD")
[ -n "$MAX_DIFF_LENGTH" ] && ARGS+=(-MaxDiffLength "$MAX_DIFF_LENGTH")
"$POWERSHELL" "${ARGS[@]}"