-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathgtr
More file actions
executable file
·1335 lines (1161 loc) · 38.1 KB
/
gtr
File metadata and controls
executable file
·1335 lines (1161 loc) · 38.1 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
# gtr - Git worktree runner
# Portable, cross-platform git worktree management
set -e
# Version
GTR_VERSION="2.0.0"
# Find the script directory (resolve symlinks; allow env override)
resolve_script_dir() {
local src="${BASH_SOURCE[0]}"
while [ -h "$src" ]; do
local dir
dir="$(cd -P "$(dirname "$src")" && pwd)"
src="$(readlink "$src")"
[[ $src != /* ]] && src="$dir/$src"
done
cd -P "$(dirname "$src")/.." && pwd
}
: "${GTR_DIR:=$(resolve_script_dir)}"
# Source library files
. "$GTR_DIR/lib/ui.sh"
. "$GTR_DIR/lib/config.sh"
. "$GTR_DIR/lib/platform.sh"
. "$GTR_DIR/lib/core.sh"
. "$GTR_DIR/lib/copy.sh"
. "$GTR_DIR/lib/hooks.sh"
# Generic adapter functions (used when no explicit adapter file exists)
# These will be overridden if an adapter file is sourced
# Globals set by load_editor_adapter: GTR_EDITOR_CMD, GTR_EDITOR_CMD_NAME
editor_can_open() {
command -v "$GTR_EDITOR_CMD_NAME" >/dev/null 2>&1
}
editor_open() {
# $GTR_EDITOR_CMD may contain arguments (e.g., "code --wait")
# Using eval here is necessary to handle multi-word commands properly
eval "$GTR_EDITOR_CMD \"\$1\""
}
# Globals set by load_ai_adapter: GTR_AI_CMD, GTR_AI_CMD_NAME
ai_can_start() {
command -v "$GTR_AI_CMD_NAME" >/dev/null 2>&1
}
ai_start() {
local path="$1"
shift
# $GTR_AI_CMD may contain arguments (e.g., "bunx @github/copilot@latest")
# Using eval here is necessary to handle multi-word commands properly
(cd "$path" && eval "$GTR_AI_CMD \"\$@\"")
}
# Main dispatcher
main() {
local cmd="${1:-help}"
shift 2>/dev/null || true
case "$cmd" in
new)
cmd_create "$@"
;;
rm)
cmd_remove "$@"
;;
go)
cmd_go "$@"
;;
run)
cmd_run "$@"
;;
editor)
cmd_editor "$@"
;;
ai)
cmd_ai "$@"
;;
copy)
cmd_copy "$@"
;;
ls|list)
cmd_list "$@"
;;
clean)
cmd_clean "$@"
;;
doctor)
cmd_doctor "$@"
;;
adapter|adapters)
cmd_adapter "$@"
;;
config)
cmd_config "$@"
;;
version|--version|-v)
echo "git gtr version $GTR_VERSION"
;;
help|--help|-h)
cmd_help
;;
*)
log_error "Unknown command: $cmd"
echo "Use 'git gtr help' for available commands"
exit 1
;;
esac
}
# Create command
cmd_create() {
local branch_name=""
local from_ref=""
local from_current=0
local track_mode="auto"
local skip_copy=0
local skip_fetch=0
local yes_mode=0
local force=0
local custom_name=""
# Parse flags and arguments
while [ $# -gt 0 ]; do
case "$1" in
--from)
from_ref="$2"
shift 2
;;
--from-current)
from_current=1
shift
;;
--track)
track_mode="$2"
shift 2
;;
--no-copy)
skip_copy=1
shift
;;
--no-fetch)
skip_fetch=1
shift
;;
--yes)
yes_mode=1
shift
;;
--force)
force=1
shift
;;
--name)
custom_name="$2"
shift 2
;;
-*)
log_error "Unknown flag: $1"
exit 1
;;
*)
# Positional argument: treat as branch name
if [ -z "$branch_name" ]; then
branch_name="$1"
fi
shift
;;
esac
done
# Validate flag combinations
if [ "$force" -eq 1 ] && [ -z "$custom_name" ]; then
log_error "--force requires --name to distinguish worktrees"
if [ -n "$branch_name" ]; then
echo "Example: git gtr new $branch_name --force --name backend" >&2
else
echo "Example: git gtr new feature-auth --force --name backend" >&2
fi
exit 1
fi
# Get repo info
local repo_root
repo_root=$(discover_repo_root) || exit 1
local base_dir prefix
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
# Get branch name if not provided
if [ -z "$branch_name" ]; then
if [ "$yes_mode" -eq 1 ]; then
log_error "Branch name required in non-interactive mode"
exit 1
fi
branch_name=$(prompt_input "Enter branch name:")
if [ -z "$branch_name" ]; then
log_error "Branch name required"
exit 1
fi
fi
# Determine from_ref with precedence: --from > --from-current > default
if [ -z "$from_ref" ]; then
if [ "$from_current" -eq 1 ]; then
# Get current branch (try modern git first, then fallback)
from_ref=$(git branch --show-current 2>/dev/null)
if [ -z "$from_ref" ]; then
from_ref=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
fi
# Handle detached HEAD state
if [ -z "$from_ref" ] || [ "$from_ref" = "HEAD" ]; then
log_warn "Currently in detached HEAD state - falling back to default branch"
from_ref=$(resolve_default_branch "$repo_root")
else
log_info "Creating from current branch: $from_ref"
fi
else
from_ref=$(resolve_default_branch "$repo_root")
fi
fi
# Construct folder name for display
local folder_name
if [ -n "$custom_name" ]; then
folder_name="$(sanitize_branch_name "$branch_name")-${custom_name}"
else
folder_name=$(sanitize_branch_name "$branch_name")
fi
log_step "Creating worktree: $folder_name"
echo "Location: $base_dir/${prefix}${folder_name}"
echo "Branch: $branch_name"
# Create the worktree
if ! worktree_path=$(create_worktree "$base_dir" "$prefix" "$branch_name" "$from_ref" "$track_mode" "$skip_fetch" "$force" "$custom_name"); then
exit 1
fi
# Copy files based on patterns
if [ "$skip_copy" -eq 0 ]; then
local includes excludes file_includes
# Pass .gtrconfig keys as second argument for file-based config
includes=$(cfg_get_all gtr.copy.include copy.include)
excludes=$(cfg_get_all gtr.copy.exclude copy.exclude)
# Read .worktreeinclude file if exists
file_includes=$(parse_pattern_file "$repo_root/.worktreeinclude")
# Merge patterns (newline-separated)
if [ -n "$file_includes" ]; then
if [ -n "$includes" ]; then
includes="$includes"$'\n'"$file_includes"
else
includes="$file_includes"
fi
fi
if [ -n "$includes" ]; then
log_step "Copying files..."
copy_patterns "$repo_root" "$worktree_path" "$includes" "$excludes"
fi
# Copy directories (typically git-ignored dirs like node_modules, .venv)
local dir_includes dir_excludes
# Pass .gtrconfig keys as second argument for file-based config
dir_includes=$(cfg_get_all gtr.copy.includeDirs copy.includeDirs)
dir_excludes=$(cfg_get_all gtr.copy.excludeDirs copy.excludeDirs)
if [ -n "$dir_includes" ]; then
log_step "Copying directories..."
copy_directories "$repo_root" "$worktree_path" "$dir_includes" "$dir_excludes"
fi
fi
# Run post-create hooks
run_hooks_in postCreate "$worktree_path" \
REPO_ROOT="$repo_root" \
WORKTREE_PATH="$worktree_path" \
BRANCH="$branch_name"
echo ""
log_info "Worktree created: $worktree_path"
echo ""
echo "Next steps:"
echo " git gtr editor $branch_name # Open in editor"
echo " git gtr ai $branch_name # Start AI tool"
echo " cd \"\$(git gtr go $branch_name)\" # Navigate to worktree"
# Display custom next steps from configuration
local custom_steps
custom_steps=$(cfg_get_all "gtr.nextStep" "nextSteps.step")
if [ -n "$custom_steps" ]; then
while IFS= read -r step; do
[ -z "$step" ] && continue
# Substitute variables
step="${step//\$BRANCH/$branch_name}"
step="${step//\${BRANCH\}/$branch_name}"
step="${step//\$WORKTREE_PATH/$worktree_path}"
step="${step//\${WORKTREE_PATH\}/$worktree_path}"
step="${step//\$REPO_ROOT/$repo_root}"
step="${step//\${REPO_ROOT\}/$repo_root}"
echo " $step"
done <<< "$custom_steps"
fi
}
# Remove command
cmd_remove() {
local delete_branch=0
local yes_mode=0
local force=0
local identifiers=""
# Parse flags
while [ $# -gt 0 ]; do
case "$1" in
--delete-branch)
delete_branch=1
shift
;;
--yes)
yes_mode=1
shift
;;
--force)
force=1
shift
;;
-*)
log_error "Unknown flag: $1"
exit 1
;;
*)
identifiers="$identifiers $1"
shift
;;
esac
done
if [ -z "$identifiers" ]; then
log_error "Usage: git gtr rm <id|branch> [<id|branch>...] [--delete-branch] [--force] [--yes]"
exit 1
fi
local repo_root base_dir prefix
repo_root=$(discover_repo_root) || exit 1
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
for identifier in $identifiers; do
# Resolve target branch
local target is_main worktree_path branch_name
target=$(resolve_target "$identifier" "$repo_root" "$base_dir" "$prefix") || continue
is_main=$(echo "$target" | cut -f1)
worktree_path=$(echo "$target" | cut -f2)
branch_name=$(echo "$target" | cut -f3)
# Cannot remove main repository
if [ "$is_main" = "1" ]; then
log_error "Cannot remove main repository"
continue
fi
log_step "Removing worktree: $branch_name"
# Run pre-remove hooks (abort on failure unless --force)
if ! run_hooks_in preRemove "$worktree_path" \
REPO_ROOT="$repo_root" \
WORKTREE_PATH="$worktree_path" \
BRANCH="$branch_name"; then
if [ "$force" -eq 0 ]; then
log_error "Pre-remove hook failed for $branch_name. Use --force to skip hooks."
continue
else
log_warn "Pre-remove hook failed, continuing due to --force"
fi
fi
# Remove the worktree
if ! remove_worktree "$worktree_path" "$force"; then
continue
fi
# Handle branch deletion
if [ -n "$branch_name" ]; then
if [ "$delete_branch" -eq 1 ]; then
if [ "$yes_mode" -eq 1 ] || prompt_yes_no "Also delete branch '$branch_name'?"; then
if git branch -D "$branch_name" 2>/dev/null; then
log_info "Branch deleted: $branch_name"
else
log_warn "Could not delete branch: $branch_name"
fi
fi
fi
fi
# Run post-remove hooks
run_hooks postRemove \
REPO_ROOT="$repo_root" \
WORKTREE_PATH="$worktree_path" \
BRANCH="$branch_name"
done
}
# Go command (navigate to worktree - prints path for shell integration)
cmd_go() {
if [ $# -ne 1 ]; then
log_error "Usage: git gtr go <id|branch>"
exit 1
fi
local identifier="$1"
local repo_root base_dir prefix
repo_root=$(discover_repo_root) || exit 1
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
# Resolve target branch
local target is_main worktree_path branch
target=$(resolve_target "$identifier" "$repo_root" "$base_dir" "$prefix") || exit 1
is_main=$(echo "$target" | cut -f1)
worktree_path=$(echo "$target" | cut -f2)
branch=$(echo "$target" | cut -f3)
# Human messages to stderr so stdout can be used in command substitution
if [ "$is_main" = "1" ]; then
echo "Main repo" >&2
else
echo "Worktree: $branch" >&2
fi
echo "Branch: $branch" >&2
# Print path to stdout for shell integration: cd "$(gtr go my-feature)"
printf "%s\n" "$worktree_path"
}
# Run command (execute command in worktree directory)
cmd_run() {
local identifier=""
local -a run_args=()
# Parse arguments
while [ $# -gt 0 ]; do
case "$1" in
-*)
log_error "Unknown flag: $1"
exit 1
;;
*)
if [ -z "$identifier" ]; then
identifier="$1"
shift
else
run_args=("$@") # Capture all remaining args as the command
break
fi
;;
esac
done
# Validation
if [ -z "$identifier" ]; then
log_error "Usage: git gtr run <id|branch> <command...>"
exit 1
fi
if [ ${#run_args[@]} -eq 0 ]; then
log_error "Usage: git gtr run <id|branch> <command...>"
log_error "No command specified"
exit 1
fi
local repo_root base_dir prefix
repo_root=$(discover_repo_root) || exit 1
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
# Resolve target branch
local target is_main worktree_path branch
target=$(resolve_target "$identifier" "$repo_root" "$base_dir" "$prefix") || exit 1
is_main=$(echo "$target" | cut -f1)
worktree_path=$(echo "$target" | cut -f2)
branch=$(echo "$target" | cut -f3)
# Human messages to stderr (like cmd_go)
if [ "$is_main" = "1" ]; then
log_step "Running in: main repo"
else
log_step "Running in: $branch"
fi
echo "Command: ${run_args[*]}" >&2
echo "" >&2
# Execute command in worktree directory (exit code propagates)
(cd "$worktree_path" && "${run_args[@]}")
}
# Copy command (copy files between worktrees)
cmd_copy() {
local source="1" # Default: main repo
local targets=""
local patterns=""
local all_mode=0
local dry_run=0
# Parse arguments (patterns come after -- separator, like git pathspec)
while [ $# -gt 0 ]; do
case "$1" in
--from)
source="$2"
shift 2
;;
-n|--dry-run)
dry_run=1
shift
;;
-a|--all)
all_mode=1
shift
;;
--)
shift
# Remaining args are patterns (like git pathspec)
while [ $# -gt 0 ]; do
if [ -n "$patterns" ]; then
patterns="$patterns"$'\n'"$1"
else
patterns="$1"
fi
shift
done
break
;;
-*)
log_error "Unknown flag: $1"
exit 1
;;
*)
targets="$targets $1"
shift
;;
esac
done
# Validation
if [ "$all_mode" -eq 0 ] && [ -z "$targets" ]; then
log_error "Usage: git gtr copy <target>... [-n] [-a] [--from <source>] [-- <pattern>...]"
exit 1
fi
# Get repo context
local repo_root base_dir prefix
repo_root=$(discover_repo_root) || exit 1
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
# Resolve source path
local src_target src_path
src_target=$(resolve_target "$source" "$repo_root" "$base_dir" "$prefix") || exit 1
src_path=$(echo "$src_target" | cut -f2)
# Get patterns (flag > config)
if [ -z "$patterns" ]; then
patterns=$(cfg_get_all gtr.copy.include copy.include)
# Also check .worktreeinclude
if [ -f "$repo_root/.worktreeinclude" ]; then
local file_patterns
file_patterns=$(parse_pattern_file "$repo_root/.worktreeinclude")
if [ -n "$file_patterns" ]; then
if [ -n "$patterns" ]; then
patterns="$patterns"$'\n'"$file_patterns"
else
patterns="$file_patterns"
fi
fi
fi
fi
if [ -z "$patterns" ]; then
log_error "No patterns specified. Use '-- <pattern>...' or configure gtr.copy.include"
exit 1
fi
local excludes
excludes=$(cfg_get_all gtr.copy.exclude copy.exclude)
# Build target list for --all mode
if [ "$all_mode" -eq 1 ]; then
targets=$(list_worktree_branches "$base_dir" "$prefix")
if [ -z "$targets" ]; then
log_error "No worktrees found"
exit 1
fi
fi
# Process each target
local copied_any=0
for target_id in $targets; do
local dst_target dst_path dst_branch
dst_target=$(resolve_target "$target_id" "$repo_root" "$base_dir" "$prefix") || continue
dst_path=$(echo "$dst_target" | cut -f2)
dst_branch=$(echo "$dst_target" | cut -f3)
# Skip if source == destination
[ "$src_path" = "$dst_path" ] && continue
if [ "$dry_run" -eq 1 ]; then
log_step "[dry-run] Would copy to: $dst_branch"
copy_patterns "$src_path" "$dst_path" "$patterns" "$excludes" "true" "true"
else
log_step "Copying to: $dst_branch"
copy_patterns "$src_path" "$dst_path" "$patterns" "$excludes" "true"
fi
copied_any=1
done
if [ "$copied_any" -eq 0 ]; then
log_warn "No files copied (source and target may be the same)"
fi
}
# Editor command
cmd_editor() {
local identifier=""
local editor=""
# Parse flags
while [ $# -gt 0 ]; do
case "$1" in
--editor)
editor="$2"
shift 2
;;
-*)
log_error "Unknown flag: $1"
exit 1
;;
*)
if [ -z "$identifier" ]; then
identifier="$1"
fi
shift
;;
esac
done
if [ -z "$identifier" ]; then
log_error "Usage: git gtr editor <id|branch> [--editor <name>]"
exit 1
fi
# Get editor from flag or config (with .gtrconfig support)
if [ -z "$editor" ]; then
editor=$(cfg_default gtr.editor.default GTR_EDITOR_DEFAULT "none" defaults.editor)
fi
local repo_root base_dir prefix
repo_root=$(discover_repo_root) || exit 1
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
# Resolve target branch
local target worktree_path branch
target=$(resolve_target "$identifier" "$repo_root" "$base_dir" "$prefix") || exit 1
worktree_path=$(echo "$target" | cut -f2)
branch=$(echo "$target" | cut -f3)
if [ "$editor" = "none" ]; then
# Just open in GUI file browser
open_in_gui "$worktree_path"
log_info "Opened in file browser"
else
# Load editor adapter and open
load_editor_adapter "$editor"
log_step "Opening in $editor..."
editor_open "$worktree_path"
fi
}
# AI command
cmd_ai() {
local identifier=""
local ai_tool=""
local -a ai_args=()
# Parse arguments
while [ $# -gt 0 ]; do
case "$1" in
--ai)
ai_tool="$2"
shift 2
;;
--)
shift
ai_args=("$@")
break
;;
-*)
log_error "Unknown flag: $1"
exit 1
;;
*)
if [ -z "$identifier" ]; then
identifier="$1"
fi
shift
;;
esac
done
if [ -z "$identifier" ]; then
log_error "Usage: git gtr ai <id|branch> [--ai <name>] [-- args...]"
exit 1
fi
# Get AI tool from flag or config (with .gtrconfig support)
if [ -z "$ai_tool" ]; then
ai_tool=$(cfg_default gtr.ai.default GTR_AI_DEFAULT "none" defaults.ai)
fi
# Check if AI tool is configured
if [ "$ai_tool" = "none" ]; then
log_error "No AI tool configured"
log_info "Set default: git gtr config set gtr.ai.default claude"
exit 1
fi
# Load AI adapter
load_ai_adapter "$ai_tool"
local repo_root base_dir prefix
repo_root=$(discover_repo_root) || exit 1
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
# Resolve target branch
local target worktree_path branch
target=$(resolve_target "$identifier" "$repo_root" "$base_dir" "$prefix") || exit 1
worktree_path=$(echo "$target" | cut -f2)
branch=$(echo "$target" | cut -f3)
log_step "Starting $ai_tool for: $branch"
echo "Directory: $worktree_path"
echo "Branch: $branch"
ai_start "$worktree_path" "${ai_args[@]}"
}
# List command
cmd_list() {
local porcelain=0
# Parse flags
while [ $# -gt 0 ]; do
case "$1" in
--porcelain)
porcelain=1
shift
;;
*)
shift
;;
esac
done
local repo_root base_dir prefix
repo_root=$(discover_repo_root) 2>/dev/null || return 0
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
# Machine-readable output (porcelain)
if [ "$porcelain" -eq 1 ]; then
# Output: path<tab>branch<tab>status
local branch status
# Try --show-current (Git 2.22+), fallback to rev-parse for older Git
branch=$(git -C "$repo_root" branch --show-current 2>/dev/null)
[ -z "$branch" ] && branch=$(git -C "$repo_root" rev-parse --abbrev-ref HEAD 2>/dev/null)
[ -z "$branch" ] || [ "$branch" = "HEAD" ] && branch="(detached)"
status=$(worktree_status "$repo_root")
printf "%s\t%s\t%s\n" "$repo_root" "$branch" "$status"
if [ -d "$base_dir" ]; then
# Find all worktree directories and output: path<tab>branch<tab>status
find "$base_dir" -maxdepth 1 -type d -name "${prefix}*" 2>/dev/null | while IFS= read -r dir; do
local branch status
branch=$(current_branch "$dir")
[ -z "$branch" ] && branch="(detached)"
status=$(worktree_status "$dir")
printf "%s\t%s\t%s\n" "$dir" "$branch" "$status"
done | LC_ALL=C sort -k2,2
fi
return 0
fi
# Human-readable output - table format
echo "Git Worktrees"
echo ""
printf "%-30s %s\n" "BRANCH" "PATH"
printf "%-30s %s\n" "------" "----"
# Always show repo root first
local branch
# Try --show-current (Git 2.22+), fallback to rev-parse for older Git
branch=$(git -C "$repo_root" branch --show-current 2>/dev/null)
[ -z "$branch" ] && branch=$(git -C "$repo_root" rev-parse --abbrev-ref HEAD 2>/dev/null)
[ -z "$branch" ] || [ "$branch" = "HEAD" ] && branch="(detached)"
printf "%-30s %s\n" "$branch [main repo]" "$repo_root"
# Show worktrees sorted by branch name
if [ -d "$base_dir" ]; then
find "$base_dir" -maxdepth 1 -type d -name "${prefix}*" 2>/dev/null | while IFS= read -r dir; do
local branch
branch=$(current_branch "$dir")
[ -z "$branch" ] && branch="(detached)"
printf "%-30s %s\n" "$branch" "$dir"
done | LC_ALL=C sort -k1,1
fi
echo ""
echo ""
echo "Tip: Use 'git gtr list --porcelain' for machine-readable output"
}
# Clean command (remove prunable worktrees)
cmd_clean() {
log_step "Cleaning up stale worktrees..."
# Run git worktree prune
if git worktree prune 2>/dev/null; then
log_info "Pruned stale worktree administrative files"
fi
local repo_root base_dir prefix
repo_root=$(discover_repo_root) || exit 1
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
if [ ! -d "$base_dir" ]; then
log_info "No worktrees directory to clean"
return 0
fi
# Find and remove empty directories
local cleaned=0
local empty_dirs
empty_dirs=$(find "$base_dir" -maxdepth 1 -type d -empty 2>/dev/null | grep -v "^${base_dir}$" || true)
if [ -n "$empty_dirs" ]; then
while IFS= read -r dir; do
if [ -n "$dir" ]; then
if rmdir "$dir" 2>/dev/null; then
cleaned=$((cleaned + 1))
log_info "Removed empty directory: $(basename "$dir")"
fi
fi
done <<EOF
$empty_dirs
EOF
fi
if [ "$cleaned" -gt 0 ]; then
log_info "Cleanup complete ($cleaned director$([ "$cleaned" -eq 1 ] && echo 'y' || echo 'ies') removed)"
else
log_info "Cleanup complete (no empty directories found)"
fi
}
# Doctor command (health check)
cmd_doctor() {
echo "Running git gtr health check..."
echo ""
local issues=0
# Check git
if command -v git >/dev/null 2>&1; then
local git_version
git_version=$(git --version)
echo "[OK] Git: $git_version"
else
echo "[x] Git: not found"
issues=$((issues + 1))
fi
# Check repo
local repo_root
if repo_root=$(discover_repo_root 2>/dev/null); then
echo "[OK] Repository: $repo_root"
# Check worktree base dir
local base_dir prefix
base_dir=$(resolve_base_dir "$repo_root")
prefix=$(cfg_default gtr.worktrees.prefix GTR_WORKTREES_PREFIX "")
if [ -d "$base_dir" ]; then
local count
count=$(find "$base_dir" -maxdepth 1 -type d -name "${prefix}*" 2>/dev/null | wc -l | tr -d ' ')
echo "[OK] Worktrees directory: $base_dir ($count worktrees)"
else
echo "[i] Worktrees directory: $base_dir (not created yet)"
fi
else
echo "[x] Not in a git repository"
issues=$((issues + 1))
fi
# Check configured editor (with .gtrconfig support)
local editor
editor=$(cfg_default gtr.editor.default GTR_EDITOR_DEFAULT "none" defaults.editor)
if [ "$editor" != "none" ]; then
# Check if adapter exists
local editor_adapter="$GTR_DIR/adapters/editor/${editor}.sh"
if [ -f "$editor_adapter" ]; then
. "$editor_adapter"
if editor_can_open 2>/dev/null; then
echo "[OK] Editor: $editor (found)"
else
echo "[!] Editor: $editor (configured but not found in PATH)"
fi
else
echo "[!] Editor: $editor (adapter not found)"
fi
else
echo "[i] Editor: none configured"
fi
# Check configured AI tool (with .gtrconfig support)
local ai_tool
ai_tool=$(cfg_default gtr.ai.default GTR_AI_DEFAULT "none" defaults.ai)
if [ "$ai_tool" != "none" ]; then
# Check if adapter exists
local adapter_file="$GTR_DIR/adapters/ai/${ai_tool}.sh"
if [ -f "$adapter_file" ]; then
. "$adapter_file"
if ai_can_start 2>/dev/null; then
echo "[OK] AI tool: $ai_tool (found)"
else
echo "[!] AI tool: $ai_tool (configured but not found in PATH)"
fi
else
echo "[!] AI tool: $ai_tool (adapter not found)"
fi
else
echo "[i] AI tool: none configured"
fi
# Check OS
local os
os=$(detect_os)
echo "[OK] Platform: $os"
echo ""
if [ "$issues" -eq 0 ]; then
echo "Everything looks good!"
return 0
else
echo "[!] Found $issues issue(s)"
return 1
fi
}
# Adapter command (list available adapters)
cmd_adapter() {
echo "Available Adapters"
echo ""
# Editor adapters
echo "Editor Adapters:"
echo ""
printf "%-15s %-15s %s\n" "NAME" "STATUS" "NOTES"
printf "%-15s %-15s %s\n" "---------------" "---------------" "-----"
for adapter_file in "$GTR_DIR"/adapters/editor/*.sh; do
if [ -f "$adapter_file" ]; then
local adapter_name
adapter_name=$(basename "$adapter_file" .sh)
. "$adapter_file"
if editor_can_open 2>/dev/null; then
printf "%-15s %-15s %s\n" "$adapter_name" "[ready]" ""
else
printf "%-15s %-15s %s\n" "$adapter_name" "[missing]" "Not found in PATH"
fi
fi
done
echo ""
echo ""
echo "AI Tool Adapters:"
echo ""
printf "%-15s %-15s %s\n" "NAME" "STATUS" "NOTES"
printf "%-15s %-15s %s\n" "---------------" "---------------" "-----"
for adapter_file in "$GTR_DIR"/adapters/ai/*.sh; do
if [ -f "$adapter_file" ]; then