Repository navigation
Expand file tree
/
Copy pathinstall-git-commit-ai.sh
More file actions
executable file
·2833 lines (2629 loc) · 101 KB
/
Copy pathinstall-git-commit-ai.sh
File metadata and controls
executable file
·2833 lines (2629 loc) · 101 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
# Sets up AI-generated git commit messages and branch names with mittwald AI:
# installs cmai and configures it. For commit messages, it installs a
# prepare-commit-msg hook into the git template directory. For branch names, it
# installs the command `git branch-ai`.
#
# Runs with bash 3.2 or later on Linux, macOS and Windows (Git Bash).
#
# Everything runs from main() at the end of the file, so that a partially
# downloaded script (curl | bash) does nothing.
set -euo pipefail
# cmai is third-party code. The installer downloads the latest version, checks
# the script for unexpected content (see cmai_script_findings) and installs the
# script itself. No downloaded code runs during the installation.
# CMAI_REPO, CMAI_BIN_DIR and CMAI_KEYCHAIN_ENTRY can be set in the
# environment. The tests use them to stay inside a sandbox.
CMAI_REPO="${CMAI_REPO:-https://github.com/mrgoonie/cmai.git}"
CMAI_INSTALL_DIR="${HOME}/git-commit-ai"
# Options that this installer, the hook and the git branch-ai command need.
# Older cmai versions lack them.
CMAI_REQUIRED_OPTIONS=(--message-only --branch-name-only --print-config --use-custom --clear-model-options --max-output-tokens --extra-body)
CMAI_CONFIG_DIR="${HOME}/.config/git-commit-ai"
# On Linux and macOS, the hook lives here once. The template directory and the
# repositories link to it, so that an update of the hook reaches all of them.
# `git init` and `git clone` copy the link from the template directory.
HOOK_SOURCE="${CMAI_INSTALL_DIR}/prepare-commit-msg"
# How deep the installer looks for repositories below a directory of --repos.
REPO_SEARCH_DEPTH=5
# The command `git branch-ai` lives here. The directory of the cmai command
# gets a link to it (on Windows a copy), so that git finds it on the PATH.
BRANCH_COMMAND='git-branch-ai'
BRANCH_COMMAND_SOURCE="${CMAI_INSTALL_DIR}/${BRANCH_COMMAND}"
# The default short git alias for the command: `git bai`.
BRANCH_ALIAS='bai'
# The system keychain keeps the API key if a keychain exists and the installed
# cmai takes the key from the environment variable CMAI_API_KEY. The hook finds
# the name of the keychain entry in KEYCHAIN_FILE. Without a keychain, the key
# stays in the key file of cmai, which only the user can read.
KEYCHAIN_ENTRY="${CMAI_KEYCHAIN_ENTRY:-git-commit-ai}"
KEYCHAIN_ACCOUNT='api-key'
KEYCHAIN_LABEL='mittwald AI API key (git-commit-ai)'
KEYCHAIN_FILE="${CMAI_CONFIG_DIR}/keychain"
# Hosts that the cmai script names today. Another host is a finding.
CMAI_KNOWN_HOSTS=' openrouter.ai localhost 127.0.0.1 github.com my-api.com '
# Constructs that cmai has no need for, as "description|extended regex".
WORD_START='(^|[^[:alnum:]_.-])'
WORD_END='([^[:alnum:]_-]|$)'
CMAI_UNEXPECTED_PATTERNS=(
"runs generated code (eval)|${WORD_START}eval${WORD_END}"
"decodes hidden data|${WORD_START}(base64|xxd|uudecode|openssl)${WORD_END}"
"opens a raw network connection|/dev/(tcp|udp)/"
"starts a tool that cmai does not need|${WORD_START}(sudo|wget|nc|ncat|netcat|socat|ssh|scp|sftp|telnet|python[0-9.]*|perl|ruby|php|crontab|nohup|setsid|disown|chattr|mkfifo)${WORD_END}"
"pipes data into a shell|\\|[[:space:]]*(ba|z|da)?sh${WORD_END}"
"runs a command string in a shell|${WORD_START}(ba|z|da)?sh[[:space:]]+-c${WORD_END}"
"loads another script|${WORD_START}source[[:space:]]"
"names a sensitive file|\\.ssh|authorized_keys|\\.gnupg|\\.aws|\\.netrc|\\.git-credentials|_history|\\.bashrc|\\.bash_profile|\\.profile|\\.zshrc|/etc/(passwd|shadow)|/proc/"
"changes the git configuration|${WORD_START}git[[:space:]]+(config|remote)${WORD_END}|credential"
"deletes directories|${WORD_START}rm[[:space:]]+-[[:alpha:]]*[rR]"
"contains encoded text|\\\\x[0-9a-fA-F]{2}|\\\\[0-7]{3}"
"starts a background process|[^&]&[[:space:]]*\$"
)
AI_BASE_URL='https://llm.aihosting.mittwald.de/v1'
AI_MODEL='Qwen3.8-27B-NVFP4'
AI_MAX_OUTPUT_TOKENS=32768
AI_EXTRA_BODY='{"chat_template_kwargs":{"enable_thinking":false}}'
# Every hook written by this installer contains one of these two texts. The
# git branch-ai command contains the first one.
HOOK_SIGNATURE='Installed by install-git-commit-ai.sh'
HOOK_SIGNATURE_OLD='cmai --message-only'
# The hook and the git branch-ai command are generated from these parts:
# head: what is special for the script, and its status texts
# setup: runner_setup_content, the limits and the status line
# run: runner_run_content, which runs cmai and sets RESULT
# tail: what the script does with RESULT
# Each generated script is one file without any other file of the installer.
# The limits, the status line and the keychain access of a generated script.
# The script sets these variables before: WHAT, CMAI_ARGS, FAIL_STATUS and
# MESSAGES.
runner_setup_content() {
cat <<'RUNNER_EOF'
MAX_ATTEMPTS=3
TIMEOUT_SECONDS=30 # limit of the first attempt
TIMEOUT_INCREASE_PERCENT=50 # growth of the limit after each timeout: 30s, 45s, 68s
KILL_AFTER_SECONDS=2 # time for cmai to stop before it is killed
KEYCHAIN_SECONDS=10 # limit for reading the API key from the system keychain
# The installer writes the name of the keychain entry to this file when it
# stores the API key in the system keychain.
KEYCHAIN_FILE="${HOME}/.config/git-commit-ai/keychain"
KEYCHAIN_ACCOUNT='api-key'
FRAMES_PER_SECOND=20
MESSAGE_FRAMES=60 # frames until the next text, about 3 seconds
# On a terminal, the status is one line that is rewritten in place.
if [ -t 2 ] && [ "${TERM:-dumb}" != "dumb" ]; then
LIVE=1
else
LIVE=0
fi
if [ "${LIVE}" -eq 1 ] && [ -z "${NO_COLOR:-}" ]; then
COLOR=1
C_RED=$'\033[1;38;2;240;98;118m' # red that fits the colors of mittwald
C_REMARK=$'\033[3;38;2;231;160;134m' # mittwald salmon, italic
C_RESET=$'\033[0m'
else
COLOR=0
C_RED=''
C_REMARK=''
C_RESET=''
fi
# Colors of the status text (24-bit): mittwald blue, purple, salmon and rose.
# The colors flow through the letters. The part of the text that shows the
# elapsed share of the time limit is bold and in full color, the rest is muted.
GRADIENT_STOPS=(75 56 232 155 110 216 231 160 134 182 117 133)
GRADIENT_SIZE=60 # color steps of one cycle through all stops
MUTED_GRAY=125 # the muted colors are a mix with this gray
MUTED_PERCENT=62
BRIGHT=()
MUTED=()
# Fills BRIGHT and MUTED with one escape sequence per color step.
build_gradient() {
local stops=$(( ${#GRADIENT_STOPS[@]} / 3 ))
local step segment from to position ease channel value bright muted
for ((step = 0; step < GRADIENT_SIZE; step++)); do
segment=$(( step * stops / GRADIENT_SIZE ))
from=$(( segment * 3 ))
to=$(( (from + 3) % ${#GRADIENT_STOPS[@]} ))
position=$(( step * stops % GRADIENT_SIZE * 1000 / GRADIENT_SIZE ))
ease=$(( position * position * (3000 - 2 * position) / 1000000 ))
bright=''
muted=''
for channel in 0 1 2; do
value=$(( GRADIENT_STOPS[from + channel] + (GRADIENT_STOPS[to + channel] - GRADIENT_STOPS[from + channel]) * ease / 1000 ))
bright+=";${value}"
muted+=";$(( value + (MUTED_GRAY - value) * MUTED_PERCENT / 100 ))"
done
BRIGHT[step]=$'\033'"[0;1;38;2${bright}m"
MUTED[step]=$'\033'"[0;38;2${muted}m"
done
}
# Draws the status line. $1 = text, $2 = frame number, $3 = number of text
# characters in full color.
draw() {
local text="$1"
local length=${#1}
local line=''
local i step
if [ "${COLOR}" -eq 1 ]; then
for ((i = 0; i < length; i++)); do
step=$(( (i * GRADIENT_SIZE / length + GRADIENT_SIZE - $2 * 2 % GRADIENT_SIZE) % GRADIENT_SIZE ))
if [ "${i}" -lt "$3" ]; then
line+="${BRIGHT[step]}${text:i:1}"
else
line+="${MUTED[step]}${text:i:1}"
fi
done
line+="${C_RESET}"
else
line="${text}"
fi
printf '\r%s\033[K' "${line}" >&2
}
# Replaces the status line with the status text in full color and the remark
# that says that cmai is done. $1 = index in MESSAGES, $2 = frame number.
finish_done() {
local text="${MESSAGES[$1]%%|*}..."
local remark="${MESSAGES[$1]#*|}"
if [ "${LIVE}" -eq 1 ]; then
draw "${text}" "$2" "${#text}"
printf ' %s%s%s\n' "${C_REMARK}" "${remark}" "${C_RESET}" >&2
else
printf '%s %s\n' "${text}" "${remark}" >&2
fi
}
# Replaces the status line with a final line. $1 = color, $2 = text.
finish() {
if [ "${LIVE}" -eq 1 ]; then
printf '\r\033[K' >&2
fi
printf '%s%s%s\n' "$1" "$2" "${C_RESET}" >&2
}
# Prints the last lines of cmai output. Control characters are removed, so that
# text from the API cannot send escape sequences to the terminal.
cmai_output() {
local file
for file in "${ERR_FILE}" "${OUT_FILE}"; do
[ -s "${file}" ] || continue
LC_ALL=C tr -d '\000-\010\013-\037\177' < "${file}" |
grep -v '^[[:space:]]*$' | tail -n 3 | cut -c 1-300 | sed 's/^/ /'
return
done
}
# Reports why cmai generated nothing and exits. $1 = reason, $2 = "details" to
# add the cmai output.
fail() {
finish "${C_RED}" "No ${WHAT} generated: $1"
if [ "${2:-}" = details ]; then
cmai_output >&2
if [ -n "${keychain_error}" ]; then
printf ' %s\n' "${keychain_error}" >&2
fi
fi
exit "${FAIL_STATUS}"
}
# Prints the PowerShell script that prints a generic credential from the
# Windows Credential Manager. The name of the credential is in the environment
# variable CMAI_KEYCHAIN_TARGET.
windows_credential_script() {
cat <<'POWERSHELL_EOF'
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public static class CmaiCredential {
[StructLayout(LayoutKind.Sequential)]
struct Credential {
public uint Flags; public uint Type; public IntPtr TargetName; public IntPtr Comment;
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
public uint BlobSize; public IntPtr Blob; public uint Persist; public uint AttributeCount;
public IntPtr Attributes; public IntPtr TargetAlias; public IntPtr UserName;
}
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool CredReadW(string target, uint type, uint flags, out IntPtr credential);
[DllImport("advapi32.dll")]
static extern void CredFree(IntPtr credential);
public static string Read(string target) {
IntPtr pointer;
if (!CredReadW(target, 1, 0, out pointer)) { return null; }
try {
Credential credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
return Marshal.PtrToStringUni(credential.Blob, (int)credential.BlobSize / 2);
} finally { CredFree(pointer); }
}
}
'@
$secret = [CmaiCredential]::Read($env:CMAI_KEYCHAIN_TARGET)
if ($null -eq $secret) { exit 1 }
[Console]::Out.Write($secret)
POWERSHELL_EOF
}
# Prints the API key from the system keychain. $1 = name of the keychain entry.
keychain_get() {
local script
case "${OSTYPE:-}" in
darwin*)
security find-generic-password -s "$1" -a "${KEYCHAIN_ACCOUNT}" -w
;;
msys*|cygwin*)
# -EncodedCommand takes the script as base64 of UTF-16, which needs no quoting.
script="$(windows_credential_script | iconv -f UTF-8 -t UTF-16LE | base64 | tr -d '\r\n')"
CMAI_KEYCHAIN_TARGET="$1" MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' \
powershell.exe -NoProfile -NonInteractive -EncodedCommand "${script}"
;;
*)
secret-tool lookup service "$1" account "${KEYCHAIN_ACCOUNT}"
;;
esac
}
keychain_error=''
RUNNER_EOF
}
# Runs cmai with CMAI_ARGS, with the time limits and the status line. Sets
# RESULT to the output of cmai, or reports the reason and exits.
runner_run_content() {
cat <<'RUNNER_EOF'
# git starts hooks and commands with its own PATH, which can lack the
# directory of cmai.
CMAI="$(command -v cmai 2>/dev/null)" || CMAI="${HOME}/git-commit-ai/git-commit.sh"
[ -x "${CMAI}" ] || fail "cmai not found"
WORK_DIR="$(mktemp -d 2>/dev/null)" || fail "mktemp failed"
OUT_FILE="${WORK_DIR}/out"
ERR_FILE="${WORK_DIR}/err"
child=''
tick() {
sleep 0.05 2>/dev/null || sleep 1
}
# Sends a signal to cmai and to the processes that cmai started. $1 = signal.
signal_cmai() {
kill "-$1" -- "-${child}" 2>/dev/null || kill "-$1" "${child}" 2>/dev/null
}
# Runs from the EXIT trap.
# shellcheck disable=SC2329
cleanup() {
[ -n "${child}" ] && signal_cmai TERM
rm -f "${OUT_FILE}" "${ERR_FILE}"
rmdir "${WORK_DIR}" 2>/dev/null
}
trap cleanup EXIT
# cmai runs in its own process group, so Ctrl-C does not reach cmai. This
# script exits instead, and cleanup stops cmai.
trap '[ "${LIVE}" -eq 1 ] && printf "%s\n" "${C_RESET}" >&2; exit 130' INT
trap 'exit 143' TERM HUP
if [ "${COLOR}" -eq 1 ]; then
build_gradient
fi
# The key goes to cmai in the environment and never touches the disk. A cmai
# version that cannot take the key from the environment uses its own key file.
api_key=''
if [ -s "${KEYCHAIN_FILE}" ]; then
IFS= read -r keychain_entry < "${KEYCHAIN_FILE}"
IFS= read -r -t "${KEYCHAIN_SECONDS}" api_key < <(keychain_get "${keychain_entry}" 2>/dev/null)
api_key="${api_key%$'\r'}"
if [ -z "${api_key}" ]; then
keychain_error='The API key could not be read from the system keychain. Re-run the installer to store the key again.'
fi
fi
attempts=0
exitcode=0
while [ "${attempts}" -lt "${MAX_ATTEMPTS}" ]; do
attempts=$((attempts + 1))
message_start=$((RANDOM % ${#MESSAGES[@]}))
message_index="${message_start}"
started="${SECONDS}"
timed_out=0
frame=0
text=''
# With job control, cmai gets its own process group. This script can then
# stop cmai together with the curl process that cmai started.
set -m
CMAI_API_KEY="${api_key}" "${CMAI}" "${CMAI_ARGS[@]}" > "${OUT_FILE}" 2> "${ERR_FILE}" < /dev/null &
child=$!
set +m
if [ "${LIVE}" -eq 0 ]; then
printf '%s...\n' "${MESSAGES[message_start]%%|*}" >&2
fi
while kill -0 "${child}" 2>/dev/null; do
elapsed=$((SECONDS - started))
if [ "${elapsed}" -ge "${TIMEOUT_SECONDS}" ]; then
timed_out=1
signal_cmai TERM
grace=$((KILL_AFTER_SECONDS * FRAMES_PER_SECOND))
while [ "${grace}" -gt 0 ] && kill -0 "${child}" 2>/dev/null; do
tick
grace=$((grace - 1))
done
signal_cmai KILL
break
fi
if [ "${LIVE}" -eq 1 ]; then
if [ $((frame % MESSAGE_FRAMES)) -eq 0 ]; then
# Every MESSAGE_FRAMES frames the next text; the integer division is intended.
# shellcheck disable=SC2017
message_index=$(( (message_start + frame / MESSAGE_FRAMES * 7) % ${#MESSAGES[@]} ))
text="${MESSAGES[message_index]%%|*}..."
fi
draw "${text}" "${frame}" "$((elapsed * ${#text} / TIMEOUT_SECONDS))"
fi
frame=$((frame + 1))
tick
done
wait "${child}" 2>/dev/null; exitcode=$?
child=''
if [ "${timed_out}" -eq 0 ]; then
break
fi
if [ "${attempts}" -ge "${MAX_ATTEMPTS}" ]; then
fail "cmai timed out after ${TIMEOUT_SECONDS}s (attempt ${attempts}/${MAX_ATTEMPTS})" details
fi
[ "${LIVE}" -eq 1 ] || printf 'Timed out after %ss\n' "${TIMEOUT_SECONDS}" >&2
TIMEOUT_SECONDS=$((TIMEOUT_SECONDS + (TIMEOUT_SECONDS * TIMEOUT_INCREASE_PERCENT + 99) / 100))
done
[ "${exitcode}" -eq 0 ] || fail "cmai failed (exit ${exitcode})" details
# jq for Windows ends lines with a carriage return.
RESULT="$(tr -d '\r' < "${OUT_FILE}")"
[ -n "${RESULT}" ] || fail "cmai returned an empty ${WHAT}" details
RUNNER_EOF
}
# The prepare-commit-msg hook. On Linux and macOS the installer writes it to
# HOOK_SOURCE; on Windows it writes a copy into each hooks directory.
hook_content() {
cat <<'HOOK_EOF'
#!/usr/bin/env bash
#
# prepare-commit-msg hook: puts a commit message generated by cmai at the top
# of the message that git opens in the editor.
# Installed by install-git-commit-ai.sh (https://github.com/mittwald/ai-developer-tools).
#
# The hook never blocks a commit. If the generation fails, the hook reports the
# reason and git opens the editor without a generated message.
#
# Runs with bash 3.2 or later on Linux, macOS and Windows (Git for Windows).
MSG_FILE="${1:-}"
SOURCE="${2:-}" # empty for a plain `git commit`; else message, template, merge, squash or commit
case "${SOURCE}" in
message|merge|squash|template|commit) exit 0 ;;
esac
[ -n "${MSG_FILE}" ] || exit 0
WHAT='commit message' # what cmai generates, for the reports
CMAI_ARGS=(--message-only)
FAIL_STATUS=0 # the hook never blocks a commit
# Status texts with a remark, as "text|remark". While cmai runs, the line
# shows "<text>...". When cmai is done, it becomes "<text>... <remark>".
# ASCII only, no line longer than 72 (text and remark together).
MESSAGES=(
'Asking the diff what it did this time|It confessed.'
'Translating your changes into human|Fluent now.'
'Teaching the model to say "fix" politely|Manners acquired.'
'Squinting at your staged changes|Eyes adjusted.'
'Pretending this was the plan all along|Nobody suspects a thing.'
'Turning chaos into Conventional Commits|Order restored!'
'Finding a nicer word for "oops"|Found one.'
'Counting the files you swear you never touched|Your secret is safe.'
'Blaming the previous commit|Case closed.'
'Resisting the urge to write "misc changes"|Resisted!'
'Consulting the commit message oracle|The oracle has spoken.'
'Reading your diff so the reviewers can skim it|Skimmable now.'
'Making "wip" sound professional|Very professional.'
'Flipping a coin between feat and fix|It landed.'
'Brewing a fresh subject line|Served hot!'
'Squeezing three hours into seventy characters|Squeezed.'
'Looking for the why behind the what|Found the why.'
'Polishing the imperative mood|Shiny!'
'Negotiating with the linter in advance|Deal signed.'
'Hiding the evidence of trial and error|No evidence left.'
'Asking the GPUs for their honest opinion|They approve.'
'Convincing the model that the tabs were intended|Convinced.'
'Composing a haiku, then deleting it|It was beautiful.'
'Removing "finally works" from the draft|And it finally works.'
'Inventing a scope that sounds official|Very official.'
'Giving your typo fix the gravitas it deserves|Gravitas applied.'
'Checking whether this counts as a refactor|The verdict is in.'
'Skipping the part where it says "stuff"|Stuff skipped.'
'Writing history, one line at a time|History written.'
'Explaining it to your future self|Future you says thanks!'
'Dressing up the diff for code review|Looking sharp!'
'Rounding "quick fix" up to "improvement"|Rounded up.'
'Decoding what "temp2_final" was supposed to mean|Decoded, mostly.'
'Warming up the tokens|Nice and toasty.'
'Deciding this is definitely not a breaking change|Probably.'
'Searching for a verb that is not "update"|Verb found!'
'Reticulating commit splines|Splines reticulated.'
'Fitting an epic into the subject line|It fits!'
'Taking credit for what the compiler made you do|Credit taken.'
'Preparing your alibi for git blame|Alibi airtight.'
'Asking mittwald AI very nicely|It said yes!'
'Thinking in German, answering in English|Fertig. Done.'
'Making the changelog proud|The changelog is beaming.'
'Distilling your diff into one honest sentence|Mostly honest.'
'Arguing with itself about the scope|It won.'
'Promising the reviewers it is a small change|Pinky promise.'
'Steering clear of "various improvements"|Steered clear.'
'Reading between the hunks|Read it all.'
'Editing the swear words out of the summary|Squeaky clean.'
'Trusting that the tests passed|Fingers crossed!'
'Sorting your hunks by level of embarrassment|Sorted.'
'Asking the reviewers to look away|They looked away.'
'Converting caffeine into a commit message|Conversion complete.'
'Checking whether "refactor" is technically true|Technically true.'
'Replacing "did stuff" with actual words|Words found.'
'Measuring the blast radius of this diff|Contained.'
'Pretending the merge conflict never happened|What conflict?'
'Folding forty lines of changes into one|Neatly folded.'
'Interviewing the lines you deleted|They will be missed.'
'Giving your variable renames a backstory|Very moving.'
'Choosing between "add" and "introduce"|Tough call.'
'Looking for the bug you fixed by accident|Found that one too.'
'Writing the message your reviewers dream of|Dream delivered.'
'Weighing the commit against the ticket|Close enough.'
'Smoothing over the third attempt at this|First try, officially.'
'Calculating how "minor" this change is|Minor-ish.'
'Politely ignoring the whitespace changes|Ignored.'
'Turning your diff into a short story|The end.'
'Rehearsing the commit for the stand-up|Ready to present.'
'Asking the hunks to form a single line|They lined up.'
'Reading the diff twice, just to be sure|Sure now.'
'Choosing the right amount of enthusiasm|Measured.'
'Untangling what changed from what moved|Untangled.'
'Leaving out the part about Friday afternoon|Our secret.'
'Keeping the subject under 72 characters|With room to spare.'
'Checking the diff for hidden feelings|None found.'
'Compressing your intentions into plain English|Compressed.'
'Paraphrasing the stack trace you fixed|Paraphrased.'
'Giving the bug a proper send-off|Rest in peace, bug.'
'Making sure "chore" is not an understatement|It is fine.'
'Spinning up a few billion parameters|All spinning.'
'Summarizing the meeting that led to this|Short meeting.'
'Agreeing on a tense with the model|Imperative it is.'
'Asking the cloud for a quick favor|Favor granted.'
'Picking words your future self will understand|Future-proof.'
'Separating the signal from the semicolons|Signal found.'
'Writing a message that git log will remember|Memorable.'
'Trimming the adjectives from your diff|Trimmed.'
'Avoiding the word "obviously"|Obviously.'
'Asking the model to be brief, for once|Brief enough.'
'Describing your fix without blaming anyone|Diplomatic.'
'Quietly forgetting the debug prints|Gone. Hopefully.'
'Making the reviewers believe it was easy|Looks easy.'
'Tuning the subject line to the right pitch|In tune.'
'Checking the diff against common sense|It passed.'
'Bribing the tokenizer with spare bytes|Bribe accepted.'
'Finding the story hidden in your staged files|Once upon a commit.'
'Considering the word "tweak" very carefully|Rejected.'
'Asking the model to skip the small talk|Straight to it.'
'Packing your changes for the trip to main|Packed and ready.'
)
HOOK_EOF
runner_setup_content
echo
runner_run_content
cat <<'HOOK_EOF'
if { printf '%s\n' "${RESULT}"; cat "${MSG_FILE}"; } > "${MSG_FILE}.tmp" &&
mv "${MSG_FILE}.tmp" "${MSG_FILE}"; then
finish_done "${message_index}" "${frame}"
else
rm -f "${MSG_FILE}.tmp"
fail "could not write ${MSG_FILE}"
fi
exit 0
HOOK_EOF
}
# The command `git branch-ai`. The installer writes it to BRANCH_COMMAND_SOURCE.
branch_command_content() {
cat <<'BRANCH_EOF'
#!/usr/bin/env bash
#
# git branch-ai: creates a branch with a name that cmai generates from the
# staged changes, and switches to the branch.
# Installed by install-git-commit-ai.sh (https://github.com/mittwald/ai-developer-tools).
#
# Runs with bash 3.2 or later on Linux, macOS and Windows (Git for Windows).
usage() {
cat <<'USAGE_EOF'
Usage: git branch-ai [-u | -d <diff>] [-p] [-y]
Creates a branch for your staged changes and switches to it. mittwald AI
generates the name of the branch from the changes. Your changes stay as
they are.
-u, --unstaged Use the unstaged and untracked changes, not the staged ones
-d, --diff <diff> Use the changes of `git diff <diff>`, for example
main...HEAD
-p, --print Print the name and do not create the branch
-y, --yes Do not ask for the name before the branch is created
-h Show this help
USAGE_EOF
}
unstaged=0
diff_spec=''
PRINT_ONLY=0
ASSUME_YES=0
while [ "$#" -gt 0 ]; do
case "$1" in
-u|--unstaged) unstaged=1 ;;
-d|--diff)
if [ "$#" -lt 2 ] || [ -z "$2" ]; then
echo 'git branch-ai: --diff needs a diff, for example main...HEAD' >&2
exit 1
fi
diff_spec="$2"
shift
;;
-p|--print) PRINT_ONLY=1 ;;
-y|--yes) ASSUME_YES=1 ;;
-h|--help) usage; exit 0 ;;
*)
echo "git branch-ai: unknown option: $1" >&2
usage >&2
exit 1
;;
esac
shift
done
if [ "${unstaged}" -eq 1 ] && [ -n "${diff_spec}" ]; then
echo 'git branch-ai: use --unstaged or --diff, not both' >&2
exit 1
fi
WHAT='branch name' # what cmai generates, for the reports
CMAI_ARGS=(--branch-name-only)
if [ "${unstaged}" -eq 1 ]; then
CMAI_ARGS+=(--unstaged)
elif [ -n "${diff_spec}" ]; then
CMAI_ARGS+=(--diff "${diff_spec}")
fi
FAIL_STATUS=1
# Status texts with a remark, as "text|remark". While cmai runs, the line
# shows "<text>...". When cmai is done, it becomes "<text>... <remark>".
# ASCII only, no line longer than 72 (text and remark together).
MESSAGES=(
'Naming things, the hard part|Named.'
'Asking the diff what it wants to be called|It chose.'
'Looking for a name shorter than the diff|Short enough.'
'Flipping a coin between feat/ and fix/|It landed.'
'Replacing every space with a hyphen|Hyphenated.'
'Steering clear of the name "test2"|Steered clear.'
'Picking a name you can still type on Friday|Typeable.'
'Growing a new branch|It sprouted.'
'Ruling out "final-final-v2"|Ruled out.'
'Reading your staged changes for a title|Titled.'
'Turning a diff into a few lowercase words|Lowercased.'
'Keeping the name under fifty characters|With room to spare.'
'Skipping "my-branch" as a suggestion|Skipped.'
'Asking mittwald AI for a good name|It had one.'
'Finding a name the reviewers can pronounce|Pronounceable.'
'Giving your changes a place to live|Moved in.'
'Counting the hyphens|All accounted for.'
'Looking up a better word for "stuff"|Found a real word.'
'Choosing a prefix with confidence|Confident.'
'Summarizing your work in three words|Three words it is.'
'Leaving "wip" out of the name|Left out.'
'Sharpening the pruning shears|Sharp.'
'Branching out|Branched.'
'Finding a name that will age well|Timeless.'
'Making the branch list one line longer|One more.'
'Resisting the name "new-new-feature"|Resisted!'
'Squeezing the idea into a slug|Squeezed.'
'Asking the hunks what they have in common|They agreed.'
'Preparing a name for the merge request|Ready to merge. Almost.'
'Checking that a good name is still free|One was left.'
'Planting a branch next to main|Planted.'
'Thinking of a name main will not be jealous of|Diplomatic.'
'Avoiding a name with your initials and a date|Avoided.'
'Translating the diff into kebab-case|Kebab served.'
'Deciding what this branch is really about|Decided.'
'Trimming the name until it fits a tab title|It fits!'
'Picking a name that tab completion will like|Completes nicely.'
'Giving the ticket number a rest|Rested.'
'Finding the one word your changes share|Found it.'
'Labeling the box before you fill it|Labeled.'
'Considering "refactor" one more time|Considered.'
'Writing the name on a small sign|Sign is up.'
'Looking for a fork in the road|Took it.'
'Leaving main in peace|Main says thanks.'
'Choosing between short and descriptive|Both, somehow.'
'Reading the diff like a table of contents|Chapter found.'
'Dropping the word "branch" from the branch name|Dropped.'
'Naming the branch before the standup asks|Just in time.'
'Measuring twice, branching once|Measured.'
'Sending your changes off on their own path|Off they go.'
)
BRANCH_EOF
echo
runner_setup_content
cat <<'BRANCH_EOF'
git rev-parse --git-dir >/dev/null 2>&1 || fail 'this is not a git repository'
if [ "${unstaged}" -eq 0 ] && [ -z "${diff_spec}" ] && git diff --cached --quiet; then
fail 'there are no staged changes. Stage your changes with "git add", or use --unstaged'
fi
BRANCH_EOF
runner_run_content
declare -f terminal_color_depth color prompt_colors
cat <<'BRANCH_EOF'
# The first line with text. A model can put quotes around the name.
NAME="$(printf '%s\n' "${RESULT}" | LC_ALL=C tr -d "\`\"'" |
sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^$/d' | head -n 1)"
if ! git check-ref-format --branch "${NAME}" >/dev/null 2>&1; then
fail "cmai returned no valid branch name" details
fi
finish_done "${message_index}" "${frame}"
if [ "${PRINT_ONLY}" -eq 1 ]; then
printf '%s\n' "${NAME}"
exit 0
fi
# On a terminal, the name can be changed before the branch is created.
ask_name=0
if [ "${ASSUME_YES}" -eq 0 ] && [ -t 0 ] && [ -t 2 ]; then
ask_name=1
prompt='Branch name: '
if [ "${COLOR}" -eq 1 ]; then
marker='>'
prompt_marker=''
case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
*UTF-8*|*utf-8*|*UTF8*|*utf8*)
marker='›'
prompt_marker='◆ '
;;
esac
terminal_color_depth
prompt_colors
prompt_bold=$'\033[1m'
prompt_arrow="${C_BLUE}${prompt_bold}"
# Readline needs the invisible color sequences marked to track the cursor.
prompt=$'\001'"${C_CODE}"$'\002'"${prompt_marker}"$'\001'"${C_RESET}${prompt_bold}"$'\002Branch name\001'"${C_RESET}"$'\002 \001'"${prompt_arrow}"$'\002'"${marker}"$'\001'"${C_RESET}"$'\002 '
fi
fi
while true; do
if [ "${ask_name}" -eq 1 ]; then
if [ "${BASH_VERSINFO[0]}" -ge 4 ]; then
IFS= read -r -e -i "${NAME}" -p "${prompt}" input || { printf '\nNo branch created.\n' >&2; exit 1; }
else
# bash 3.2 (macOS) cannot put the name into the input line.
if [ "${COLOR}" -eq 1 ]; then
printf '%s%s%s%sBranch name%s [%s] %s%s%s ' \
"${C_CODE}" "${prompt_marker}" "${C_RESET}" "${prompt_bold}" "${C_RESET}" \
"${NAME}" "${prompt_arrow}" "${marker}" "${C_RESET}" >&2
else
printf 'Branch name [%s]: ' "${NAME}" >&2
fi
IFS= read -r input || { printf '\nNo branch created.\n' >&2; exit 1; }
fi
# Without the spaces around the input. An empty input keeps the name.
input="${input#"${input%%[![:space:]]*}"}"
input="${input%"${input##*[![:space:]]}"}"
[ -z "${input}" ] || NAME="${input}"
fi
if ! git check-ref-format --branch "${NAME}" >/dev/null 2>&1; then
problem="\"${NAME}\" is not a valid branch name"
elif git show-ref --verify --quiet "refs/heads/${NAME}"; then
problem="the branch \"${NAME}\" already exists"
else
break
fi
if [ "${ask_name}" -eq 0 ]; then
finish "${C_RED}" "No branch created: ${problem}"
exit 1
fi
printf '%sNo branch created: %s%s\n' "${C_RED}" "${problem}" "${C_RESET}" >&2
done
git checkout -b "${NAME}"
BRANCH_EOF
}
VIM_SNIPPET='" abort git commit when quitting with :q or :q!
augroup GitCommitAbort
autocmd!
autocmd FileType gitcommit cnoreabbrev <buffer> q! cq
autocmd FileType gitcommit cnoreabbrev <buffer> q cq
augroup END'
# Vim loads defaults.vim (syntax, filetype detection) only while no vimrc
# exists. A new vimrc keeps the defaults with these lines.
# shellcheck disable=SC2016
VIM_DEFAULTS_SNIPPET='" keep the Vim defaults, which Vim skips as soon as a vimrc exists
if filereadable(expand("$VIMRUNTIME/defaults.vim"))
unlet! skip_defaults_vim
source $VIMRUNTIME/defaults.vim
endif'
PLATFORM='' # linux, macos or windows
non_interactive=0
feature_commit=1 # 1 to set up AI commit messages
feature_branch=1 # 1 to set up AI branch names
features_given=0 # 1 if --features names the features
step_number=0 # the number of the last heading
step_total=0 # the number of steps for the chosen features
tmp_dir=''
cmai_path='' # the cmai script in use
downloaded_script=''
cmai_is_latest=0 # 1 if the installed cmai is the same as the latest one
cmai_api_key='' # the key that the user gave in step 2
keychain_api_key='' # the key, if the system keychain keeps it
template_dir=''
hook_path=''
repo_dirs=() # the directories of --repos
terminal_color_depth() {
case "${COLORTERM:-}:${TERM_PROGRAM:-}:${WT_SESSION:+wt}" in
*truecolor*|*24bit*|*iTerm.app*|*WezTerm*|*ghostty*|*vscode*|*mintty*|*wt) COLOR_DEPTH=24 ;;
*)
case "${TERM:-}" in
*256color*|xterm-kitty|alacritty|foot*) COLOR_DEPTH=8 ;;
*) COLOR_DEPTH=4 ;;
esac
;;
esac
}
prompt_colors() {
C_BLUE="$(color 124 112 255 105 34)" # mittwald blue, lighter for dark terminals
C_CODE="$(color 231 160 134 216 95)" # mittwald salmon
}
# The colors of mittwald: blue, purple, salmon and rose. A terminal with 24-bit
# color gets them exactly, a terminal with 256 colors gets the nearest ones.
# Output to a file or a pipe stays plain text without symbols.
setup_colors() {
FANCY=0
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
terminal_color_depth
prompt_colors
case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
*UTF-8*|*utf-8*|*UTF8*|*utf8*) FANCY=1 ;;
esac
C_RESET=$'\033[0m'
C_BOLD=$'\033[1m'
C_ITALIC=$'\033[3m'
C_CYAN="$(color 155 110 216 140 35)" # mittwald purple
C_ROSE="$(color 182 117 133 132 35)" # mittwald rose
C_DIM="$(color 140 138 160 245 90)"
C_GREEN="$(color 94 204 150 78 32)"
C_YELLOW="$(color 240 190 100 221 33)"
C_RED="$(color 240 98 118 204 31)"
C_COLOR_NAME="$(color 196 178 240 183 35)" # light purple
C_COLOR_VALUE="$(color 240 214 200 223 37)" # light salmon
C_BADGE="$(color 255 255 255 231 97)$(background 75 56 232 56 44)${C_BOLD}"
else
COLOR_DEPTH=0
C_RESET=''
C_BOLD=''
C_ITALIC=''
C_DIM=''
C_RED=''
C_GREEN=''
C_YELLOW=''
C_BLUE=''
C_CYAN=''
C_CODE=''
C_ROSE=''
C_COLOR_NAME=''
C_COLOR_VALUE=''
C_BADGE=''
fi
# The progress of slow work goes straight to the terminal, so that it also
# shows while the output of a command is captured or piped.
PROGRESS_TTY=''
if [ "${FANCY}" -eq 1 ] && [ -t 2 ] && { : > /dev/tty; } 2>/dev/null; then
PROGRESS_TTY=/dev/tty
fi
if [ "${FANCY}" -eq 1 ]; then
BAR='▎'
M_OK='✔ '
M_NOTE='▲ '
M_ERROR='✖ '
M_ASK='◆ '
else
BAR='>'
M_OK=''
M_NOTE=''
M_ERROR=''
M_ASK=''
fi
}
# Prints the escape sequence of a text color. $1 $2 $3 = 24-bit color,
# $4 = nearest of 256 colors, $5 = basic color.
color() {
case "${COLOR_DEPTH}" in
24) printf '\033[38;2;%s;%s;%sm' "$1" "$2" "$3" ;;
8) printf '\033[38;5;%sm' "$4" ;;
*) printf '\033[%sm' "$5" ;;
esac
}
# Like color, for the background.
background() {
case "${COLOR_DEPTH}" in
24) printf '\033[48;2;%s;%s;%sm' "$1" "$2" "$3" ;;
8) printf '\033[48;5;%sm' "$4" ;;
*) printf '\033[%sm' "$5" ;;
esac
}
# Keeps the style $2 for all of $1, also after a part of $1 that ends with
# C_RESET, such as the output of code.
styled() {
if [ -n "${C_RESET}" ]; then
printf '%s%s%s' "$2" "${1//"${C_RESET}"/${C_RESET}$2}" "${C_RESET}"
else
printf '%s' "$1"
fi
}
# Prints $1 in bold with the colors of mittwald flowing through the letters.
gradient_text() {
local text="$1"
local stops=(75 56 232 155 110 216 231 160 134 182 117 133)
local length=${#1}
local i segment from position ease channel value rgb line=''
if [ "${COLOR_DEPTH}" -ne 24 ]; then
styled "${text}" "${C_BOLD}${C_BLUE}"
return
fi
for ((i = 0; i < length; i++)); do
# Position in the gradient from the first to the last stop, 0 to 3000.
position=$(( i * 3000 / (length > 1 ? length - 1 : 1) ))
segment=$(( position / 1000 ))
[ "${segment}" -lt 3 ] || segment=2
from=$(( segment * 3 ))
ease=$(( position - segment * 1000 ))
rgb=''
for channel in 0 1 2; do
value=$(( stops[from + channel] + (stops[from + 3 + channel] - stops[from + channel]) * ease / 1000 ))
# Lighter, so that the dark blue stays readable on a dark terminal.
value=$(( value + (255 - value) * 25 / 100 ))
rgb+=";${value}"
done
line+=$'\033'"[1;38;2${rgb}m${text:i:1}"
done
printf '%s%s' "${line}" "${C_RESET}"
}
# Prints the title of the installer.
banner() {
if [ "${FANCY}" -eq 1 ]; then
echo
echo " ${C_BLUE}${BAR}${C_RESET} $(gradient_text 'mittwald AI — git commit messages and branch names')"
echo " ${C_CYAN}${BAR}${C_RESET} ${C_DIM}Installer is running on $(platform_title).${C_RESET}"
echo " ${C_ROSE}${BAR}${C_RESET} ${C_DIM}All changes will be shown before they are applied.${C_RESET}"
else
echo "${C_GREEN}Installer is running on $(platform_title).${C_RESET}"
echo "${C_DIM}All changes will be shown before they are applied.${C_RESET}"
fi
}
# Prints the end of the installation.
outro() {
if [ "${FANCY}" -eq 1 ]; then
echo " ${C_GREEN}${M_OK}${C_RESET}$(gradient_text 'All set. Happy committing!')"
echo
fi
}
# Progress of slow work, in the style of the status line of the hook: the
# colors of mittwald flow through the text, and the bold part grows with the
# elapsed share of PROGRESS_SECONDS.
PROGRESS_SECONDS=20 # the time limit of `limited`
PROGRESS_DELAY_FRAMES=6 # work that ends within 0.3 seconds shows nothing
PROGRESS_STOPS=(75 56 232 155 110 216 231 160 134 182 117 133)
PROGRESS_STEPS=60 # color steps of one cycle through all stops
PROGRESS_BRIGHT=()
PROGRESS_MUTED=()
PROGRESS_PID=''
# Fills PROGRESS_BRIGHT and PROGRESS_MUTED with one escape sequence per color
# step. The muted colors are a mix with gray.
build_progress_gradient() {
local stop_count=$(( ${#PROGRESS_STOPS[@]} / 3 ))
local step segment from to position ease channel value bright muted
for ((step = 0; step < PROGRESS_STEPS; step++)); do
segment=$(( step * stop_count / PROGRESS_STEPS ))
from=$(( segment * 3 ))
to=$(( (from + 3) % ${#PROGRESS_STOPS[@]} ))
position=$(( step * stop_count % PROGRESS_STEPS * 1000 / PROGRESS_STEPS ))
ease=$(( position * position * (3000 - 2 * position) / 1000000 ))
bright=''
muted=''
for channel in 0 1 2; do
value=$(( PROGRESS_STOPS[from + channel] + (PROGRESS_STOPS[to + channel] - PROGRESS_STOPS[from + channel]) * ease / 1000 ))
bright+=";$(( value + (255 - value) * 25 / 100 ))"
muted+=";$(( value + (125 - value) * 62 / 100 ))"
done
PROGRESS_BRIGHT[step]=$'\033'"[0;1;38;2${bright}m"
PROGRESS_MUTED[step]=$'\033'"[0;38;2${muted}m"
done
}
# Prints $1 with the colors flowing. $2 = frame number, $3 = number of
# characters in bold and full color.
progress_text() {
local text="$1"
local length=${#1}
local line='' i step
if [ "${COLOR_DEPTH}" -ne 24 ]; then
printf '%s%s%s%s%s' "${C_BOLD}${C_BLUE}" "${text:0:$3}" "${C_RESET}${C_DIM}" "${text:$3}" "${C_RESET}"
return
fi
[ "${#PROGRESS_BRIGHT[@]}" -gt 0 ] || build_progress_gradient
for ((i = 0; i < length; i++)); do
step=$(( (i * PROGRESS_STEPS / length + PROGRESS_STEPS - $2 * 2 % PROGRESS_STEPS) % PROGRESS_STEPS ))
if [ "${i}" -lt "$3" ]; then
line+="${PROGRESS_BRIGHT[step]}${text:i:1}"
else
line+="${PROGRESS_MUTED[step]}${text:i:1}"