-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-sync.sh
More file actions
executable file
·2046 lines (1844 loc) · 56.5 KB
/
Copy pathgit-sync.sh
File metadata and controls
executable file
·2046 lines (1844 loc) · 56.5 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
# Copyright (C) 2026 Julien Cochuyt (https://github.com/JulienCochuyt)
# SPDX-License-Identifier: GPL-2.0-only
set -euo pipefail
readonly GIT_SYNC_VERSION='1.2.1-dev'
readonly COLOR_RED=$'\033[31m'
readonly COLOR_GREEN=$'\033[32m'
readonly COLOR_YELLOW=$'\033[33m'
readonly COLOR_BLUE=$'\033[34m'
readonly COLOR_CYAN=$'\033[36m'
readonly COLOR_RESET=$'\033[0m'
# Section color mapping (human-readable mode)
readonly SECTION_COLOR_MISSING="$COLOR_YELLOW"
readonly SECTION_COLOR_NEW="$COLOR_CYAN"
readonly SECTION_COLOR_DIFFERENT="$COLOR_RED"
readonly SECTION_COLOR_BEHIND="$COLOR_YELLOW"
readonly SECTION_COLOR_AHEAD="$COLOR_BLUE"
readonly SECTION_COLOR_DIVERGED="$COLOR_RED"
readonly SECTION_COLOR_UNRELATED="$COLOR_RED"
readonly SECTION_COLOR_UNKNOWN="$COLOR_RED"
readonly SECTION_COLOR_SAME="$COLOR_GREEN"
usage_main() {
cat <<'EOF'
Usage:
git sync <command> [<args>]
Commands:
status Compare branches or tags across remotes or against the working copy.
align Push branches or tags from source to target.
Options:
-h, --help Show this help.
--version Print version.
Configuration:
Defaults can be set via git config. Example:
git config sync.include 'release/*'
git config --add sync.include 'main'
git config sync.exclude 'dependabot/*'
git config sync.align.on-failure abort
git config sync.status.expand 5
git config sync.status.collapse 100
Patterns are resolved in layers: shared config, per-command config,
then CLI. For includes, CLI replaces config unless -i + is passed
to merge. For excludes, CLI merges with config unless -x - is
passed to replace.
For command-specific help:
git sync status --help
git sync align --help
EOF
}
usage_status() {
cat <<'EOF'
Usage:
git sync status [<options>]
git sync status [<options>] @
git sync status [<options>] [@]<remote>
git sync status [<options>] <remote> @
git sync status [<options>] [@]<remote> [@]<remote>
With no remote, uses the upstream of the current branch, or the
sole configured remote.
When one remote is given, compares local branches/tags against it.
When two remotes are given, compares them against each other.
By default, reads local tracking refs (refs/remotes/<remote>/*).
Prefix a remote with @ to query it live via git ls-remote instead.
For tags (-t), remotes are always queried via ls-remote.
Bare @ (without a remote name) resolves the default remote and
compares its local tracking refs against its live state — a quick
pre-fetch check. With two remotes, bare @ inherits the other
remote's name. Not supported with --tags.
Options:
-p, --porcelain Machine-readable output.
--name-only Output only branch/tag names (one per line).
-t, --tags Compare tags instead of branches.
-a, --annotated With --tags, show only annotated tags.
-A, --lightweight With --tags, show only lightweight tags.
-s, --subset <category[,category...]>
Restrict output to selected categories.
Categories: new, missing, different, behind,
ahead, diverged, unrelated, unknown, same.
Prefix with + to add to or - to remove from the
default set (e.g. --subset +same, --subset -new).
Plain entries replace the defaults entirely.
Availability depends on which sides are local:
Both local: behind, ahead, diverged,
unrelated, unknown (not different).
Local + @remote: behind or ahead (depending on which
side is local) and different.
Both @remote: different only.
--tags: different only.
new, missing, and same are always available.
-i, --include <pattern>
Include branches/tags matching a shell glob pattern.
Replaces config includes. Use -i + to merge with them.
Repeatable.
-I, --include-from <file>
Include glob patterns listed in <file> (one per line).
-x, --exclude <pattern>
Exclude branches/tags matching a shell glob pattern.
Merges with config excludes. Use -x - to replace them.
Use -x + to re-assert all excludes after includes.
Repeatable.
-X, --exclude-from <file>
Exclude glob patterns listed in <file> (one per line).
-h, --help Show this help.
Examples:
git sync status
git sync status @
git sync status origin
git sync status origin @
git sync status origin upstream
git sync status -t origin
git sync status -t origin upstream
git sync status -i 'release/*' -x 'release/tmp-*' origin upstream
EOF
}
usage_align() {
cat <<'EOF'
Usage:
git sync align [<options>] <source> <target>
Options:
-n, --dry-run Show actions without pushing.
-t, --tags Align tags instead of branches.
-a, --annotated With --tags, process only annotated tags.
-A, --lightweight With --tags, process only lightweight tags.
--on-failure <strategy>
Failure strategy: continue, fail-fast, interactive.
Default: interactive.
-f, --force Use --force for push attempts.
-F, --force-with-lease
Use --force-with-lease for push attempts.
-v, --verbose Print git commands as they are executed.
-y, --yes Skip interactive confirmation before deleting
refs (category new).
-s, --subset <category[,category...]>
Restrict processing to selected categories.
Prefix with + to add to or - to remove from the
default set (e.g. --subset +new, --subset -missing).
Plain entries replace the defaults entirely.
Common categories: new, missing.
Branches only: behind, ahead, diverged, unrelated, unknown.
Tags only: different.
-i, --include <pattern>
Include branches/tags matching a shell glob pattern.
Replaces config includes. Use -i + to merge with them.
Repeatable.
-I, --include-from <file>
Include glob patterns listed in <file> (one per line).
-x, --exclude <pattern>
Exclude branches/tags matching a shell glob pattern.
Merges with config excludes. Use -x - to replace them.
Use -x + to re-assert all excludes after includes.
Repeatable.
-X, --exclude-from <file>
Exclude glob patterns listed in <file> (one per line).
-h, --help Show this help.
Arguments:
<source> and <target> are remote names (e.g. origin, upstream).
For branches, local tracking refs are used for comparison;
pushes and deletions always target the real remote.
For tags, remotes are queried live via git ls-remote.
Examples:
git sync align origin upstream
git sync align --dry-run --subset missing,behind origin upstream
git sync align -t origin upstream
git sync align --on-failure interactive --force-with-lease origin upstream
EOF
}
# Short hint printed on usage errors instead of the full usage text.
usage_hint() {
printf 'Use "%s --help" for detailed usage.\n' "$1" >&2
}
usage_hint_status() { usage_hint 'status'; }
usage_hint_align() { usage_hint 'align'; }
sort_lines() {
if (($# == 0)); then
return
fi
printf '%s\n' "$@" | LC_ALL=C sort
}
# Determine if a category should be shown in detail.
# Args: $1 = normally_collapsed (0 or 1), $2 = count,
# $3 = expand threshold, $4 = collapse threshold
should_show_details() {
local normally_collapsed=$1 count=$2 expand=$3 collapse=$4
if ((normally_collapsed == 1)); then
((count <= expand))
return
fi
if ((collapse > 0 && count >= collapse)); then
return 1
fi
return 0
}
print_colored_line() {
local prefix="$1"
local color="$2"
local text="$3"
if [[ -t 1 ]]; then
printf '%s%b%s%b\n' "$prefix" "$color" "$text" "$COLOR_RESET"
else
printf '%s%s\n' "$prefix" "$text"
fi
}
print_section() {
local title="$1"
local color="$2"
shift 2
local count=$#
printf '%s (%d)\n' "$title" "$count"
if (($# == 0)); then
print_colored_line ' ' "$color" '(none)'
return
fi
local ref
for ref in "$@"; do
print_colored_line ' ' "$color" "$ref"
done
}
# Format ref names with commit count annotations for directional categories.
# For behind: "ref (N commits)"
# For ahead: "ref (N commits)"
# For diverged: "ref (N behind, M ahead)"
format_refs_with_counts() {
local category="$1"
local -n frc_behind_map="$2"
local -n frc_ahead_map="$3"
shift 3
local ref b a
for ref in "$@"; do
b="${frc_behind_map[$ref]:--}"
a="${frc_ahead_map[$ref]:--}"
case "$category" in
behind)
if [[ "$b" != '-' ]]; then
printf '%s (%s commits)\n' "$ref" "$b"
else
printf '%s\n' "$ref"
fi
;;
ahead)
if [[ "$a" != '-' ]]; then
printf '%s (%s commits)\n' "$ref" "$a"
else
printf '%s\n' "$ref"
fi
;;
diverged)
if [[ "$b" != '-' && "$a" != '-' ]]; then
printf '%s (%s behind, %s ahead)\n' "$ref" "$b" "$a"
else
printf '%s\n' "$ref"
fi
;;
esac
done
}
# Output: <category>\t<ref>\t<source_hash>\t<target_hash>\t<behind_count>\t<ahead_count>
# Unavailable fields use "-" as sentinel.
print_porcelain_refs() {
local category="$1"
local refs_str="$2"
local -n pr_src_map="$3"
local -n pr_tgt_map="$4"
local -n pr_behind_counts="$5"
local -n pr_ahead_counts="$6"
[[ -n "$refs_str" ]] || return 0
local -a pr_refs=()
mapfile -t pr_refs <<< "$refs_str"
local -a sorted=()
local ref
mapfile -t sorted < <(sort_lines "${pr_refs[@]}")
for ref in "${sorted[@]}"; do
printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$category" "$ref" \
"${pr_src_map[$ref]:--}" "${pr_tgt_map[$ref]:--}" \
"${pr_behind_counts[$ref]:--}" "${pr_ahead_counts[$ref]:--}"
done
}
# Classify how target (hash_b) relates to source (hash_a):
# behind = target is ancestor of source (fast-forwardable)
# ahead = source is ancestor of target
# diverged = neither is ancestor; commits share a common ancestor
# unrelated = neither is ancestor; commits share NO common ancestor
# unknown = ancestry inconclusive (local repo is shallow and at
# least one tip's walk hits the shallow boundary)
# Modes:
# full — both sides local; behind/ahead/diverged/unrelated/unknown all reliable.
# ahead-only — B is local; only ahead is reliably detectable.
# behind-only — A is local; only behind is reliably detectable.
is_interactive_tty() {
[[ -t 0 ]]
}
classify_direction_relation() {
local hash_a="$1"
local hash_b="$2"
local mode="${3:-full}"
case "$mode" in
ahead-only)
# B is local — "ahead" (A ancestor of B) is always detectable
# because A's hash must be in B's local ancestry if true.
if git merge-base --is-ancestor "$hash_a" "$hash_b" >/dev/null 2>&1; then
printf 'ahead\n'
else
printf 'different\n'
fi
;;
behind-only)
# A is local — "behind" (B ancestor of A) is always detectable
# because B's hash must be in A's local ancestry if true.
if git merge-base --is-ancestor "$hash_b" "$hash_a" >/dev/null 2>&1; then
printf 'behind\n'
else
printf 'different\n'
fi
;;
*)
# full: both sides local — all categories available.
# Use a single merge-base call: capture the ancestor hash and
# distinguish behind/ahead/diverged/unrelated from one result.
# When both hashes are equal mb equals both sides; prefer
# `behind` for self-comparison to match the prior `--is-ancestor`
# semantics (the legacy code tested B-ancestor-of-A first).
local mb
if mb=$(git merge-base "$hash_a" "$hash_b" 2>/dev/null); then
if [[ "$mb" == "$hash_b" ]]; then
printf 'behind\n'
elif [[ "$mb" == "$hash_a" ]]; then
printf 'ahead\n'
else
printf 'diverged\n'
fi
else
# No common ancestor reachable. Two possibilities:
# - histories are genuinely disjoint (→ unrelated)
# - the local repo is shallow and the would-be common
# ancestor lies below the shallow boundary (→ unknown)
#
# We cannot reliably distinguish "truly disjoint" from
# "merge-base hidden by depth" inside a shallow clone:
# `.git/shallow` is rewritten by each fetch and may not
# list every boundary, so per-tip root-walking is
# unreliable. Take the conservative path: any merge-base
# failure inside a shallow repo is reported as `unknown`
# (ancestry inconclusive). The user can re-run after
# `git fetch --unshallow` to get a definitive answer.
if git rev-parse --is-shallow-repository 2>/dev/null \
| grep -qx 'true'; then
printf 'unknown\n'
else
printf 'unrelated\n'
fi
fi
;;
esac
}
load_remote_heads() {
local remote="$1"
local -n out_map="$2"
local hash ref branch
while IFS=$'\t' read -r hash ref; do
[[ -z "$hash" || -z "$ref" ]] && continue
branch="${ref#refs/heads/}"
[[ "$branch" == "$ref" ]] && continue
out_map["$branch"]="$hash"
done < <(git ls-remote "$remote" 'refs/heads/*')
}
load_local_heads() {
local remote="$1"
local -n out_map="$2"
local hash ref branch
while IFS=$'\t' read -r hash ref; do
[[ -z "$hash" || -z "$ref" ]] && continue
branch="${ref#refs/remotes/${remote}/}"
[[ "$branch" == "$ref" ]] && continue
[[ "$branch" == "HEAD" ]] && continue
out_map["$branch"]="$hash"
done < <(git for-each-ref --format='%(objectname)%09%(refname)' "refs/remotes/${remote}")
}
load_worktree_heads() {
local -n out_map="$1"
local hash ref branch
while IFS=$'\t' read -r hash ref; do
[[ -z "$hash" || -z "$ref" ]] && continue
branch="${ref#refs/heads/}"
[[ "$branch" == "$ref" ]] && continue
out_map["$branch"]="$hash"
done < <(git for-each-ref --format='%(objectname)%09%(refname)' refs/heads)
}
# Resolve the default remote for the current branch.
# Tries: 1) upstream remote of current branch, 2) sole configured remote.
# Prints the remote name to stdout. Returns 1 if unable to resolve.
resolve_default_remote() {
local branch
branch="$(git symbolic-ref --short HEAD 2>/dev/null)" || true
if [[ -n "$branch" ]]; then
local upstream_remote
upstream_remote="$(git config --get "branch.${branch}.remote" 2>/dev/null)" || true
if [[ -n "$upstream_remote" ]]; then
printf '%s\n' "$upstream_remote"
return 0
fi
fi
local -a remotes
mapfile -t remotes < <(git remote)
if ((${#remotes[@]} == 1)); then
printf '%s\n' "${remotes[0]}"
return 0
fi
return 1
}
# ls-remote lists annotated tags twice: the tag object and the peeled (^{}) commit.
# We prefer the peeled hash so comparisons use the underlying commit.
# $3 = tag_type filter: 0=all, 1=annotated only, 2=lightweight only.
load_remote_tags() {
local remote="$1"
local -n out_map="$2"
local tag_type="${3:-0}"
local -A _annotated_set=()
local hash ref tag_name base_name
while IFS=$'\t' read -r hash ref; do
[[ -z "$hash" || -z "$ref" ]] && continue
if [[ "$ref" == refs/tags/*^{} ]]; then
base_name="${ref#refs/tags/}"
base_name="${base_name%^\{\}}"
_annotated_set["$base_name"]=1
out_map["$base_name"]="$hash"
continue
fi
tag_name="${ref#refs/tags/}"
[[ "$tag_name" == "$ref" ]] && continue
if [[ -z "${out_map[$tag_name]+x}" ]]; then
out_map["$tag_name"]="$hash"
fi
done < <(git ls-remote "$remote" 'refs/tags/*')
# Apply tag type filter.
if ((tag_type != 0)); then
for tag_name in "${!out_map[@]}"; do
if ((tag_type == 1)) && [[ -z "${_annotated_set[$tag_name]+x}" ]]; then
unset 'out_map[$tag_name]'
elif ((tag_type == 2)) && [[ -n "${_annotated_set[$tag_name]+x}" ]]; then
unset 'out_map[$tag_name]'
fi
done
fi
}
# %(*objectname) is the peeled hash for annotated tags, empty for lightweight.
# Uses pipe delimiter (not tab) so empty %(*objectname) produces a real empty
# field — consecutive IFS whitespace characters are folded by bash read.
# $2 = tag_type filter: 0=all, 1=annotated only, 2=lightweight only.
load_local_tags() {
local -n out_map="$1"
local tag_type="${2:-0}"
local object_hash peeled_hash ref tag_name selected_hash
while IFS='|' read -r object_hash peeled_hash ref; do
[[ -z "$object_hash" || -z "$ref" ]] && continue
tag_name="${ref#refs/tags/}"
[[ "$tag_name" == "$ref" ]] && continue
# Filter by tag type.
if ((tag_type == 1)) && [[ -z "$peeled_hash" ]]; then
continue # want annotated only, skip lightweight
fi
if ((tag_type == 2)) && [[ -n "$peeled_hash" ]]; then
continue # want lightweight only, skip annotated
fi
selected_hash="$object_hash"
if [[ -n "$peeled_hash" ]]; then
selected_hash="$peeled_hash"
fi
out_map["$tag_name"]="$selected_hash"
done < <(git for-each-ref --format='%(objectname)|%(*objectname)|%(refname)' refs/tags)
}
parse_remote_ref() {
local input_ref="$1"
local -n out_name="$2"
local -n out_source="$3"
local usage_fn="${4:-usage_hint_status}"
if [[ "$input_ref" == @* ]]; then
out_source='remote'
out_name="${input_ref#@}"
else
out_source='local'
out_name="$input_ref"
fi
if [[ -z "$out_name" ]]; then
printf 'Invalid remote ref: %s\n\n' "$input_ref" >&2
"$usage_fn"
exit 1
fi
}
load_pattern_file() {
local file_path="$1"
local -n out_patterns="$2"
local usage_fn="${3:-usage_hint_status}"
if [[ ! -r "$file_path" ]]; then
printf 'Cannot read pattern file: %s\n\n' "$file_path" >&2
"$usage_fn"
exit 1
fi
local line
# Handle any line ending: LF (Unix), CRLF (Windows), CR (old Mac).
# tr normalises CR-only and CRLF to plain LF before read processes it.
while IFS= read -r line || [[ -n "$line" ]]; do
[[ -z "$line" ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
out_patterns+=("$line")
done < <(tr '\r' '\n' < "$file_path" | cat -s)
}
# Load a multi-value git config key into an array.
# Returns 0 if any values found, 1 if key is unset.
load_config_multi() {
local key="$1"
local -n _cm_ref="$2"
local -a _cm_vals=()
if mapfile -t _cm_vals < <(git config --get-all "$key" 2>/dev/null) \
&& (("${#_cm_vals[@]}" > 0)) && [[ -n "${_cm_vals[0]}" ]]; then
_cm_ref+=("${_cm_vals[@]}")
return 0
fi
return 1
}
# Load a single-value git config key.
# Returns 0 if found, 1 if unset. Value printed to stdout.
load_config_scalar() {
git config --get "$1" 2>/dev/null
}
# Load a multi-value git config key into a newline-delimited string
# at a specific index of an indexed array.
load_config_multi_joined() {
local key="$1"
local -n _cmj_ref="$2"
local idx="$3"
local -a _cmj_vals=()
if load_config_multi "$key" _cmj_vals; then
_cmj_ref[$idx]="$(printf '%s\n' "${_cmj_vals[@]}")"
return 0
fi
return 1
}
# Pass 1: resolve layered include/exclude modifiers in place.
# Takes three indexed array namerefs (each with 3 entries, index = layer):
# $1 = inc_layers — newline-delimited include patterns per layer
# $2 = exc_layers — newline-delimited exclude patterns per layer
# $3 = re_exclude — output: 0 or 1 per layer (re-exclusion flag)
# Strips +/- modifier tokens. Clears earlier layers per merge/replace
# semantics. Sets re_exclude[i]=1 when "+" appears in exc_layers[i].
resolve_patterns() {
local -n _rp_inc="$1"
local -n _rp_exc="$2"
local -n _rp_re="$3"
local i j
for i in 0 1 2; do
# --- Includes ---
if [[ -n "${_rp_inc[$i]}" ]]; then
local _has_merge=0
local _new_inc=''
local _pat
while IFS= read -r _pat; do
[[ -z "$_pat" ]] && continue
if [[ "$_pat" == '+' ]]; then
_has_merge=1
else
_new_inc+="$_pat"$'\n'
fi
done <<< "${_rp_inc[$i]}"
_new_inc="${_new_inc%$'\n'}"
if ((!_has_merge)); then
for ((j = 0; j < i; j++)); do
_rp_inc[$j]=''
done
fi
_rp_inc[$i]="$_new_inc"
fi
# --- Excludes ---
if [[ -n "${_rp_exc[$i]}" ]]; then
local _has_replace=0
local _has_reassert=0
local _new_exc=''
local _pat
while IFS= read -r _pat; do
[[ -z "$_pat" ]] && continue
if [[ "$_pat" == '-' ]]; then
_has_replace=1
elif [[ "$_pat" == '+' ]]; then
_has_reassert=1
else
_new_exc+="$_pat"$'\n'
fi
done <<< "${_rp_exc[$i]}"
_new_exc="${_new_exc%$'\n'}"
if ((_has_replace)); then
for ((j = 0; j < i; j++)); do
_rp_exc[$j]=''
done
fi
_rp_re[$i]="$_has_reassert"
_rp_exc[$i]="$_new_exc"
fi
done
}
# Pass 2 per-ref: is this ref accepted by the resolved layers?
# Returns 0 (accepted) or 1 (rejected).
ref_is_accepted() {
local ref="$1"
local -n _ra_inc="$2"
local -n _ra_exc="$3"
local -n _ra_re="$4"
# has_any_include: true if any layer has non-empty includes
local has_inc=0
local i
for i in 0 1 2; do
if [[ -n "${_ra_inc[$i]}" ]]; then has_inc=1; break; fi
done
local accepted=$((1 - has_inc)) # all refs if no includes, else empty
for i in 0 1 2; do
# Step 1: this layer's excludes remove from accepted
if ((accepted)) && [[ -n "${_ra_exc[$i]}" ]]; then
local _pat
while IFS= read -r _pat; do
[[ -n "$_pat" ]] && [[ "$ref" == $_pat ]] && { accepted=0; break; }
done <<< "${_ra_exc[$i]}"
fi
# Steps 2-3: layer includes (pick from full set, minus own excludes)
local layer_match=0
if [[ -n "${_ra_inc[$i]}" ]]; then
local _pat
while IFS= read -r _pat; do
[[ -n "$_pat" ]] && [[ "$ref" == $_pat ]] && { layer_match=1; break; }
done <<< "${_ra_inc[$i]}"
if ((layer_match)) && [[ -n "${_ra_exc[$i]}" ]]; then
while IFS= read -r _pat; do
[[ -n "$_pat" ]] && [[ "$ref" == $_pat ]] && { layer_match=0; break; }
done <<< "${_ra_exc[$i]}"
fi
fi
# Step 4: re-exclusion — check all previous layers' excludes
if ((layer_match && _ra_re[i])); then
local j
for ((j = 0; j < i; j++)); do
[[ -z "${_ra_exc[$j]}" ]] && continue
while IFS= read -r _pat; do
[[ -n "$_pat" ]] && [[ "$ref" == $_pat ]] && { layer_match=0; break 2; }
done <<< "${_ra_exc[$j]}"
done
fi
# Step 5: layer match adds to accepted
((layer_match)) && accepted=1
done
return $((1 - accepted))
}
load_ref_set() {
local ref_mode="$1"
local ref="$2"
local tags_mode="$3"
local -n target_map="$4"
local tag_type="${5:-0}"
if ((tags_mode == 1)); then
if [[ "$ref_mode" == 'remote' ]]; then
load_remote_tags "$ref" target_map "$tag_type"
else
load_local_tags target_map "$tag_type"
fi
else
if [[ "$ref_mode" == 'remote' ]]; then
load_remote_heads "$ref" target_map
elif [[ "$ref_mode" == 'worktree' ]]; then
load_worktree_heads target_map
else
load_local_heads "$ref" target_map
fi
fi
}
compute_ref_categories() {
local -n source_map_ref="$1"
local -n target_map_ref="$2"
local direction_mode="$3"
local -n inc_layers_ref="$4"
local -n exc_layers_ref="$5"
local -n re_exclude_ref="$6"
local -n refs_by_cat_ref="$7"
local -n behind_count_map_ref="$8"
local -n ahead_count_map_ref="$9"
# Initialize all category keys to empty.
local _cat
for _cat in missing new different behind ahead diverged unrelated unknown same; do
refs_by_cat_ref[$_cat]=''
done
local ref
for ref in "${!source_map_ref[@]}"; do
if ! ref_is_accepted "$ref" inc_layers_ref exc_layers_ref re_exclude_ref; then
continue
fi
if [[ -z "${target_map_ref[$ref]+x}" ]]; then
refs_by_cat_ref[missing]+="$ref"$'\n'
elif [[ "${source_map_ref[$ref]}" == "${target_map_ref[$ref]}" ]]; then
refs_by_cat_ref[same]+="$ref"$'\n'
else
if [[ "$direction_mode" == 'none' ]]; then
refs_by_cat_ref[different]+="$ref"$'\n'
else
local _dir _left _right
_dir="$(classify_direction_relation "${source_map_ref[$ref]}" "${target_map_ref[$ref]}" "$direction_mode")"
case "$_dir" in
behind|ahead|diverged)
read -r _left _right < <(git rev-list --count --left-right "${source_map_ref[$ref]}...${target_map_ref[$ref]}" 2>/dev/null) || { _left='-'; _right='-'; }
behind_count_map_ref["$ref"]="$_left"
ahead_count_map_ref["$ref"]="$_right"
;;&
behind)
refs_by_cat_ref[behind]+="$ref"$'\n'
;;
ahead)
refs_by_cat_ref[ahead]+="$ref"$'\n'
;;
different)
refs_by_cat_ref[different]+="$ref"$'\n'
;;
unrelated)
# Counts are meaningless without a common ancestor;
# leave behind/ahead maps unset so output renders "-".
refs_by_cat_ref[unrelated]+="$ref"$'\n'
;;
unknown)
# Counts are inconclusive (shallow boundary cuts off
# the walk); leave behind/ahead maps unset so output
# renders "-".
refs_by_cat_ref[unknown]+="$ref"$'\n'
;;
*)
refs_by_cat_ref[diverged]+="$ref"$'\n'
;;
esac
fi
fi
done
for ref in "${!target_map_ref[@]}"; do
if ! ref_is_accepted "$ref" inc_layers_ref exc_layers_ref re_exclude_ref; then
continue
fi
if [[ -z "${source_map_ref[$ref]+x}" ]]; then
refs_by_cat_ref[new]+="$ref"$'\n'
fi
done
# Strip trailing newlines.
for _cat in missing new different behind ahead diverged unrelated unknown same; do
refs_by_cat_ref[$_cat]="${refs_by_cat_ref[$_cat]%$'\n'}"
done
}
apply_subset_filters() {
local -n subset_filters_ref="$1"
local -n refs_by_cat_ref="$2"
if ((${#subset_filters_ref[@]} == 0)); then
return
fi
local _cat
for _cat in missing new different behind ahead diverged unrelated unknown same; do
[[ -n "${subset_filters_ref[$_cat]+x}" ]] || refs_by_cat_ref[$_cat]=''
done
}
normalize_subset_category() {
local lower="${1,,}"
case "$lower" in
new|missing|different|same|behind|ahead|diverged|unrelated|unknown)
printf '%s\n' "$lower"
;;
*)
return 1
;;
esac
}
# Strip leading and trailing whitespace using parameter expansion.
trim_spaces() {
local value="$1"
value="${value#"${value%%[![:space:]]*}"}"
value="${value%"${value##*[![:space:]]}"}"
printf '%s\n' "$value"
}
add_subset_categories_or_exit() {
local raw_value="$1"
local -n out_plain="$2"
local -n out_add="$3"
local -n out_remove="$4"
local usage_fn="${5:-usage_hint_status}"
local -a parts=()
local part trimmed normalized prefix
IFS=',' read -r -a parts <<< "$raw_value"
for part in "${parts[@]}"; do
trimmed="$(trim_spaces "$part")"
if [[ -z "$trimmed" ]]; then
printf 'Option --subset contains an empty category.\n\n' >&2
"$usage_fn"
exit 1
fi
prefix=''
if [[ "$trimmed" == +* ]]; then
prefix='+'
trimmed="${trimmed:1}"
elif [[ "$trimmed" == -* ]]; then
prefix='-'
trimmed="${trimmed:1}"
fi
if [[ -z "$trimmed" ]]; then
printf 'Option --subset contains an empty category after prefix.\n\n' >&2
"$usage_fn"
exit 1
fi
if ! normalized="$(normalize_subset_category "$trimmed")"; then
printf 'Invalid category: %s\n\n' "$trimmed" >&2
"$usage_fn"
exit 1
fi
case "$prefix" in
'+') out_add["$normalized"]=1 ;;
'-') out_remove["$normalized"]=1 ;;
*) out_plain["$normalized"]=1 ;;
esac
done
}
# Resolve the final subset_filters map from parsed --subset entries.
# 1. If plain entries exist, start from those.
# 2. Otherwise, start from the default set.
# 3. Add + entries.
# 4. Remove - entries.
resolve_subset_filters() {
local -n rs_plain="$1"
local -n rs_add="$2"
local -n rs_remove="$3"
local -n rs_defaults="$4"
local -n rs_out="$5"
# Start from plain entries if any, otherwise from defaults.
if ((${#rs_plain[@]} > 0)); then
local cat
for cat in "${!rs_plain[@]}"; do
rs_out["$cat"]=1
done
else
local cat
for cat in "${!rs_defaults[@]}"; do
rs_out["$cat"]=1
done
fi
# Apply additions.
local cat
for cat in "${!rs_add[@]}"; do
rs_out["$cat"]=1
done
# Apply removals.
local cat
for cat in "${!rs_remove[@]}"; do
unset 'rs_out[$cat]'
done
}
status_print_name_only() {
local refs_str="$1"
[[ -n "$refs_str" ]] || return 0
local -a refs=()
mapfile -t refs <<< "$refs_str"
local -a sorted=()
mapfile -t sorted < <(sort_lines "${refs[@]}")
printf '%s\n' "${sorted[@]}"
}
status_command() {
local porcelain=0
local direction_mode='none'
local tags_mode=0
local tag_type=0
local name_only=0
local -a included_patterns=()
local -a excluded_patterns=()
local -A subset_plain=()
local -A subset_add=()
local -A subset_remove=()
local -A subset_filters=()
local -a _positional_args=()
while (($# > 0)); do
# Expand combined short options (e.g., -ts → -t -s)
if [[ "$1" =~ ^-[a-zA-Z]{2,}$ ]]; then
local _combined="$1"
shift
local _k
for ((_k = ${#_combined} - 1; _k >= 1; _k--)); do
set -- "-${_combined:_k:1}" "$@"
done
fi
case "$1" in
-p|--porcelain)
porcelain=1
shift
;;
-t|--tags)