-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfzf-git-branches.sh
executable file
·2114 lines (1905 loc) · 87.7 KB
/
fzf-git-branches.sh
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
# Description: Manage Git branches and worktrees with fzf
command -v fzf >/dev/null 2>&1 || return
fgb() {
local VERSION="0.16.0"
# Set the command to use for fzf
local fzf_version
fzf_version="$(fzf --version | awk -F. '{ print $1 * 1e6 + $2 * 1e3 + $3 }')"
local fzf_min_version=16001
local FZF_ARGS_GLOB="\
--ansi \
--bind=ctrl-y:accept,ctrl-t:toggle+down \
--border=top \
--cycle \
--multi \
--pointer='' \
--preview 'FGB_BRANCH={1}; \
git log --oneline --decorate --graph --color=always \${FGB_BRANCH:1:-1}' \
"
FZF_ARGS_GLOB="${FGB_FZF_OPTS:-"$FZF_ARGS_GLOB"}"
local FZF_CMD_GLOB
if [[ $fzf_version -gt $fzf_min_version ]]; then
FZF_CMD_GLOB="fzf --height 80% --reverse $FZF_ARGS_GLOB"
elif [[ ${FZF_TMUX:-1} -eq 1 ]]; then
FZF_CMD_GLOB="fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}"
else
FZF_CMD_GLOB="fzf $FZF_ARGS_GLOB"
fi
__fgb__functions() {
__fgb_confirmation_dialog() {
# Confirmation dialog with a single 'y' character to accept
local user_prompt="${1:-Are you sure?}"
echo -en "$user_prompt (y|N): "
local ANS
if [[ -n "${ZSH_VERSION-}" ]]; then
read -rk 1 ANS
else
read -rn 1 ANS
fi
echo # Move to the next line for a cleaner output
case "$ANS" in
[yY]) return 0 ;;
*) return 1 ;;
esac
}
__fgb_stdout_unindented() {
# Print a string to stdout unindented
# Usage: $0 "string"
# String supposed to be indented with any number of any characters.
# The first `|' character in the string will be treated as the start of the string.
# The first and last lines of the string will be removed because they must be empty and
# exist since a quoted literal starts with a new line after the opening quote and ends
# with a new line before the closing quote, like this:
# string="
# |line 1
# |line 2
# "
# source: https://unix.stackexchange.com/a/674903/424165
# Concatenate lines that end with \# (backslash followed by a hash character) and then
# remove indentation
sed '1d;s/^[^|]*|//;$d' <<< "$(sed -z 's/\\#\n[^|]*|//g' <<< "$1")"
}
__fgb_git_branch_delete() {
# Delete a Git branch
if [[ -z "$1" ]]; then
echo "$0: Missing argument: list of branches to delete" >&2
return 1
fi
local \
branch \
branch_name \
branches_to_delete="$1" \
error_pattern \
is_remote \
local_branches \
local_tracking \
output \
remote_name \
remote_tracking \
return_code \
upstream \
user_prompt \
line
local -a array_of_lines
while IFS= read -r line; do
array_of_lines+=( "$line" )
done <<< "$branches_to_delete"
for branch_name in "${array_of_lines[@]}"; do
branch=""
is_remote=false
local_branches=""
local_tracking=""
output=""
remote_name=""
remote_tracking=""
upstream=""
# shellcheck disable=SC2053
if [[ "$branch_name" == "$c_bracket_rem_open"*/*"$c_bracket_rem_close" ]]; then
is_remote=true
# Remove the first and the last characters (brackets)
branch_name="${branch_name:1}"; branch_name="${branch_name%?}"
# Remove everything after the first slash
remote_name="${branch_name%%/*}"
# Remove the first segment of the reference name (<upstream>/)
branch_name="${branch_name#*/}"
elif [[ "$branch_name" == "$c_bracket_loc_open"*"$c_bracket_loc_close" ]]; then
# Remove the first and the last characters (brackets)
branch_name="${branch_name:1}"; branch_name="${branch_name%?}"
else
echo "error: invalid branch name pattern: $branch_name" >&2
return 1
fi
if [[ "$c_extend_del" == true ]]; then
if [[ "$is_remote" == true ]]; then
# Find local branch that tracks the selected remote branch
local_branches="$(__fgb_git_branch_list "local")"
return_code=$?; [[ $return_code -ne 0 ]] && return "$return_code"
remote_tracking="refs/remotes/${branch_name}"
while IFS= read -r branch; do
upstream="$(
git \
for-each-ref \
--format \
'%(upstream)' "$branch"
)"
if [[ "$remote_tracking" == "$upstream" ]]; then
local_tracking="$branch"
break
fi
done <<< "$(cut -d: -f1 <<< "$local_branches")"
else
# Find upstream branch for the selected local branch
local_tracking="$branch_name"
remote_tracking="$(
git for-each-ref --format '%(upstream)' "refs/heads/$branch_name"
)"
fi
fi
if [[ "$is_remote" == true ]]; then
branch_name="${branch_name#remotes/*/}"
user_prompt=$(__fgb_stdout_unindented "
|${col_r_bold}WARNING:${col_reset} \#
|Delete branch: '${col_b_bold}${branch_name}${col_reset}' \#
|from remote: ${col_y_bold}${remote_name}${col_reset}?
")
# NOTE: Avoid --force here as it's no undoable operation for remote branches
if __fgb_confirmation_dialog "$user_prompt"; then
git push --delete "$remote_name" "$branch_name" || return $?
if [[ "$c_extend_del" == true ]]; then
if [[ -n "$local_tracking" ]]; then
branch="$c_bracket_loc_open"
branch+="${local_tracking#refs/heads/}"
branch+="$c_bracket_loc_close"
__fgb_git_branch_delete "$branch"
fi
fi
fi
else
user_prompt=$(__fgb_stdout_unindented "
|${col_r_bold}Delete${col_reset} \#
|local branch: \`${col_b_bold}${branch_name}${col_reset}'?
")
if [[ "$c_force" == true ]] || __fgb_confirmation_dialog "$user_prompt"; then
if ! output="$(git branch -d "$branch_name" 2>&1)"; then
local head_branch; head_branch="$(git rev-parse --abbrev-ref HEAD)"
error_pattern="^error: the branch '$branch_name' is not fully merged\.\?$"
if ! grep -q "$error_pattern" <<< "$output"; then
echo "$output"
continue
fi
user_prompt=$(__fgb_stdout_unindented "
|
|${col_r_bold}WARNING:${col_reset} \#
|The branch '${col_b_bold}${branch_name}${col_reset}' \#
|is not yet merged into the \#
|'${col_g_bold}${head_branch}${col_reset}' branch.
|
|Are you sure you want to delete it?
")
# NOTE: Avoid --force here
# as it's not clear if intended for non-merged branches
if __fgb_confirmation_dialog "$user_prompt"; then
git branch -D "$branch_name" || return $?
fi
else
echo "$output"
if [[ "$c_extend_del" == true ]]; then
if [[ -n "$remote_tracking" ]]; then
branch="$c_bracket_rem_open"
branch+="${remote_tracking#refs/remotes/}"
branch+="$c_bracket_rem_close"
__fgb_git_branch_delete "$branch"
fi
fi
fi
fi
fi
done
}
__fgb_git_branch_list() {
# List branches in a git repository
# shellcheck disable=SC2076
if [[ $# -lt 1 ]]; then
echo "$0 error: missing argument: branch_type (local|remote|all)" >&2
return 1
elif [[ ! " local remote all " =~ " $1 " ]]; then
echo "$0 error: invalid argument: \`$1'" >&2
return 1
fi
local branch_type="$1"
local filter_list="${2-}"
local -a ref_types=()
[[ "$branch_type" == "local" ]] && ref_types=("heads")
[[ "$branch_type" == "remote" ]] && ref_types=("remotes")
[[ "$branch_type" == "all" ]] && ref_types=("heads" "remotes")
local ref_type refs return_code git_cmd line
git_cmd="git for-each-ref "
git_cmd+="--format=\"$(\
printf '%%(refname)%b%s%b%s' \
"$c_split_char" \
"$c_author_format" \
"$c_split_char" \
"$c_date_format"
)\" "
while IFS= read -r line; do
git_cmd+="--sort=\"$line\" "
done < <(tr ',' '\n' <<< "$c_branch_sort_order")
for ref_type in "${ref_types[@]}"; do
refs=$(eval "$git_cmd refs/$ref_type")
return_code=$?; [[ $return_code -ne 0 ]] && return "$return_code"
if [[ -n "$filter_list" ]]; then
echo "$refs" | grep "$(
sed "s/^/^/; s/$/$(printf "%b" "$c_split_char")/" <<< "$filter_list"
)"
else
echo "$refs"
fi
done
}
__fgb_branch_set_vars() {
# Define branch related variables
if [ $# -ne 1 ]; then
echo "error: missing argument: branch list" >&2
return 41
fi
local branch_list="$1"
local \
line \
branch \
branch_name \
branch_curr_width \
author_name \
author_curr_width \
date_curr_width
while IFS= read -r line; do
# Remove the longest suffix starting with unit delimeter char
branch="${line%%"$c_split_char"*}"
branch_name="$branch"
# Remove first two segments of the reference name
branch_name="${branch_name#*/}"
branch_name="${branch_name#*/}"
# Remove the shortest prefix ending with unit delimeter char
author_name="${line#*"$c_split_char"}"
# Remove the shortest suffix starting with unit delimeter char
author_name="${author_name%"$c_split_char"*}"
c_branch_author_map["$branch"]="$author_name"
# Remove the longest prefix ending with unit delimeter char
c_branch_date_map["$branch"]="${line##*"$c_split_char"}"
date_curr_width="${#c_branch_date_map["$branch"]}"
c_date_width="$((
date_curr_width > c_date_width ?
date_curr_width :
c_date_width
))"
# Calculate column widths
branch_curr_width="${#branch_name}"
c_branch_width="$((
branch_curr_width > c_branch_width ?
branch_curr_width :
c_branch_width
))"
# Trim long author names with multiple parts delimited by '/'
author_curr_width="${#author_name}"
if [[ "$author_curr_width" -gt 25 && "$author_name" == *"/"* ]]; then
author_name=".../${author_name#*/}"
c_branch_author_map["$branch"]="$author_name"
author_curr_width="${#author_name}"
fi
c_author_width="$((
author_curr_width > c_author_width ?
author_curr_width :
c_author_width
))"
done <<< "$branch_list"
}
__fgb_branch_list() {
# List branches in a git repository
local branch branch_name author_name author_date bracket_open bracket_close
while IFS= read -r branch; do
branch="${branch%%"$c_split_char"*}"
branch_name="$branch"
if [[ "$branch" == refs/heads/* ]]; then
# Define the bracket characters
bracket_open="$c_bracket_loc_open" bracket_close="$c_bracket_loc_close"
elif [[ "$branch" == refs/remotes/* ]]; then
# Define the bracket characters
bracket_open="$c_bracket_rem_open" bracket_close="$c_bracket_rem_close"
fi
# Remove first two segments of the reference name
branch_name="${branch_name#*/}"; branch_name="${branch_name#*/}"
# Adjust the branch name column width based on the number of color code characters
printf \
"%-$(( c_branch_width + 13 ))b" \
"${bracket_open}${col_y_bold}${branch_name}${col_reset}${bracket_close}"
if [[ "$c_show_author" == true ]]; then
author_name="${c_branch_author_map["$branch"]}"
printf \
"%${c_spacer}s${col_g}%-${c_author_width}s${col_reset}" " " "$author_name"
fi
if [[ "$c_show_date" == true ]]; then
author_date="${c_branch_date_map["$branch"]}"
printf "%${c_spacer}s(${col_b}%s${col_reset})" " " "$author_date"
fi
echo
done <<< "$c_branches"
}
__fgb_set_spacer_var() {
# Set spacer variables for branch/worktree list subcommands
local list_type="${1:-branch}"
# shellcheck disable=SC2076
if [[ ! " branch worktree " =~ " $list_type " ]]; then
echo "$0 error: invalid argument: \`$list_type'" >&2
return 1
fi
local num_spacers
if [[ $list_type == "branch" ]]; then
# Add 5 to avoid truncating the date column
c_total_width="$(( c_branch_width + c_author_width + c_date_width + 5 ))"
if [ "$c_total_width" -gt "$WIDTH_OF_WINDOW" ]; then
c_show_author=false
c_total_width="$(( c_total_width - c_author_width ))"
fi
if [ "$c_total_width" -gt "$WIDTH_OF_WINDOW" ]; then
c_show_date=false
c_total_width="$(( c_total_width - c_date_width ))"
fi
# Calculate spacers
num_spacers=2
c_spacer="$(
echo "$WIDTH_OF_WINDOW $c_total_width $num_spacers" | \
awk '{printf("%.0f", ($1 - $2) / $3)}'
)"
[ "$c_spacer" -le 0 ] && c_spacer=1 || c_spacer=$(( c_spacer < 4 ? c_spacer : 4 ))
elif [[ $list_type == "worktree" ]]; then
# Add 5 to avoid truncating the date column
c_total_width="$((
c_branch_width + c_wt_path_width + c_author_width + c_date_width + 5
))"
if [ "$c_total_width" -gt "$WIDTH_OF_WINDOW" ]; then
c_show_wt_path=false
c_show_wt_flag=true
c_total_width="$(( c_total_width - c_wt_path_width + 1 ))"
fi
if [ "$c_total_width" -gt "$WIDTH_OF_WINDOW" ]; then
c_show_author=false
c_total_width="$(( c_total_width - c_author_width ))"
fi
if [ "$c_total_width" -gt "$WIDTH_OF_WINDOW" ]; then
c_show_date=false
c_total_width="$(( c_total_width - c_date_width ))"
fi
# Calculate spacers
num_spacers=3
if [[ "$c_show_wt_flag" == true ]]; then
num_spacers="$(( num_spacers + 1 ))"
c_total_width="$(( c_total_width + 2 ))"
fi
c_spacer="$(
echo "$WIDTH_OF_WINDOW $c_total_width $num_spacers" | \
awk '{printf("%.0f", ($1 - $2) / $3)}'
)"
[ "$c_spacer" -le 0 ] && c_spacer=1 || c_spacer=$(( c_spacer < 4 ? c_spacer : 4 ))
fi
}
__fgb_print_branch_info() {
# Pring branch information
if [[ $# -lt 1 ]]; then
echo "$0 error: missing argument: branch_name" >&2
return 1
fi
local branch="$1"
local -A values=(
["1.branch"]="$branch"
["2.worktree"]="${c_worktree_path_map["refs/heads/${branch}"]}"
["3.author"]="$(git log -1 --pretty=format:"%an <%ae>" "$branch")"
["4.authordate"]="$(git log -1 --format="%ad" --date=iso "$branch")"
["5.committer"]="$(git log -1 --pretty=format:"%cn <%ce>" "$branch")"
["6.committerdate"]="$(git log -1 --format="%cd" --date=iso "$branch")"
["7.HEAD"]="$(git rev-parse "$branch")"
["8.message"]="$(git log -1 --format="%B" "$branch")"
)
local -A colors=(
["1.branch"]="$col_y_bold"
["2.worktree"]="$col_bold"
["3.author"]="$col_g"
["4.authordate"]="$col_b"
["5.committer"]="$col_g"
["6.committerdate"]="$col_b"
["7.HEAD"]="$col_m"
["8.message"]="$col_y"
)
local -a keys=()
local line key
if [[ -n "${ZSH_VERSION-}" ]]; then
# shellcheck disable=2066,2296
while IFS=$'\n' read -r line; do
keys+=("$line")
done <<< "$(for key in "${(@k)values}"; do echo "$key"; done | sort -n)"
else
while IFS=$'\n' read -r line; do
keys+=("$line")
done <<< "$(for key in "${!values[@]}"; do echo "$key"; done | sort -n)"
fi
local key_width max_width=0
for key in "${keys[@]}"; do
# Remove N. from the key
key="${key:2}"
key_width="${#key}"
max_width="$(( key_width > max_width ? key_width : max_width ))"
done
local message_indent_width message_indent_str
message_indent_width="$(( max_width + 3 ))"
message_indent_str=$(printf "%${message_indent_width}s")
for key in "${keys[@]}"; do
[[ -n "${values[$key]}" ]] && \
printf "%-${max_width}s : ${colors[$key]}%s${col_reset}\n" \
"${key:2}" "${values[$key]}" | sed "3,\$s/^/${message_indent_str}/"
done
}
__fgb_git_branch_new() {
# Create a fork from the selected branch
if [[ $# -eq 0 ]]; then
echo "$0 error: missing arguments: branch_name, branch_type" >&2
return 1
elif [[ $# -lt 2 ]]; then
echo "$0 error: missing argument: branch_type" >&2
return 1
fi
local branch_name="$1"
local branch_type="$2"
local for_new_worktree="${3:-false}"
echo -e "Fork the branch \`${col_b_bold}${branch_name}${col_reset}' and switch to it."
local message="Enter a name for the new branch:"
local new_branch="$branch_name"
if [[ "$branch_type" == "remote" ]]; then
new_branch="${new_branch#*/}"
fi
new_branch+="_fork"
if [[ -n "${ZSH_VERSION-}" ]]; then
vared -p "$message " new_branch
else
echo -en "${message}${col_r}"
IFS= read -re -p " " -i "$new_branch" new_branch
echo -en "$col_reset"
fi
local return_code
if "$for_new_worktree"; then
git branch "$new_branch" "$branch_name"
return_code=$?
else
git switch -c "$new_branch" "$branch_name" >/dev/null
return_code=$?
fi
[[ $return_code -eq 0 ]] &&
c_new_branch="${c_bracket_loc_open}${new_branch}${c_bracket_loc_close}"
}
__fgb_branch_manage() {
# Manage Git branches
local \
spacer_branch=" " \
spacer_authour=" " \
header_column_names_row
spacer_branch="$(
printf "%$(( c_branch_width + 2 - ${#c_column_branch} + c_spacer ))s" " "
)"
spacer_authour="$(printf "%$(( c_author_width - ${#c_column_author} + c_spacer ))s" " ")"
header_column_names_row="${c_column_branch}${spacer_branch}"
[[ "$c_show_author" == true ]] && \
header_column_names_row+="${c_column_author}${spacer_authour}"
[[ "$c_show_date" == true ]] && header_column_names_row+="$c_column_date"
local header="Manage Git Branches:"
header+=" ${c_del_key}:del, ${c_extend_del_key}:extended-del, ${c_info_key}:info"
header+=", ${c_new_branch_key}:fork"
[[ -n "$c_bind_keys" ]] && header+=", $c_bind_keys"
header+=$(__fgb_stdout_unindented "
|
|$header_column_names_row
")
local fzf_cmd="\
$FZF_CMD_GLOB \
--expect='"$c_del_key,$c_extend_del_key,$c_info_key,$c_new_branch_key"' \
--header '$header' \
"
[[ $# -gt 0 ]] && fzf_cmd+=" --query='$*'"
local lines; lines="$(__fgb_branch_list | eval "$fzf_cmd" | cut -d' ' -f1)"
[[ -z "$lines" ]] && return
local key; key="$(head -1 <<< "$lines")"
local is_remote=false
local branch; branch="$(tail -1 <<< "$lines")"
# shellcheck disable=SC2053
if [[ "$branch" == "$c_bracket_rem_open"*/*"$c_bracket_rem_close" ]]; then
is_remote=true
elif [[ "$branch" != "$c_bracket_loc_open"*"$c_bracket_loc_close" ]]; then
echo "error: invalid branch name pattern: $branch" >&2
return 1
fi
local branch_type=""
case "${branch:0:1}" in
"$c_bracket_loc_open") branch_type="local" ;;
"$c_bracket_rem_open") branch_type="remote" ;;
esac
# Remove the first and the last characters (brackets)
branch="${branch:1:-1}"
case $key in
"$c_del_key") __fgb_git_branch_delete "$(sed 1d <<< "$lines")" ;;
"$c_extend_del_key")
c_extend_del=true
__fgb_git_branch_delete "$(sed 1d <<< "$lines")"
;;
"$c_info_key")
__fgb_print_branch_info "$branch"
;;
"$c_new_branch_key")
__fgb_git_branch_new "$branch" "$branch_type"
;;
*)
if ! git rev-parse --show-toplevel &>/dev/null; then
echo "Not inside a Git worktree. Exit..." >&2
return 128
fi
# Remove the first segment of the remote reference name (<upstream>/)
[[ "$is_remote" == true ]] && branch="${branch#*/}"
git switch "$branch"
;;
esac
}
__fgb_transform_git_format_string() {
# Enclose the Git format string into %( ... ) brackets if needed
if [[ $# -ne 1 ]]; then
echo "$0 error: missing argument: input Git format string" >&2
return 1
fi
local input_string="$1"
if [[ "$input_string" =~ %\\([^\)]*[a-zA-Z0-9_]+[^\)]*\\) ]]; then
printf "%s" "$input_string"
else
printf "%%(%s)" "$input_string"
fi
}
__fgb_convert_git_format_string() {
# Convert the Git format string compatible with for-each-ref command to the one
# compatible with log command
if [[ $# -ne 1 ]]; then
echo "$0 error: missing argument: input Git format string" >&2
return 1
fi
local input_string="$1"
# Perform substitutions
input_string="${input_string//\%\(authorname\)/%an}"
input_string="${input_string//\%\(authoremail\)/<%ae>}"
input_string="${input_string//\%\(committername\)/%cn}"
input_string="${input_string//\%\(committeremail\)/<%ce>}"
local date_formats="relative|local|default|iso|iso-strict|rfc|short|raw|"
date_formats+="relative-local|default-local|iso-local|iso-strict-local|"
date_formats+="rfc-local|short-local|raw-local"
local regexp="%\((authordate|committerdate):(format:[^)]+|$date_formats)\)"
input_string="$(sed -E "s/$regexp/%(\1)/g" <<< "$input_string")"
input_string="${input_string//\%\(authordate\)/"$c_split_char"%ad"$c_split_char"}"
input_string="${input_string//\%\(committerdate\)/"$c_split_char"%cd"$c_split_char"}"
echo "$input_string"
}
__fgb_extract_date_format() {
# Extract the date format from the Git for-each-ref compatible foramt string
if [[ $# -ne 1 ]]; then
echo "$0 error: missing argument: input Git format string" >&2
return 1
fi
local input_string="$1"
local date_formats="relative|local|default|iso|iso-strict|rfc|short|raw|"
date_formats+="relative-local|default-local|iso-local|iso-strict-local|"
date_formats+="rfc-local|short-local|raw-local"
local regexp="%\((authordate|committerdate):(format:[^)]+|$date_formats)\)"
extracted="$(grep -oE "$regexp" <<< "$input_string")"
if [[ -n "$extracted" ]]; then
sed -E "s/$regexp/%\1$c_split_char\2/" <<< "$extracted" |
sed 's/authordate/ad/;s/committerdate/cd/'
fi
}
__fgb_branch() {
# Manage Git branches
local subcommand="$1"
shift
case $subcommand in
list | manage)
if ! git rev-parse --git-dir &>/dev/null; then
echo "Not inside a Git repository. Exit..." >&2
return 128
fi
local -a fzf_query=()
local branch_show_remote=false branch_show_all=false
while [ $# -gt 0 ]; do
case "$1" in
-s | --sort)
shift
c_branch_sort_order="$1"
;;
--sort=*)
c_branch_sort_order="${1#*=}"
;;
-d | --date-format)
shift
c_date_format="$1"
;;
--date-format=*)
c_date_format="${1#*=}"
;;
-u | --author-format)
shift
c_author_format="$1"
;;
--author-format=*)
c_author_format="${1#*=}"
;;
-r | --remotes)
branch_show_remote=true
;;
-a | --all)
branch_show_all=true
;;
-f | --force)
if [[ "$subcommand" == "list" ]]; then
echo "error: unknown option: \`$1'" >&2
echo "${usage_message[branch_$subcommand]}" >&2
return 1
fi
c_force=true
;;
-h | --help)
echo "${usage_message[branch_$subcommand]}"
return 0
;;
--)
if [[ "$subcommand" == "list" ]]; then
echo "error: unknown option: \`$1'" >&2
echo " query not expected for the list command." >&2
echo "${usage_message[branch_$subcommand]}" >&2
return 1
fi
while [ $# -gt 1 ]; do
shift
fzf_query+=("$1")
done
break
;;
--* | -*)
echo "error: unknown option: \`$1'" >&2
echo "${usage_message[branch_$subcommand]}" >&2
return 1
;;
*)
if [[ "$subcommand" == "list" ]]; then
echo "error: unknown option: \`$1'" >&2
echo " query not expected for the list command." >&2
echo "${usage_message[branch_$subcommand]}" >&2
return 1
fi
fzf_query+=("$1")
;;
esac
shift
done
c_date_format="$(__fgb_transform_git_format_string "$c_date_format")"
c_author_format="$(__fgb_transform_git_format_string "$c_author_format")"
local branch_type
[[ "$branch_show_remote" == true ]] && \
branch_type="remote" || \
branch_type="local"
[[ "$branch_show_all" == true ]] && branch_type="all"
local return_code
c_branches="$(__fgb_git_branch_list "$branch_type")"
return_code=$?; [[ $return_code -ne 0 ]] && return "$return_code"
__fgb_branch_set_vars "$c_branches"
__fgb_set_spacer_var "branch"
case $subcommand in
list) __fgb_branch_list ;;
manage) __fgb_branch_manage "${fzf_query[@]}" ;;
esac
;;
-h | --help)
echo "${usage_message[branch]}"
;;
--* | -*)
echo "error: unknown option: \`$subcommand'" >&2
echo "${usage_message[branch]}" >&2
return 1
;;
*)
echo "error: unknown subcommand: \`$subcommand'" >&2
echo "${usage_message[branch]}" >&2
return 1
;;
esac
}
__fgb_git_worktree_delete() {
# Delete a Git worktree for a given branch
if [[ -z "$1" ]]; then
echo "$0: Missing argument: list of branches" >&2
return 1
fi
local \
force_bak="$c_force" \
branch_name \
error_pattern \
is_in_target_wt=false \
is_remote \
output \
success_message \
user_prompt \
worktrees_to_delete="$1" \
wt_path \
line
local -a array_of_lines
while IFS= read -r line; do
array_of_lines+=( "$line" )
done <<< "$worktrees_to_delete"
for branch_name in "${array_of_lines[@]}"; do
is_remote=false
wt_path=""
# shellcheck disable=SC2053
if [[ "$branch_name" == "$c_bracket_rem_open"*/*"$c_bracket_rem_close" ]]; then
is_remote=true
elif [[ "$branch_name" != "$c_bracket_loc_open"*"$c_bracket_loc_close" ]]; then
echo "error: invalid branch name pattern: $branch_name" >&2
return 1
fi
# Remove the first and the last characters (brackets)
branch_name="${branch_name:1}"; branch_name="${branch_name%?}"
[[ ! "$is_remote" == true ]] && \
wt_path="${c_worktree_path_map["refs/heads/${branch_name}"]}"
if [[ -n "$wt_path" ]]; then
# Process a branch with a corresponding worktree
is_in_target_wt=false
if [[ "$PWD" == "$wt_path" ]]; then
cd "$c_bare_repo_path" && is_in_target_wt=true || return 1
fi
user_prompt=$(__fgb_stdout_unindented "
|${col_r_bold}Delete${col_reset} worktree: \#
|${col_y_bold}${wt_path}${col_reset}, \#
|for branch '${col_b_bold}${branch_name}${col_reset}'?
")
if [[ "$c_force" == true ]] || __fgb_confirmation_dialog "$user_prompt"; then
success_message=$(__fgb_stdout_unindented "
|${col_g_bold}Deleted${col_reset} worktree: \#
|${col_y_bold}${wt_path}${col_reset} \#
|for branch '${col_b_bold}${branch_name}${col_reset}'
")
if ! output="$(git worktree remove "$wt_path" 2>&1)"; then
error_pattern="^fatal: .* contains modified or untracked files,"
error_pattern+=" use --force to delete it$"
if ! grep -q "$error_pattern" <<< "$output"; then
echo "$output"
continue
fi
user_prompt=$(__fgb_stdout_unindented "
|
|${col_r_bold}WARNING:${col_reset} \#
|This will permanently reset/delete the following files:
|
|$(script -q /dev/null -c "git -C \"$wt_path\" status --short")
|
|in the ${col_y_bold}${wt_path}${col_reset} path.
|
|Are you sure you want to proceed?
")
# NOTE: Avoid --force here as it's not undoable operation
if __fgb_confirmation_dialog "$user_prompt"; then
if output="$(git worktree remove "$wt_path" --force)"; then
echo -e "$success_message"
else
echo "$output" >&2
fi
user_prompt=$(__fgb_stdout_unindented "
|${col_r_bold}Delete${col_reset} the corresponding \#
|'${col_b_bold}${branch_name}${col_reset}' branch as well?
")
if __fgb_confirmation_dialog "$user_prompt"; then
c_force=true
branch_name="${c_bracket_loc_open}${branch_name}"
branch_name+="$c_bracket_loc_close"
__fgb_git_branch_delete "$branch_name"
c_force="$force_bak"
fi
else
if [[ "$is_in_target_wt" == true ]]; then
cd "$wt_path" || return 1
fi
fi
else
[[ "$c_force" == true ]] && echo -e "$success_message"
user_prompt=$(__fgb_stdout_unindented "
|${col_r_bold}Delete${col_reset} the corresponding \#
|'${col_b_bold}${branch_name}${col_reset}' branch as well?
")
if __fgb_confirmation_dialog "$user_prompt"; then
c_force=true
branch_name="${c_bracket_loc_open}${branch_name}"
branch_name+="$c_bracket_loc_close"
__fgb_git_branch_delete "$branch_name"
c_force="$force_bak"
fi
fi
else
if [[ "$is_in_target_wt" == true ]]; then
cd "$wt_path" || return 1
fi
fi
else
# Process a branch that doesn't have a corresponding worktree
c_force=true
if [[ "$is_remote" == true ]]; then
branch_name="${c_bracket_rem_open}${branch_name}${c_bracket_rem_close}"
else
branch_name="${c_bracket_loc_open}${branch_name}${c_bracket_loc_close}"
fi
__fgb_git_branch_delete "$branch_name"
c_force="$force_bak"
fi
done
}
__fgb_git_worktree_jump_or_add() {
# Jump to an existing worktree or add a new one for a given branch
if [ $# -eq 0 ]; then
echo "Missing argument: branch name" >&2
return 1
fi
local \
branch_name="$1" \
remote_branch \
wt_path \
message \
ref_prefix
# shellcheck disable=SC2053
if [[ "$branch_name" == "$c_bracket_rem_open"*/*"$c_bracket_rem_close" ]]; then
# Remove the first and the last characters (brackets)
remote_branch="${branch_name:1}"; remote_branch="${remote_branch%?}"
# Remove the first segment of the reference name (<upstream>/)
branch_name="${remote_branch#*/}"
ref_prefix="refs/remotes/"
elif [[ "$branch_name" == "$c_bracket_loc_open"*"$c_bracket_loc_close" ]]; then
branch_name="${branch_name:1}"; branch_name="${branch_name%?}"
ref_prefix="refs/heads/"
elif [[ "$branch_name" == "$c_bracket_det_open"*"$c_bracket_det_close" ]]; then
branch_name="${branch_name:1}"; branch_name="${branch_name%?}"
ref_prefix="$c_detached_wt_prefix"
else
echo "error: invalid branch name pattern: $branch_name" >&2
return 1
fi
wt_path="${c_worktree_path_map["$ref_prefix$branch_name"]}"
if [[ -n "$wt_path" ]]; then
cd "$wt_path" || return 1
message=$(__fgb_stdout_unindented "
|${col_g_bold}Jumped${col_reset} to worktree: \#
|${col_y_bold}${wt_path}${col_reset}, \#
|for branch '${col_b_bold}${branch_name}${col_reset}'
")
echo -e "$message"
else
if [[ "$c_confirmed" == true ]]; then
wt_path="${c_bare_repo_path}/${branch_name}"
else
if [[ -n "$remote_branch" ]]; then
printf "%b\n" "$(__fgb_stdout_unindented "
|Add a new worktree for '${col_b_bold}${branch_name}${col_reset}' \#
|(remote branch: '${col_y_bold}${remote_branch}${col_reset}').
|The path to the worktree must be absolute \#
|or relative to the path to the bare repository.
")"
else
printf "%b\n" "$(__fgb_stdout_unindented "
|Add a new worktree for '${col_b_bold}${branch_name}${col_reset}'.
|The path to the worktree must be absolute \#
|or relative to the path to the bare repository.
")"
fi
message="Enter the path:"
wt_path="$branch_name"