Repository navigation
Expand file tree
/
Copy pathinstall-git-commit-ai.sh
More file actions
executable file
·1792 lines (1646 loc) · 61.9 KB
/
Copy pathinstall-git-commit-ai.sh
File metadata and controls
executable file
·1792 lines (1646 loc) · 61.9 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 with mittwald AI: installs cmai,
# configures it and installs a prepare-commit-msg hook into the git template
# directory.
#
# 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 and the hook need. Older cmai versions lack them.
CMAI_REQUIRED_OPTIONS=(--message-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 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.
HOOK_SIGNATURE='Installed by install-git-commit-ai.sh'
HOOK_SIGNATURE_OLD='cmai --message-only'
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
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 the hook kills it
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'
case "${SOURCE}" in
message|merge|squash|template|commit) exit 0 ;;
esac
[ -n "${MSG_FILE}" ] || exit 0
# Status texts with a remark, as "text|remark". While cmai runs, the line
# shows "1/3 <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!'
)
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_DIM=$'\033[2m'
C_FAINT=$'\033[0;2;38;2;80;80;80m' # the slash of the attempt counter
C_RED=$'\033[31m'
C_RESET=$'\033[0m'
else
COLOR=0
C_DIM=''
C_FAINT=''
C_RED=''
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.
# The attempt counter in front of the text stays dim, in the color of the theme.
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 = attempt counter such as 1/3 (empty for none),
# $2 = text, $3 = frame number, $4 = number of text characters in full color.
draw() {
local text="$2"
local length=${#2}
local line=''
local i step
if [ "${COLOR}" -eq 1 ]; then
if [ -n "$1" ]; then
line="${C_DIM}${1%%/*}${C_FAINT}/${C_DIM}${1#*/} "
fi
for ((i = 0; i < length; i++)); do
step=$(( (i * GRADIENT_SIZE / length + GRADIENT_SIZE - $3 * 2 % GRADIENT_SIZE) % GRADIENT_SIZE ))
if [ "${i}" -lt "$4" ]; then
line+="${BRIGHT[step]}${text:i:1}"
else
line+="${MUTED[step]}${text:i:1}"
fi
done
line+="${C_RESET}"
else
line="${1:+$1 }${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\n' "${remark}" >&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 there is no generated message. $1 = reason, $2 = "details" to add
# the cmai output.
fail() {
finish "${C_RED}" "No commit message generated: $1"
if [ "${2:-}" = details ]; then
cmai_output >&2
if [ -n "${keychain_error}" ]; then
printf ' %s\n' "${keychain_error}" >&2
fi
fi
exit 0
}
# 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=''
# git starts hooks 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. The hook
# 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. The hook can then stop
# cmai together with the curl process that cmai started.
set -m
CMAI_API_KEY="${api_key}" "${CMAI}" --message-only > "${OUT_FILE}" 2> "${ERR_FILE}" < /dev/null &
child=$!
set +m
if [ "${LIVE}" -eq 0 ]; then
printf '%s/%s %s...\n' "${attempts}" "${MAX_ATTEMPTS}" "${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 "${attempts}/${MAX_ATTEMPTS}" "${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.
COMMIT_MSG="$(tr -d '\r' < "${OUT_FILE}")"
[ -n "${COMMIT_MSG}" ] || fail "cmai returned an empty message" details
if { printf '%s\n' "${COMMIT_MSG}"; 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
}
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
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
setup_colors() {
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
C_RESET=$'\033[0m'
C_BOLD=$'\033[1m'
C_ITALIC=$'\033[3m'
C_DIM=$'\033[2m'
C_RED=$'\033[31m'
C_GREEN=$'\033[32m'
C_YELLOW=$'\033[33m'
C_BLUE=$'\033[34m'
C_CYAN=$'\033[36m'
C_CODE=$'\033[95m'
else
C_RESET=''
C_BOLD=''
C_ITALIC=''
C_DIM=''
C_RED=''
C_GREEN=''
C_YELLOW=''
C_BLUE=''
C_CYAN=''
C_CODE=''
fi
}
usage() {
echo "Usage: install-git-commit-ai.sh [--non-interactive] [--repos DIR]..."
echo
echo " --non-interactive Do not prompt; accept the default answer of every step."
echo " The default keeps an existing hook from another source"
echo " and does not install a cmai script with unexpected content."
echo " --repos DIR Look for repositories in DIR (can repeat). A repository"
echo " with a copy of the hook from this installer gets a link to"
echo " the hook instead (on Windows: the current hook). The"
echo " repository in the current directory is always checked."
echo " -h, --help Show this help"
echo
echo "Environment:"
echo " MITTWALD_AI_API_KEY API key to store, instead of typing it"
echo " CMAI_BIN_DIR Directory on the PATH for the cmai command"
echo " (default: /usr/local/bin, on Windows ~/bin)"
echo
echo "Pass options through a pipe with: curl ... | bash -s -- --non-interactive"
}
parse_args() {
while [ "$#" -gt 0 ]; do
case "$1" in
--non-interactive) non_interactive=1 ;;
--repos)
if [ "$#" -lt 2 ] || [ -z "$2" ]; then
echo "${C_RED}ERROR:${C_RESET} --repos needs a directory" >&2
usage >&2
exit 1
fi
repo_dirs+=("$2")
shift
;;
-h|--help) usage; exit 0 ;;
*)
echo "${C_RED}ERROR:${C_RESET} unknown option: $1" >&2
usage >&2
exit 1
;;
esac
shift
done
}
cleanup() {
if [ -n "${tmp_dir}" ]; then
rm -rf "${tmp_dir}"
fi
}
is_interactive() {
[ "${non_interactive}" -eq 0 ] && { [ -t 0 ] || [ -t 1 ]; }
}
code() {
printf '%s%s%s' "${C_CODE}" "$1" "${C_RESET}"
}
dim_output() {
sed "s/^/ ${C_DIM}/; s/\$/${C_RESET}/"
}
heading() {
printf '\n%sStep %s:%s %s\n' "${C_BOLD}${C_CYAN}" "$1" "${C_RESET}" "$2"
}
# Shows a command or an action before it runs.
action() {
echo " ${C_ITALIC}${C_BLUE}>${C_RESET}${C_ITALIC} $1${C_RESET}"
}
warning() {
echo " ${C_YELLOW}${C_BOLD}WARNING:${C_RESET}${C_YELLOW} $1${C_RESET}"
}
error() {
echo " ${C_RED}ERROR:${C_RESET} $1" >&2
}
die() {
error "$1"
exit 1
}
abort() {
echo " ${C_RED}Aborting.${C_RESET}"
exit 1
}
# Asks a yes/no question. $1 = question, $2 = default answer (y or n).
ask() {
local question="$1"
local default="$2"
local hint='[y/N]'
local answer=''
if [ "${default}" = y ]; then
hint='[Y/n]'
fi
printf ' %s%s %s:%s ' "${C_BOLD}${C_BLUE}" "${question}" "${hint}" "${C_RESET}"
if is_interactive; then
read -r answer < /dev/tty || true
elif [ "${default}" = y ]; then
echo 'Y'
else
echo 'N'
fi
if [ -z "${answer}" ]; then
answer="${default}"
fi
case "${answer}" in
y|Y|yes|Yes|YES) return 0 ;;
*) return 1 ;;
esac
}
prompt_step() {
heading "$1" "$2"
echo
ask "Run this step?" y
}
# Reads the API key without echo, so that the key does not stay on the screen
# or in the terminal scrollback.
prompt_api_key() {
printf ' %s%s:%s ' "${C_BOLD}${C_BLUE}" "$1" "${C_RESET}"
cmai_api_key=''
if is_interactive; then
read -r -s cmai_api_key < /dev/tty || true
fi
echo
}
# The tilde in the next two functions is literal text, as git config stores it.
# shellcheck disable=SC2088
to_tilde_path() {
local p="$1"
if [ "$p" = "$HOME" ]; then
printf '~'
elif [ "${p#"$HOME"/}" != "$p" ]; then
printf '~/%s' "${p#"$HOME"/}"
else
printf '%s' "$p"
fi
}
# shellcheck disable=SC2088
resolve_template_dir() {
local p="$1"
case "$p" in
"~") printf '%s\n' "${HOME}" ;;
"~/"*) printf '%s/%s\n' "${HOME}" "${p#"~/"}" ;;
*) printf '%s\n' "$p" ;;
esac
}
# True for /dir and for C:/dir, the form in which git for Windows stores paths.
is_absolute_path() {
case "$1" in
/*|[A-Za-z]:[/\\]*) return 0 ;;
*) return 1 ;;
esac
}
prompt_template_dir() {
local initial="$1"
local input=''
local resolved=''
while true; do
if is_interactive && [ "${BASH_VERSINFO[0]}" -ge 4 ]; then
printf ' %sTemplate directory:%s ' "${C_BOLD}${C_BLUE}" "${C_RESET}"
read -r -e -i "${initial}" input < /dev/tty || true
elif is_interactive; then
# bash 3.2 (macOS) cannot put the default into the input line.
printf ' %sTemplate directory [%s]:%s ' "${C_BOLD}${C_BLUE}" "${initial}" "${C_RESET}"
read -r input < /dev/tty || true
else
printf ' %sTemplate directory:%s %s\n' "${C_BOLD}${C_BLUE}" "${C_RESET}" "$(code "${initial}")"
input="${initial}"
fi
[ -z "${input}" ] && input="${initial}"
resolved="$(resolve_template_dir "${input}")"
if ! is_absolute_path "${resolved}"; then
error "template directory must be an absolute path."
if is_interactive; then
continue
fi
return 1
fi
template_dir="${resolved}"
return 0
done
}
warn_template_dir_not_global() {
echo
warning "template directory is not configured globally."
echo " ${C_YELLOW}The template will not be found automatically.${C_RESET}"
}
# Old cmai versions take an unknown option as the API key and then run
# `git add .`. The check therefore reads the cmai script and does not run it.
cmai_is_current() {
local option
cmai_path="$(find_cmai)" || return 1
[ -r "${cmai_path}" ] || return 1
for option in "${CMAI_REQUIRED_OPTIONS[@]}"; do
grep -qF -e "${option})" "${cmai_path}" || return 1
done
}
# Prints the cmai script in use: the command on the PATH, or else the installed
# copy. The hook looks for cmai in the same order.
find_cmai() {
hash -r
if command -v cmai 2>/dev/null; then
return 0
fi
if [ -x "${CMAI_INSTALL_DIR}/git-commit.sh" ]; then
printf '%s\n' "${CMAI_INSTALL_DIR}/git-commit.sh"
return 0
fi
return 1
}
# True if a cmai script takes the API key from the environment. $1 = script.
cmai_reads_key_from_environment() {
grep -qF -e 'CMAI_API_KEY' "$1"
}
# Prints one line for each thing in a downloaded cmai script that does not look
# like cmai. $1 = script file. The script is read and parsed, but not run.
# These checks are heuristics: they catch a wrong, broken or crudely modified
# script, but they cannot prove that a script is harmless.
cmai_script_findings() {
local file="$1"
local option entry line host
head -n 1 "${file}" | grep -qE '^#!(/usr)?/bin/(env )?bash' || echo "is not a bash script"
bash -n "${file}" 2>/dev/null || echo "has a syntax error"
for option in "${CMAI_REQUIRED_OPTIONS[@]}"; do
grep -qF -e "${option})" "${file}" || echo "lacks the option ${option}"
done
[ "$(wc -c < "${file}")" -le 200000 ] || echo "is larger than expected"
if ! awk 'length($0) > 1000 { exit 1 }' "${file}"; then
echo "has very long lines"
fi
line="$(LC_ALL=C grep -n -m 1 '[^[:print:][:space:]]' "${file}" | cut -d: -f1 || true)"
if [ -n "${line}" ]; then
echo "contains non-ASCII or control characters (line ${line})"
fi
for entry in "${CMAI_UNEXPECTED_PATTERNS[@]}"; do
line="$(LC_ALL=C grep -nE -m 1 -e "${entry#*|}" "${file}" | cut -d: -f1 || true)"
if [ -n "${line}" ]; then
echo "${entry%%|*} (line ${line})"
fi
done
while IFS= read -r host; do
case "${CMAI_KNOWN_HOSTS}" in
*" ${host} "*) ;;
*) echo "names the unknown host ${host}" ;;
esac
done < <(LC_ALL=C grep -oE 'https?://[^/"'"'"' )]+' "${file}" | sed 's|.*://||; s|:.*||' | sort -u)
return 0
}
# Writes a cmai setting. The file is private from the moment it is created.
write_cmai_setting() {
local file="${CMAI_CONFIG_DIR}/$1"
(
umask 077
mkdir -p "${CMAI_CONFIG_DIR}" && printf '%s\n' "$2" > "${file}"
) && chmod 700 "${CMAI_CONFIG_DIR}" && chmod 600 "${file}"
}
keychain_title() {
case "${PLATFORM}" in
macos) printf 'macOS Keychain' ;;
windows) printf 'Windows Credential Manager' ;;
*) printf 'system keyring' ;;
esac
}
# Runs a command with a time limit of 20 seconds and with the stdin of the
# caller. A keychain tool can wait for a dialog that nobody sees, for example
# in an SSH session or without a default keychain.
limited() {
local pid
local started="${SECONDS}"
"$@" <&0 &
pid=$!
while kill -0 "${pid}" 2>/dev/null; do
if [ $((SECONDS - started)) -ge 20 ]; then
kill "${pid}" 2>/dev/null
wait "${pid}" 2>/dev/null || true
return 124
fi
sleep 0.1 2>/dev/null || sleep 1
done
wait "${pid}"
}
# True if this system has a keychain that the installer can use.
keychain_exists() {
local problem default_keychain
local status=0
case "${PLATFORM}" in
macos)
command -v security >/dev/null 2>&1 || return 1
# security prints the default keychain as a path in quotes. Without that
# keychain, every other security command opens a dialog and waits.
default_keychain="$(limited security default-keychain 2>/dev/null | sed -e 's/^[[:space:]]*"//' -e 's/"[[:space:]]*$//')" || return 1
[ -n "${default_keychain}" ] && [ -e "${default_keychain}" ]
;;
windows)
command -v powershell.exe >/dev/null 2>&1 && command -v iconv >/dev/null 2>&1 &&
command -v base64 >/dev/null 2>&1
;;
*)
command -v secret-tool >/dev/null 2>&1 || return 1
# Without a Secret Service (server, SSH session), secret-tool reports an error.
problem="$(limited secret-tool lookup service "${KEYCHAIN_ENTRY}" account "${KEYCHAIN_ACCOUNT}" 2>&1 >/dev/null)" || status=$?
[ -z "${problem}" ] && [ "${status}" -le 1 ]
;;
esac
}
# Prints the PowerShell script that writes, reads or deletes a generic
# credential in the Windows Credential Manager. The action and its values are
# in the environment variables CMAI_KEYCHAIN_ACTION, _TARGET, _USER and _SECRET.
windows_credential_script() {
cat <<'POWERSHELL_EOF'
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
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", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool CredWriteW(ref Credential credential, uint flags);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool CredDeleteW(string target, uint type, uint flags);
[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); }
}
public static void Write(string target, string user, string secret) {
byte[] blob = Encoding.Unicode.GetBytes(secret);
Credential credential = new Credential();
credential.Type = 1; // generic credential
credential.Persist = 2; // kept for this user on this computer
credential.TargetName = Marshal.StringToCoTaskMemUni(target);
credential.UserName = Marshal.StringToCoTaskMemUni(user);
credential.BlobSize = (uint)blob.Length;
credential.Blob = Marshal.AllocCoTaskMem(blob.Length);
try {
Marshal.Copy(blob, 0, credential.Blob, blob.Length);
if (!CredWriteW(ref credential, 0)) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
} finally {
Marshal.FreeCoTaskMem(credential.TargetName);
Marshal.FreeCoTaskMem(credential.UserName);
Marshal.FreeCoTaskMem(credential.Blob);
}
}
public static void Delete(string target) { CredDeleteW(target, 1, 0); }
}
'@
switch ($env:CMAI_KEYCHAIN_ACTION) {
'write' { [CmaiCredential]::Write($env:CMAI_KEYCHAIN_TARGET, $env:CMAI_KEYCHAIN_USER, $env:CMAI_KEYCHAIN_SECRET) }
'read' {
$secret = [CmaiCredential]::Read($env:CMAI_KEYCHAIN_TARGET)
if ($null -eq $secret) { exit 1 }
[Console]::Out.Write($secret)
}
'delete' { [CmaiCredential]::Delete($env:CMAI_KEYCHAIN_TARGET) }
}
POWERSHELL_EOF
}
# Runs the credential script. $1 = action, $2 = secret for the action write.
run_windows_credential() {
local script
# -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')" || return 1
# Git Bash rewrites arguments and variables that look like a path. The
# MSYS settings keep the script and a secret that starts with a slash as they are.
CMAI_KEYCHAIN_ACTION="$1" CMAI_KEYCHAIN_TARGET="${KEYCHAIN_ENTRY}" CMAI_KEYCHAIN_USER="${KEYCHAIN_ACCOUNT}" \
CMAI_KEYCHAIN_SECRET="${2:-}" MSYS2_ENV_CONV_EXCL='CMAI_KEYCHAIN_SECRET' \
MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' \
limited powershell.exe -NoProfile -NonInteractive -EncodedCommand "${script}"
}
# Stores the secret $1 in the system keychain. The secret goes to the keychain
# tool on stdin or in the environment and never as a command argument, because
# other local users can read the arguments of a running process.
keychain_set() {
case "${PLATFORM}" in
macos)
# `security -i` reads its command from stdin. Its quoting is simple, so
# only a secret without quote, backslash and space goes this way.
case "$1" in
*[!A-Za-z0-9._~+/=:@%-]*) return 1 ;;
esac
printf 'add-generic-password -U -s "%s" -a "%s" -l "%s" -w "%s"\n' \
"${KEYCHAIN_ENTRY}" "${KEYCHAIN_ACCOUNT}" "${KEYCHAIN_LABEL}" "$1" | limited security -i >/dev/null
;;
windows)
run_windows_credential write "$1" >/dev/null
;;
*)
printf '%s' "$1" | limited secret-tool store --label="${KEYCHAIN_LABEL}" \
service "${KEYCHAIN_ENTRY}" account "${KEYCHAIN_ACCOUNT}"
;;
esac
}
# Prints the secret from the system keychain.
keychain_get() {
case "${PLATFORM}" in
macos)
limited security find-generic-password -s "${KEYCHAIN_ENTRY}" -a "${KEYCHAIN_ACCOUNT}" -w 2>/dev/null
;;
windows)
run_windows_credential read 2>/dev/null | tr -d '\r'
;;
*)
limited secret-tool lookup service "${KEYCHAIN_ENTRY}" account "${KEYCHAIN_ACCOUNT}" 2>/dev/null
;;
esac
}
keychain_delete() {
case "${PLATFORM}" in
macos)
limited security delete-generic-password -s "${KEYCHAIN_ENTRY}" -a "${KEYCHAIN_ACCOUNT}" >/dev/null 2>&1
;;
windows)
run_windows_credential delete >/dev/null 2>&1
;;
*)
limited secret-tool clear service "${KEYCHAIN_ENTRY}" account "${KEYCHAIN_ACCOUNT}" 2>/dev/null
;;
esac
}
# Prints the editor command that git starts for a commit message.
detect_editor() {
local editor
editor="$(git var GIT_EDITOR 2>/dev/null || true)"
if [ -z "${editor}" ]; then
editor="${VISUAL:-${EDITOR:-}}"
fi
printf '%s' "${editor}"
}
# Prints vim, nvim or other for an editor command. Follows symbolic links such
# as the Debian `editor` alternative.
editor_kind() {
local command_name="${1%% *}"
local resolved
resolved="$(command -v -- "${command_name}" 2>/dev/null || true)"
if [ -n "${resolved}" ]; then
resolved="$(readlink -f -- "${resolved}" 2>/dev/null || printf '%s' "${resolved}")"
fi
case "$(basename -- "${resolved:-${command_name}}")" in
nvim*) echo nvim ;;