-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithelper.sh
More file actions
executable file
·2828 lines (2513 loc) · 117 KB
/
Copy pathgithelper.sh
File metadata and controls
executable file
·2828 lines (2513 loc) · 117 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
# =============================================
# Interactive Git + GitHub Helper for Termux
# =============================================
# ── Colors ────────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
RESET='\033[0m'
# ── Script location ────────────────────────────────────────────────────────
# Used to co-locate some state files with the repo this script lives in,
# instead of always dumping them in $HOME.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
# ── Config file (saved GitHub accounts) ───────────────────────────────────────
CONFIG_FILE="$SCRIPT_DIR/.githelper_accounts"
LAST_MSG_FILE="$SCRIPT_DIR/.githelper_lastmsg"
AI_CONFIG_FILE="$SCRIPT_DIR/.githelper_ai_engine"
# Per-account SSH signing key mapping, one line per account:
# username:keypath:email
# keypath points at the PRIVATE key file (its .pub sibling is used for
# allowed_signers / display). Used to auto-apply the right signing identity
# whenever quick_switch_account / gh_switch_to_saved switches accounts, so
# two Termux accounts never accidentally sign commits with the wrong key.
SSH_KEY_CONFIG_FILE="$HOME/.githelper_ssh_keys"
ALLOWED_SIGNERS_FILE="$HOME/.ssh/allowed_signers"
DRY_RUN=false
# ── AI engine list (order = priority if none configured) ─────────────────────
# Status: gemini, openrouter = live. anthropic, openai, megallm = placeholders
# (env var read + curl wiring present, but left for future endpoint/model tuning).
AI_ENGINES=(gemini openrouter anthropic openai megallm)
# Gemini-specific model cascade (tried in this order within the gemini engine).
# On any recoverable failure for one model -- quota exhaustion (HTTP 429 /
# RESOURCE_EXHAUSTED), a deprecated/missing model, a server overload, a
# safety-blocked empty response, etc. -- automatically falls through to the
# next model. Only a rejected/invalid key (401/403) skips straight to the
# next configured key instead of the next model.
GEMINI_MODELS=(gemini-3.5-flash gemini-3.1-flash-lite gemini-2.5-flash gemini-2.5-flash-lite)
ai_env_var() {
case "$1" in
gemini) echo "GEMINI_API_KEY" ;;
openrouter) echo "OPENROUTER_API_KEY" ;;
anthropic) echo "ANTHROPIC_API_KEY" ;;
openai) echo "OPENAI_API_KEY" ;;
megallm) echo "MEGALLM_API_KEY" ;;
esac
}
# Multiple keys per engine are supported by setting the env var to a
# comma-separated list, e.g. GEMINI_API_KEY="key1,key2,key3".
# This returns that engine's keys as a bash array (via global AI_KEYS).
ai_keys_for() {
local engine="$1" var raw
var=$(ai_env_var "$engine")
raw="${!var}"
AI_KEYS=()
[ -z "$raw" ] && return 0
local IFS=','
read -ra AI_KEYS <<< "$raw"
# trim whitespace around each key
local i
for i in "${!AI_KEYS[@]}"; do
AI_KEYS[$i]=$(echo "${AI_KEYS[$i]}" | xargs)
done
}
ai_engine_live() {
# Engines with an actual API call implemented below
case "$1" in
gemini|openrouter) return 0 ;;
*) return 1 ;;
esac
}
ai_load_config() {
AI_ACTIVE=""
AI_FALLBACKS=()
if [ -f "$AI_CONFIG_FILE" ]; then
AI_ACTIVE=$(sed -n '1p' "$AI_CONFIG_FILE")
local fb_line
fb_line=$(sed -n '2p' "$AI_CONFIG_FILE")
[ -n "$fb_line" ] && IFS=',' read -ra AI_FALLBACKS <<< "$fb_line"
fi
[ -z "$AI_ACTIVE" ] && AI_ACTIVE="gemini"
}
ai_check_deps() {
local missing=()
command -v curl &>/dev/null || missing+=(curl)
command -v jq &>/dev/null || missing+=(jq)
if [ ${#missing[@]} -gt 0 ]; then
echo -e "${RED}✗ Missing: ${missing[*]}. Install with: pkg install ${missing[*]}${RESET}" >&2
return 1
fi
}
ai_save_config() {
{
echo "$AI_ACTIVE"
local IFS=','
echo "${AI_FALLBACKS[*]}"
} > "$AI_CONFIG_FILE"
}
# ── m) AI Engine Selector ──────────────────────────────────────────────────────
ai_engine_config() {
ai_load_config
echo -e "${CYAN}${BOLD}AI Engine Selector${RESET}\n"
echo -e "${BLUE}Active: $AI_ACTIVE${RESET}"
echo -e "${BLUE}Fallback: ${AI_FALLBACKS[*]:-none}${RESET}\n"
for i in "${!AI_ENGINES[@]}"; do
local e="${AI_ENGINES[$i]}" status key_state
ai_keys_for "$e"
if [ ${#AI_KEYS[@]} -eq 1 ]; then
key_state="${GREEN}1 key${RESET}"
elif [ ${#AI_KEYS[@]} -gt 1 ]; then
key_state="${GREEN}${#AI_KEYS[@]} keys${RESET}"
else
key_state="${YELLOW}no key${RESET}"
fi
if ai_engine_live "$e"; then status="${GREEN}live${RESET}"; else status="${MAGENTA}placeholder${RESET}"; fi
printf " %d) %-12s [%s, %s]\n" "$((i+1))" "$e" "$status" "$key_state"
done
echo ""
echo " s) Set active engine"
echo " f) Set fallback order (comma list of numbers, e.g. 2,1)"
echo " t) Test active engine"
echo " q) Back"
read -rp "Choice: " ac
case $ac in
s|S)
read -rp "Active engine number: " n
if [[ $n =~ ^[0-9]+$ ]] && [ "$n" -ge 1 ] && [ "$n" -le "${#AI_ENGINES[@]}" ]; then
AI_ACTIVE="${AI_ENGINES[$((n-1))]}"
ai_save_config
echo -e "${GREEN}✓ Active engine set to $AI_ACTIVE${RESET}"
fi
;;
f|F)
read -rp "Fallback order (numbers, comma-separated): " fb
AI_FALLBACKS=()
IFS=',' read -ra picks <<< "$fb"
for n in "${picks[@]}"; do
n=$(echo "$n" | xargs)
if [[ $n =~ ^[0-9]+$ ]] && [ "$n" -ge 1 ] && [ "$n" -le "${#AI_ENGINES[@]}" ]; then
AI_FALLBACKS+=("${AI_ENGINES[$((n-1))]}")
fi
done
ai_save_config
echo -e "${GREEN}✓ Fallback order: ${AI_FALLBACKS[*]:-none}${RESET}"
;;
t|T)
local out
out=$(ai_call "Reply with exactly: OK")
if [ -n "$out" ]; then
echo -e "${GREEN}✓ $AI_ACTIVE responded:${RESET} $out"
else
echo -e "${RED}✗ No response from $AI_ACTIVE (and any fallbacks).${RESET}"
fi
;;
esac
}
# ── Generic AI call with active engine + fallback chain ───────────────────────
# Usage: ai_call "prompt text" → prints response to stdout, empty on total failure
ai_call() {
local prompt="$1"
ai_check_deps || return 1
ai_load_config
local chain=("$AI_ACTIVE" "${AI_FALLBACKS[@]}")
local tried=()
local total_engines=${#chain[@]}
local engine_num=0
for engine in "${chain[@]}"; do
[ -z "$engine" ] && continue
engine_num=$((engine_num+1))
# skip duplicates
[[ " ${tried[*]} " == *" $engine "* ]] && continue
tried+=("$engine")
if ! ai_engine_live "$engine"; then
echo -e "${YELLOW}↷ Skipping $engine (placeholder, not implemented yet)${RESET}" >&2
continue
fi
ai_keys_for "$engine"
if [ ${#AI_KEYS[@]} -eq 0 ]; then
local var
var=$(ai_env_var "$engine")
echo -e "${YELLOW}↷ Skipping $engine (no $var set)${RESET}" >&2
continue
fi
progress_step "Engine: $engine" "$engine_num" "$total_engines"
local key_idx result key_used
for key_idx in "${!AI_KEYS[@]}"; do
local key="${AI_KEYS[$key_idx]}"
[ -z "$key" ] && continue
key_used=$((key_idx+1))
if [ "${#AI_KEYS[@]}" -gt 1 ]; then
echo -e " ${CYAN}key ${key_used}/${#AI_KEYS[@]}${RESET}" >&2
fi
case "$engine" in
gemini) result=$(ai_call_gemini "$key" "$prompt") ;;
openrouter) result=$(ai_call_openrouter "$key" "$prompt") ;;
esac
if [ -n "$result" ]; then
echo "$result"
return 0
else
echo -e "${YELLOW}✗ $engine key $key_used failed, trying next...${RESET}" >&2
fi
done
done
echo -e "${RED}✗ All configured engines failed or unavailable.${RESET}" >&2
return 1
}
ai_call_gemini() {
local key="$1" prompt="$2"
local payload
payload=$(jq -n --arg p "$prompt" '{contents:[{parts:[{text:$p}]}]}')
[ -z "$payload" ] && return 1
# Try models in order. Quota exhaustion (429 / RESOURCE_EXHAUSTED) falls
# through to the next model, and so does everything else *except* a
# genuine auth/key failure -- a 404 for a deprecated model name, a 503
# overload, or a safety-blocked empty response are model-specific or
# transient and worth retrying on the next model. Only a bad/invalid key
# is truly pointless to retry across models, so that's the one case that
# jumps straight to the next key.
local model model_num=0 total_models=${#GEMINI_MODELS[@]}
for model in "${GEMINI_MODELS[@]}"; do
model_num=$((model_num+1))
if $DRY_RUN; then
echo -e " ${MAGENTA}[dry-run] would call $model${RESET}" >&2
echo "[dry-run OK: $model]"
return 0
fi
local response http_code body
response=$(run_spinner "Gemini ${model} (${model_num}/${total_models})" \
curl -s --max-time 30 -w $'\n%{http_code}' -X POST \
"https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=$key" \
-H "Content-Type: application/json" \
-d "$payload")
http_code=$(echo "$response" | tail -1)
body=$(echo "$response" | sed '$d')
if [ "$http_code" == "200" ]; then
local text
text=$(echo "$body" | jq -r '.candidates[0].content.parts[0].text // empty' 2>/dev/null)
if [ -n "$text" ]; then
echo "$text"
return 0
fi
echo -e " ${YELLOW}↷ $model: 200 but no text (likely safety-blocked), trying next Gemini model...${RESET}" >&2
continue
fi
if [ "$http_code" == "429" ] || echo "$body" | grep -qi "RESOURCE_EXHAUSTED"; then
echo -e " ${YELLOW}↷ $model: quota exhausted, trying next Gemini model...${RESET}" >&2
continue
fi
if [ "$http_code" == "401" ] || [ "$http_code" == "403" ] || \
echo "$body" | grep -qiE "API_KEY_INVALID|UNAUTHENTICATED|PERMISSION_DENIED"; then
echo -e " ${RED}✗ $model: key rejected (HTTP $http_code) — skipping remaining models for this key.${RESET}" >&2
return 1
fi
# Anything else (404 deprecated model, 500/503 overloaded, network
# hiccup, etc.) is model-specific or transient -- try the next model
# before giving up on this key entirely.
echo -e " ${YELLOW}↷ $model: request failed (HTTP $http_code), trying next Gemini model...${RESET}" >&2
done
return 1
}
ai_call_openrouter() {
local key="$1" prompt="$2"
local payload
payload=$(jq -n --arg p "$prompt" '{model:"openrouter/auto",messages:[{role:"user",content:$p}]}' 2>/dev/null)
[ -z "$payload" ] && return 1
if $DRY_RUN; then
echo -e " ${MAGENTA}[dry-run] would call openrouter${RESET}" >&2
echo "[dry-run OK: openrouter]"
return 0
fi
local response
response=$(run_spinner "OpenRouter" \
curl -s --max-time 30 -X POST "https://openrouter.ai/api/v1/chat/completions" \
-H "Authorization: Bearer $key" \
-H "Content-Type: application/json" \
-d "$payload")
echo "$response" | jq -r '.choices[0].message.content // empty' 2>/dev/null
}
# ── Placeholder engines (future implementation) ───────────────────────────────
# Anthropic, OpenAI, and Megallm calls go here once wired up. They're already
# selectable in the menu and will be skipped automatically by ai_call() until
# ai_engine_live() is updated to return 0 for them and a matching
# ai_call_<engine>() function is added above.
ai_call_anthropic() { :; }
ai_call_openai() { :; }
ai_call_megallm() { :; }
# ── Parse flags & direct-launch args ─────────────────────────────────────────
# Usage:
# gh1 → interactive menu (normal mode)
# gh1 --dry-run → interactive menu, no commands execute
# gh1 <file> → jump straight to file history for that file
# gh1 --gitignore → jump straight to .gitignore editor
# gh1 --workspace → jump straight to workspace switcher
DIRECT_MODE=""
DIRECT_FILE=""
for arg in "$@"; do
case "$arg" in
--dry-run) DRY_RUN=true ;;
--gitignore) DIRECT_MODE="gitignore" ;;
--workspace) DIRECT_MODE="workspace" ;;
--help) DIRECT_MODE="help" ;;
--*) echo -e "${RED}Unknown flag: $arg${RESET}"; exit 1 ;;
*)
# Treat any non-flag argument as a file path for file history
DIRECT_FILE="$arg"
DIRECT_MODE="filehistory"
;;
esac
done
# ── Run or simulate a command ─────────────────────────────────────────────────
run() {
if $DRY_RUN; then
echo -e "${MAGENTA}[dry-run] $*${RESET}"
else
"$@"
fi
}
# ── Progress: spinner + step counter ──────────────────────────────────────────
# Two pieces that combine for multi-phase operations:
# progress_step "label" cur total → prints "[cur/total] label" once, no spin
# run_spinner "label" cmd args... → runs cmd in background, spins until done,
# then prints a final ✓/✗ line in its place
#
# Usage in a phase loop:
# progress_step "Pushing to origin" 1 1
# run_spinner "git push" git push
#
# run_spinner captures the command's stdout+stderr to a temp file and replays it
# after the spinner line is cleared, so output isn't lost or interleaved.
PROGRESS_ACTIVE=false # set true while a spinner owns the terminal line
progress_step() {
local label="$1" cur="$2" total="$3"
echo -e "${CYAN}[${cur}/${total}]${RESET} ${label}" >&2
}
run_spinner() {
local label="$1"; shift
local frames='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
local tmp_out
tmp_out=$(mktemp)
if $DRY_RUN; then
echo -e "${MAGENTA}[dry-run] $*${RESET}"
rm -f "$tmp_out"
return 0
fi
"$@" > "$tmp_out" 2>&1 &
local pid=$!
PROGRESS_ACTIVE=true
local i=0
local start_ts=$SECONDS
# Hide cursor while spinning, always restore it on exit (even on Ctrl-C)
tput civis >&2 2>/dev/null
trap 'tput cnorm >&2 2>/dev/null' RETURN
while kill -0 "$pid" 2>/dev/null; do
local frame="${frames:i++%${#frames}:1}"
local elapsed=$((SECONDS - start_ts))
printf "\r${MAGENTA}%s${RESET} %s ${YELLOW}(%ds)${RESET}\033[K" "$frame" "$label" "$elapsed" >&2
sleep 0.1
done
wait "$pid"
local status=$?
tput cnorm >&2 2>/dev/null
PROGRESS_ACTIVE=false
printf "\r\033[K" >&2
if [ $status -eq 0 ]; then
echo -e "${GREEN}✓${RESET} ${label}" >&2
else
echo -e "${RED}✗${RESET} ${label} ${RED}(exit $status)${RESET}" >&2
fi
# Replay captured output below the status line
if [ -s "$tmp_out" ]; then
cat "$tmp_out"
fi
rm -f "$tmp_out"
return $status
}
# ── Helpers ───────────────────────────────────────────────────────────────────
require_repo() {
if ! git rev-parse --git-dir &>/dev/null; then
echo -e "${RED}✗ Not inside a git repository.${RESET}"
return 1
fi
}
require_gh() {
if ! command -v gh &>/dev/null; then
echo -e "${RED}✗ 'gh' CLI is not installed. Install it with: pkg install gh${RESET}"
return 1
fi
if ! gh auth status &>/dev/null; then
echo -e "${RED}✗ Not logged in to GitHub. Run: gh auth login${RESET}"
return 1
fi
}
require_copilot() {
require_gh || return 1
if ! gh copilot --help &>/dev/null; then
echo -e "${RED}✗ 'gh copilot' extension not installed.${RESET}"
read -rp "Install it now with 'gh extension install github/gh-copilot'? (y/n) [y]: " inst
inst="${inst:-y}"
if [[ $inst == y || $inst == Y ]]; then
run gh extension install github/gh-copilot || { echo -e "${RED}✗ Install failed.${RESET}"; return 1; }
else
return 1
fi
fi
}
# ── Numbered branch picker ─────────────────────────────────────────────────────
pick_branch() {
local prompt="${1:-Branch}"
local branches=()
while IFS= read -r b; do
branches+=("$(echo "$b" | sed 's/^\*[[:space:]]*//' | xargs)")
done < <(git branch -a 2>/dev/null | grep -v HEAD)
if [ ${#branches[@]} -eq 0 ]; then
echo -e "${YELLOW}No branches found.${RESET}" >&2
return 1
fi
echo -e "${CYAN}Available branches:${RESET}" >&2
for i in "${!branches[@]}"; do
printf " %2d) %s\n" "$((i+1))" "${branches[$i]}" >&2
done
echo "" >&2
read -rp "$prompt (number or name): " sel
# If numeric pick
if [[ $sel =~ ^[0-9]+$ ]] && [ "$sel" -ge 1 ] && [ "$sel" -le "${#branches[@]}" ]; then
echo "${branches[$((sel-1))]}"
else
echo "$sel"
fi
}
# ── Stage preview before commit ───────────────────────────────────────────────
stage_and_confirm() {
echo -e "${CYAN}Changed files:${RESET}"
git status -s
echo ""
read -rp "Stage all changes? (y/n) [y]: " sa
sa="${sa:-y}"
if [[ $sa == y || $sa == Y ]]; then
run git add -A
return 0
else
echo -e "${YELLOW}Aborted — nothing staged.${RESET}"
return 1
fi
}
# ── Secret redaction before sending any diff to an AI engine ──────────────────
# Two passes:
# 1. Hard patterns (AWS keys, GH tokens, private key blocks, key=/secret=/
# password= assignments, JWTs, generic API key formats) → auto-redacted,
# no prompt, since these are unambiguous.
# 2. Lines that merely *look* like they could hold a secret (long random-ish
# token assigned to a var) → shown to the user, who decides per line.
# This only touches the text sent to the AI; the real diff used for git
# commit / gh pr diff is never modified.
redact_diff() {
local diff="$1"
local redacted=""
local line
local q="\"'" # quote chars, used as a bracket-class fragment below
local in_key_block=0
# NOTE: matching below uses bash's native `[[ =~ ]]` instead of piping
# through `echo | grep` for every pattern on every line. The old version
# forked 2 external processes per pattern per line (6+ patterns x every
# line in the diff), which is what made this step slow — process
# spawning is expensive, especially under Termux/Android. Native bash
# regex has no fork/exec cost. The sed substitutions below still fork,
# but only on lines that actually matched, which is rare.
local pat_end_key='^[+-]?[[:space:]]*-----END (RSA|EC|OPENSSH|PGP|DSA)? ?PRIVATE KEY-----'
local pat_begin_key='^[+-]?[[:space:]]*-----BEGIN (RSA|EC|OPENSSH|PGP|DSA)? ?PRIVATE KEY-----'
local pat_aws='AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}'
local pat_gh='gh[pousr]_[A-Za-z0-9]{20,}'
local pat_sk='sk-(ant-|proj-)?[A-Za-z0-9_-]{20,}'
local pat_kv="(api[_-]?key|secret|password|passwd|token|access[_-]?key)[$q]?[[:space:]]*[:=][[:space:]]*[$q]?[A-Za-z0-9_/+=-]{12,}"
local pat_jwt='eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}'
local pat_ambiguous="^[+-].{0,40}[:=][[:space:]]*[$q]?[A-Za-z0-9_/+-]{24,}[$q]?"
while IFS= read -r line <&3; do
local hard_hit=0
if [ "$in_key_block" -eq 1 ]; then
[[ $line =~ $pat_end_key ]] && in_key_block=0
redacted+="[REDACTED_PRIVATE_KEY_BLOCK]"$'\n'
continue
fi
# --- Hard, unambiguous patterns -> always redact, no prompt ---
if [[ $line =~ $pat_aws ]]; then
line=$(echo "$line" | sed -E 's/(AKIA|ASIA)[0-9A-Z]{16}/[REDACTED_AWS_KEY]/g')
hard_hit=1
fi
if [[ $line =~ $pat_gh ]]; then
line=$(echo "$line" | sed -E 's/gh[pousr]_[A-Za-z0-9]{20,}/[REDACTED_GH_TOKEN]/g')
hard_hit=1
fi
if [[ $line =~ $pat_sk ]]; then
line=$(echo "$line" | sed -E 's/sk-(ant-|proj-)?[A-Za-z0-9_-]{20,}/[REDACTED_API_KEY]/g')
hard_hit=1
fi
if [[ $line =~ $pat_begin_key ]]; then
line="[REDACTED_PRIVATE_KEY_BLOCK]"
hard_hit=1
in_key_block=1
fi
local kv_hit=0
shopt -s nocasematch
[[ $line =~ $pat_kv ]] && kv_hit=1
shopt -u nocasematch
if [ "$kv_hit" -eq 1 ]; then
line=$(echo "$line" | sed -E "s/([:=][[:space:]]*[$q]?)[A-Za-z0-9_/+=-]{12,}([$q]?)/\1[REDACTED]\2/")
hard_hit=1
fi
if [[ $line =~ $pat_jwt ]]; then
line=$(echo "$line" | sed -E 's/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/[REDACTED_JWT]/g')
hard_hit=1
fi
# --- Ambiguous pass: long random-looking token, not already handled ---
if [ "$hard_hit" -eq 0 ] && [[ $line =~ $pat_ambiguous ]]; then
echo "" >&2
echo -e "${YELLOW}⚠ Possible secret in diff:${RESET}" >&2
echo -e "${CYAN}$line${RESET}" >&2
read -rp "Send this line to AI as-is? (y = send, n = redact) [n]: " sendit < /dev/tty >&2 2>/dev/null || \
read -rp "Send this line to AI as-is? (y = send, n = redact) [n]: " sendit >&2
sendit="${sendit:-n}"
if [[ $sendit != y && $sendit != Y ]]; then
line=$(echo "$line" | sed -E "s/([:=][[:space:]]*[$q]?)[A-Za-z0-9_/+-]{24,}([$q]?)/\1[REDACTED]\2/")
fi
fi
redacted+="$line"$'\n'
done 3<<< "$diff"
echo "$redacted"
}
suggest_commit_msg() {
local diff
diff=$(git diff --cached --stat; echo; git diff --cached | head -c 6000)
if [ -z "$diff" ]; then
echo -e "${YELLOW}Nothing staged to summarize.${RESET}" >&2
return 1
fi
diff=$(redact_diff "$diff")
ai_load_config
echo " 1) gh copilot" >&2
echo " 2) AI rotator (active: $AI_ACTIVE)" >&2
read -rp "Use which engine? [2]: " eng >&2
eng="${eng:-2}"
if [[ $eng == 1 ]]; then
require_copilot || return 1
echo -e "${MAGENTA}Asking Copilot for a commit message...${RESET}" >&2
local copilot_out copilot_status
copilot_out=$(gh copilot suggest -t shell --non-interactive \
"Write a single concise conventional-commit style git commit message (one line, no quotes, no explanation) for this staged diff:
$diff" 2>&1)
copilot_status=$?
if [ $copilot_status -ne 0 ] || [ -z "$copilot_out" ]; then
echo -e "${YELLOW}↷ gh copilot failed (exit $copilot_status):${RESET} ${copilot_out:-no output}" >&2
return 1
fi
echo "$copilot_out" | grep -vE '^(gh|Suggestion|Welcome|$)' | sed -n '1{/^[[:space:]]*$/d};p' | head -1
else
ai_call "Write a single concise conventional-commit style git commit message (one line, no quotes, no explanation, no markdown) for this staged diff:
$diff" | head -1
fi
}
# ── Commit with last-message memory ───────────────────────────────────────────
commit_with_msg() {
local last_msg=""
[ -f "$LAST_MSG_FILE" ] && last_msg=$(cat "$LAST_MSG_FILE")
if [ -n "$last_msg" ]; then
echo -e "${BLUE}Last message: ${last_msg}${RESET}"
read -rp "Commit message (Enter to reuse last, '?' for AI suggestion): " msg
else
read -rp "Commit message ('?' for AI suggestion): " msg
fi
if [[ $msg == "?" ]]; then
local ai_msg
ai_msg=$(suggest_commit_msg)
if [ -n "$ai_msg" ]; then
echo -e "${GREEN}Suggested: ${ai_msg}${RESET}"
read -rp "Use this message? (y/n) [y]: " useit
useit="${useit:-y}"
if [[ $useit == y || $useit == Y ]]; then
msg="$ai_msg"
else
read -rp "Commit message: " msg
fi
else
echo -e "${YELLOW}Could not get a suggestion.${RESET}"
read -rp "Commit message: " msg
fi
fi
[ -z "$msg" ] && [ -n "$last_msg" ] && msg="$last_msg"
if [ -z "$msg" ]; then
echo -e "${YELLOW}Aborted — empty message.${RESET}"
return 1
fi
echo "$msg" > "$LAST_MSG_FILE"
run git commit -m "$msg" && echo -e "${GREEN}✓ Committed: $msg${RESET}"
}
# ── Force-push menu shown after a hard reset ─────────────────────────────────
# Call this after any hard reset so the user can optionally rewrite the remote.
force_push_after_reset() {
# Only makes sense inside a repo with a remote
if ! git rev-parse --git-dir &>/dev/null; then return; fi
local remote_url
remote_url=$(git remote get-url origin 2>/dev/null)
[ -z "$remote_url" ] && return
local branch
branch=$(git branch --show-current)
# Show how local compares to origin
local ahead behind
ahead=$(git rev-list --count "origin/${branch}..HEAD" 2>/dev/null || echo "?")
behind=$(git rev-list --count "HEAD..origin/${branch}" 2>/dev/null || echo "?")
echo ""
echo -e "${CYAN}${BOLD}── Remote status ──${RESET}"
if [[ $ahead == "0" && $behind == "0" ]]; then
echo -e "${GREEN}Local branch is in sync with origin/${branch}.${RESET}"
return
fi
[ "$ahead" != "0" ] && echo -e "${YELLOW}Local is ${ahead} commit(s) ahead of origin/${branch}.${RESET}"
[ "$behind" != "0" ] && echo -e "${YELLOW}Local is ${behind} commit(s) behind origin/${branch}.${RESET}"
echo ""
echo -e "${YELLOW}Force-push this reset to origin?${RESET}"
echo -e "${RED}This will rewrite the remote branch history.${RESET}"
echo -e "Only do this if you intend to replace the remote history.\n"
echo " 1) No (default)"
echo " 2) Force push (safe): git push --force-with-lease origin ${branch}"
echo " 3) Force push anyway: git push --force origin ${branch}"
echo ""
read -rp "Choice [1]: " fpc
fpc="${fpc:-1}"
case $fpc in
2)
run_spinner "Force push (--force-with-lease) origin/${branch}" \
git push --force-with-lease origin "$branch"
;;
3)
echo -e "${RED}${BOLD}WARNING: This rewrites remote history permanently.${RESET}"
read -rp "Type YES to confirm: " fpconfirm
if [[ $fpconfirm == "YES" ]]; then
run_spinner "Force push (--force) origin/${branch}" \
git push --force origin "$branch"
else
echo -e "${YELLOW}Force push cancelled.${RESET}"
fi
;;
*)
echo -e "${YELLOW}Skipped — remote not changed.${RESET}"
;;
esac
}
# ── Detect the repo's default branch (main/master/etc) ────────────────────────
# Local-only, no network calls: prefers the remote HEAD symref set at clone
# time, falls back to checking common names against already-fetched
# remote-tracking refs. Repo-agnostic by construction — never hardcodes
# "main".
detect_default_branch() {
local ref
ref=$(git symbolic-ref -q refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@')
if [ -n "$ref" ]; then
echo "$ref"
return 0
fi
local candidate
for candidate in main master develop; do
if git rev-parse --verify -q "origin/$candidate" &>/dev/null; then
echo "$candidate"
return 0
fi
done
return 1
}
# ── Re-sign commits (fix missing/failed "Verified" badges) ────────────────────
# Repo/account-agnostic: reads whatever signing key is *currently active*
# in git config (set via apply_account_signing / the Account Manager, or
# manually) — never assumes a specific key path, repo, or account. Detects
# unsigned/bad-signature commits using git's own %G? status per commit
# rather than any hardcoded SHA list, so it works on any branch in any repo.
#
# Scoping: by default this only ever looks at commits unique to the CURRENT
# branch since it diverged from the repo's default branch (via merge-base) --
# not an arbitrary slice of shared history. That's almost always what "resign
# my commits" actually means, and it keeps a crude scroll-and-copy-a-hash
# step out of the common case.
resign_commits() {
echo -e "${CYAN}${BOLD}Re-sign commits (fix missing/failed signatures)${RESET}\n"
local signingkey signing_on
signingkey=$(git config user.signingkey 2>/dev/null)
signing_on=$(git config commit.gpgsign 2>/dev/null)
if [ -z "$signingkey" ] || [[ "$signing_on" != "true" ]]; then
echo -e "${RED}✗ No active SSH signing key configured for this repo/account.${RESET}"
echo -e "${YELLOW} Set one up first: 'G) GitHub Accounts → k) Set/generate SSH signing key'.${RESET}"
return 1
fi
echo -e "${BLUE}Signing key in use: $signingkey${RESET}\n"
# Cross-check against whichever account gh is CURRENTLY authenticated
# as. Local user.signingkey/user.name only get refreshed when you switch
# accounts through this script (quick_switch_account / gh_switch_to_saved)
# -- if the gh session moved on since (another switch elsewhere, a raw
# `gh auth switch`), this repo's local config would still point at the
# old account's key. That would sign commits under the wrong identity.
local git_identity gh_active
git_identity=$(git config user.name 2>/dev/null)
gh_active=$(gh api user --jq '.login' 2>/dev/null)
if [ -n "$gh_active" ] && [ -n "$git_identity" ] && [ "$gh_active" != "$git_identity" ]; then
echo -e "${RED}✗ Mismatch: this repo is configured to sign as '$git_identity',${RESET}"
echo -e "${RED} but gh is currently authenticated as '$gh_active'.${RESET}"
echo -e "${YELLOW} Re-sync first: 'S) Switch GH Account' → pick '$gh_active', then retry.${RESET}"
read -rp "Continue signing as '$git_identity' anyway? (y/n) [n]: " force_mismatch
[[ $force_mismatch != y && $force_mismatch != Y ]] && { echo -e "${YELLOW}Cancelled.${RESET}"; return 1; }
fi
local branch
branch=$(git branch --show-current)
if [ -z "$branch" ]; then
echo -e "${RED}✗ Not on a branch (detached HEAD?) — aborting.${RESET}"
return 1
fi
local default_branch
default_branch=$(detect_default_branch)
if [ -n "$default_branch" ] && [ "$branch" == "$default_branch" ]; then
echo -e "${RED}${BOLD}⚠ You're on '$branch', which looks like this repo's default branch.${RESET}"
echo -e "${RED} Rewriting shared trunk history is rarely what you want and can break${RESET}"
echo -e "${RED} other clones/collaborators of this branch.${RESET}\n"
read -rp "Type YES to fall back to manual mode anyway: " trunk_confirm
[ "$trunk_confirm" != "YES" ] && { echo -e "${YELLOW}Cancelled.${RESET}"; return 1; }
_resign_manual_fallback "$branch"
return $?
fi
local base=""
if [ -n "$default_branch" ]; then
base=$(git merge-base HEAD "origin/$default_branch" 2>/dev/null || git merge-base HEAD "$default_branch" 2>/dev/null)
fi
if [ -z "$base" ]; then
echo -e "${YELLOW}↷ Couldn't auto-detect where '$branch' diverged from the default branch.${RESET}"
_resign_manual_fallback "$branch"
return $?
fi
# %G? per commit: G=good, U=good/unknown validity, B=bad, X/Y/R=expired
# or revoked, E=can't check, N=no signature at all.
local hashes=() lines=() i=0
while IFS= read -r line; do
i=$((i+1))
lines+=("$line")
hashes+=("$(echo "$line" | awk '{print $1}')")
done < <(git log --pretty=format:"%h [%G?] %s" "${base}..HEAD")
if [ ${#lines[@]} -eq 0 ]; then
echo -e "${GREEN}✓ '$branch' has no commits beyond '$default_branch' — nothing to resign.${RESET}"
return 0
fi
echo -e "${CYAN}Commits on '$branch' since it diverged from '$default_branch':${RESET}"
local n
for n in "${!lines[@]}"; do
printf " %d) %s\n" "$((n+1))" "${lines[$n]}"
done
echo ""
echo -e "${YELLOW}Press Enter to re-sign ALL ${#lines[@]} of the above.${RESET}"
echo -e "${YELLOW}Or enter a number to re-sign only commits NEWER than that one.${RESET}"
read -rp "Choice [Enter = all]: " pick
if [ -n "$pick" ]; then
if ! [[ $pick =~ ^[0-9]+$ ]] || [ "$pick" -lt 1 ] || [ "$pick" -gt "${#lines[@]}" ]; then
echo -e "${RED}✗ Invalid selection.${RESET}"
return 1
fi
base="${hashes[$((pick-1))]}"
fi
echo ""
echo -e "${CYAN}This rewrites the selected commit(s) on '$branch',${RESET}"
echo -e "${CYAN}re-signing each with the key above. Commit hashes will change.${RESET}"
git log --oneline "${base}..HEAD"
echo ""
read -rp "Proceed? (y/n) [n]: " confirm
if [[ $confirm != y && $confirm != Y ]]; then
echo -e "${YELLOW}Cancelled.${RESET}"
return 0
fi
run git rebase --exec "git commit --amend --no-edit -S" "$base"
local status=$?
if [ $status -ne 0 ]; then
echo -e "${RED}✗ Rebase stopped — likely a conflict.${RESET}"
echo -e "${YELLOW} Resolve it, then run: git rebase --continue${RESET}"
echo -e "${YELLOW} Or use 'x) Conflict Resolver' from the main menu.${RESET}"
return 1
fi
echo -e "${GREEN}✓ Rebase complete. New signature status:${RESET}"
git log --pretty=format:" %C(yellow)%h%C(reset) [%G?] %s" "${base}..HEAD"
echo ""
echo -e "${YELLOW}Note: any GitHub review comments anchored to the old commit SHAs${RESET}"
echo -e "${YELLOW}may show as 'outdated' after you push — that's expected.${RESET}\n"
force_push_after_reset
}
# Escape hatch for when default-branch divergence can't be auto-detected
# (no origin remote-tracking ref, or genuinely on/near the default branch):
# falls back to the original scroll-and-type-a-hash flow, scoped to the
# last 20 commits so it's still usable without network access.
_resign_manual_fallback() {
local branch="$1"
echo -e "${CYAN}Recent commits on '$branch' (status → subject):${RESET}"
git log --pretty=format:" %C(yellow)%h%C(reset) [%G?] %s" -20
echo -e "\n"
echo -e "${YELLOW}Find the newest commit that is NOT marked [N] going down from the top —${RESET}"
echo -e "${YELLOW}everything above it (and including any [N] ones) will be re-signed.${RESET}\n"
local base
read -rp "Base commit hash to rebase FROM (last known-good commit, exclusive): " base
if [ -z "$base" ] || ! git cat-file -e "${base}^{commit}" 2>/dev/null; then
echo -e "${RED}✗ Not a valid commit.${RESET}"
return 1
fi
echo ""
echo -e "${CYAN}This rewrites every commit from ${base} to HEAD on '$branch',${RESET}"
echo -e "${CYAN}re-signing each with the currently configured key. Commit hashes will change.${RESET}"
git log --oneline "${base}..HEAD"
echo ""
read -rp "Proceed? (y/n) [n]: " confirm
if [[ $confirm != y && $confirm != Y ]]; then
echo -e "${YELLOW}Cancelled.${RESET}"
return 0
fi
run git rebase --exec "git commit --amend --no-edit -S" "$base"
local status=$?
if [ $status -ne 0 ]; then
echo -e "${RED}✗ Rebase stopped — likely a conflict.${RESET}"
echo -e "${YELLOW} Resolve it, then run: git rebase --continue${RESET}"
echo -e "${YELLOW} Or use 'x) Conflict Resolver' from the main menu.${RESET}"
return 1
fi
echo -e "${GREEN}✓ Rebase complete. New signature status:${RESET}"
git log --pretty=format:" %C(yellow)%h%C(reset) [%G?] %s" "${base}..HEAD"
echo ""
force_push_after_reset
}
# ── Push with upstream auto-set ───────────────────────────────────────────────
smart_push() {
local branch
branch=$(git branch --show-current)
progress_step "Checking upstream" 1 2
local push_out push_status
if $DRY_RUN; then
echo -e "${MAGENTA}[dry-run] git push${RESET}"
return 0
fi
push_out=$(git push 2>&1)
push_status=$?
if [ $push_status -ne 0 ] && echo "$push_out" | grep -q "no upstream"; then
echo -e "${YELLOW}No upstream set. Push and set upstream for '$branch'? (y/n)${RESET}"
read -rp "> " ans
if [[ $ans == y || $ans == Y ]]; then
progress_step "Pushing & setting upstream" 2 2
run_spinner "Push (set-upstream origin $branch)" git push --set-upstream origin "$branch"
fi
elif [ $push_status -ne 0 ]; then
echo -e "${RED}✗ Push failed:${RESET}"
echo "$push_out"
if echo "$push_out" | grep -qi "not found"; then
local remote_url remote_owner gh_active
remote_url=$(git remote get-url origin 2>/dev/null)
remote_owner=$(echo "$remote_url" | sed -E 's#.*[:/]([^/]+)/[^/.]+(\.git)?/?$#\1#')
gh_active=$(gh api user --jq '.login' 2>/dev/null)
echo ""
echo -e "${YELLOW}↷ 'Repository not found' usually means:${RESET}"
echo -e "${YELLOW} 1. The repo name/owner is wrong, or it was renamed/deleted.${RESET}"
echo -e "${YELLOW} 2. It's private and the currently authenticated account can't see it${RESET}"
echo -e "${YELLOW} (GitHub returns this same error for both cases).${RESET}"
if [ -n "$gh_active" ] && [ -n "$remote_owner" ] && [ "$gh_active" != "$remote_owner" ]; then
echo ""
echo -e "${RED} ✗ Likely cause: gh is authenticated as '$gh_active', but the remote${RESET}"
echo -e "${RED} points at owner '$remote_owner' (${remote_url}).${RESET}"
echo -e "${YELLOW} Use 's' from the main menu to switch to '$remote_owner', or check${RESET}"
echo -e "${YELLOW} '9) Manage Remotes' if the URL itself is wrong.${RESET}"
fi
fi
return 1
else
progress_step "Pushed" 2 2
echo -e "${GREEN}✓ Pushed${RESET}"
[ -n "$push_out" ] && echo "$push_out"
fi
}
# ── r) AI-Assisted PR Review ──────────────────────────────────────────────────
ai_pr_review() {
require_gh || return 1
echo -e "${CYAN}${BOLD}AI-Assisted PR Review${RESET}\n"
echo -e "${BLUE}Open PRs:${RESET}"