-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclc.sh
More file actions
executable file
·1183 lines (1022 loc) · 50.2 KB
/
clc.sh
File metadata and controls
executable file
·1183 lines (1022 loc) · 50.2 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
# clc - Claude Cloak
# Use Claude Code across worktrees without leaving traces.
set -euo pipefail
# ── Constants ─────────────────────────────────────────────────────────────────
CLC_VERSION="1.4.1"
CLC_STORE="${CLC_STORE:-${HOME}/.clc}"
# ── Color / style ─────────────────────────────────────────────────────────────
# Populated by setup_color(); empty strings when color is disabled.
CLR_BOLD="" CLR_DIM="" CLR_RESET=""
CLR_SECTION="" CLR_KEY="" CLR_VAL="" CLR_MUTED="" CLR_WARN=""
setup_color() {
# Disable when NO_COLOR is set, --no-color was passed, or stdout is not a tty.
if [[ -n "${NO_COLOR-}" || "${OPT_NO_COLOR}" == 1 || ! -t 1 ]]; then
return
fi
CLR_BOLD=$'\e[1m'
CLR_DIM=$'\e[2m'
CLR_RESET=$'\e[0m'
CLR_SECTION="${CLR_BOLD}" # section headers
CLR_KEY="${CLR_DIM}" # label column
CLR_VAL="" # value column (plain)
CLR_MUTED="${CLR_DIM}" # <none> / secondary info
CLR_WARN=$'\e[1;33m' # bold yellow for warnings
}
# ── Helpers ───────────────────────────────────────────────────────────────────
die() { echo "clc: error: $*" >&2; exit 1; }
need_cmd() { command -v "$1" &>/dev/null || die "'$1' not found on PATH"; }
# Shorten a path by replacing $HOME prefix with ~.
short_path() { echo "~${1#${HOME}}"; }
# Print a section header with optional subtitle on the same line.
print_header() {
local heading="$1" subtitle="${2-}"
if [[ -n "${subtitle}" ]]; then
echo "${CLR_BOLD}${heading}${CLR_RESET} (${subtitle})"
else
echo "${CLR_BOLD}${heading}${CLR_RESET}"
fi
}
# ── Claude-file state detection ───────────────────────────────────────────────
# Exact patterns we look for in ignore files (slashes significant).
CLC_PAT_MD="CLAUDE.md"
CLC_PAT_DIR="/.claude/"
# Return 0 if any Claude-related files are tracked by git in the given worktree.
claude_files_tracked() {
local wt="$1"
git -C "${wt}" ls-files -- "CLAUDE.md" "*/CLAUDE.md" ".claude" 2>/dev/null | grep -q .
}
# Echo "yes", "partial", or "no" based on exact-line presence of both/one/neither
# CLC pattern in .git/info/exclude (uncommented = exact match, no leading #).
claude_local_ignore_state() {
local main_gitdir="$1"
local exclude_file="${main_gitdir}/info/exclude"
local has_md=0 has_dir=0
if [[ -f "${exclude_file}" ]]; then
grep -qxF "${CLC_PAT_MD}" "${exclude_file}" 2>/dev/null && has_md=1
grep -qxF "${CLC_PAT_DIR}" "${exclude_file}" 2>/dev/null && has_dir=1
fi
if [[ ${has_md} -eq 1 && ${has_dir} -eq 1 ]]; then echo "yes"
elif [[ ${has_md} -eq 1 || ${has_dir} -eq 1 ]]; then echo "partial"
else echo "no"
fi
}
# Return 0 if any CLC pattern appears as an uncommented exact line in root .gitignore.
claude_in_gitignore() {
local wt="$1"
local gitignore="${wt}/.gitignore"
[[ -f "${gitignore}" ]] || return 1
grep -qxF "${CLC_PAT_MD}" "${gitignore}" 2>/dev/null && return 0
grep -qxF "${CLC_PAT_DIR}" "${gitignore}" 2>/dev/null && return 0
return 1
}
# Print a warning line subordinate to the line above it. Args: warning messages.
print_warning_line() {
[[ $# -eq 0 ]] && return
local msg="$1"; shift
for w in "$@"; do msg+="; ${w}"; done
printf " %s%s%s\n" "${CLR_WARN}" "${msg}" "${CLR_RESET}"
}
# ── Git helpers ───────────────────────────────────────────────────────────────
# Resolve the main .git directory for the repo containing $PWD.
# For a peer worktree this is the commondir (the main repo's .git), not the worktree's .git file.
git_main_gitdir() {
local git_dir common_dir
git_dir=$(git rev-parse --git-dir 2>/dev/null) || return 1
# Peer worktrees have a commondir file pointing to the main .git
if [[ -f "${git_dir}/commondir" ]]; then
common_dir=$(cat "${git_dir}/commondir")
# commondir may be relative to git_dir
if [[ "${common_dir}" != /* ]]; then
common_dir="${git_dir}/${common_dir}"
fi
realpath "${common_dir}"
else
realpath "${git_dir}"
fi
}
# Absolute path of the main worktree root given its .git directory path.
# For submodules the gitdir lives inside the parent's .git/modules/, so
# dirname would be wrong. core.worktree in the gitdir config points back
# to the real working directory; regular repos don't set it, so dirname
# remains the fallback.
git_main_worktree() {
local main_gitdir="$1"
local worktree
worktree=$(git config -f "${main_gitdir}/config" core.worktree 2>/dev/null)
if [[ -n "${worktree}" ]]; then
# core.worktree may be relative to the gitdir
if [[ "${worktree}" != /* ]]; then
worktree="${main_gitdir}/${worktree}"
fi
realpath "${worktree}"
else
dirname "${main_gitdir}"
fi
}
# Absolute path of the current worktree root (the worktree $PWD belongs to).
git_current_worktree() {
git rev-parse --show-toplevel 2>/dev/null
}
# ── Managed-worktree helpers ──────────────────────────────────────────────────
# List all worktrees for the repo.
# Prints tab-separated lines: <type>\t<name>\t<path>\t<branch>
# type = "main" | "peer" | "unmanaged"
# name = "main" for main; suffix after "<base>-" for peers; empty for unmanaged
# branch = branch name, "<detached>", or "<unknown>"
list_all_worktrees() {
local main_worktree="$1"
local parent base
parent=$(dirname "${main_worktree}")
base=$(basename "${main_worktree}")
# git worktree list output: <path> <hash> [<branch>] (or "(HEAD detached ...)")
while IFS= read -r line; do
local wt_path wt_branch
wt_path=$(awk '{print $1}' <<< "${line}")
if [[ "${line}" =~ \[([^\]]+)\] ]]; then
wt_branch="${BASH_REMATCH[1]}"
elif [[ "${line}" =~ \(detached\ HEAD ]]; then
wt_branch="<detached>"
else
wt_branch="<unknown>"
fi
# Dirty if the worktree has any staged or unstaged changes
local wt_dirty=""
[[ -n "$(git -C "${wt_path}" status --porcelain 2>/dev/null)" ]] && wt_dirty="dirty"
if [[ "${wt_path}" == "${main_worktree}" ]]; then
printf '%s\n' "main"$'\002'"main"$'\002'"${wt_path}"$'\002'"${wt_branch}"$'\002'"${wt_dirty}"
elif [[ "${wt_path}" == "${parent}/${base}-"* ]]; then
local wt_name="${wt_path##*/${base}-}"
printf '%s\n' "peer"$'\002'"${wt_name}"$'\002'"${wt_path}"$'\002'"${wt_branch}"$'\002'"${wt_dirty}"
else
printf '%s\n' "unmanaged"$'\002\002'"${wt_path}"$'\002'"${wt_branch}"$'\002'"${wt_dirty}"
fi
done < <(git -C "${main_worktree}" worktree list 2>/dev/null)
}
# ── Claude-file helpers ───────────────────────────────────────────────────────
# Return 0 if a relative path (file or dir) in the given worktree is git-managed:
# tracked/staged, or untracked but not ignored (visible to git).
_claude_item_git_managed() {
local wt="$1" rel="${2%/}" # strip trailing slash for git path matching
git -C "${wt}" ls-files -- "${rel}" 2>/dev/null | grep -q . && return 0
git -C "${wt}" ls-files --others --exclude-standard -- "${rel}" 2>/dev/null | grep -q . && return 0
return 1
}
# ── Storage helpers ───────────────────────────────────────────────────────────
# Cross-platform md5 hash of a string.
md5_str() {
if command -v md5sum &>/dev/null; then
printf '%s' "$1" | md5sum | awk '{print $1}'
else
printf '%s' "$1" | md5 -q
fi
}
# Return the base save directory for a repo: ~/.clc/saved/<name>@<md5-of-path>
repo_save_base() {
local resolved; resolved=$(realpath "$1")
echo "${CLC_STORE}/saved/$(basename "${resolved}")@$(md5_str "${resolved}")"
}
# Print relative paths of all Claude files in a directory (sorted, unique).
collect_claude_files_in_dir() {
local base="$1"
local -a results=()
if [[ -d "${base}/.claude" ]]; then
while IFS= read -r f; do results+=("${f#${base}/}"); done \
< <(find "${base}/.claude" -type f 2>/dev/null | sort)
fi
while IFS= read -r f; do results+=("${f#${base}/}"); done \
< <(_find_claude_md_files "${base}")
[[ ${#results[@]} -eq 0 ]] && return
printf '%s\n' "${results[@]}" | sort -u
}
# Find CLAUDE.md files in a directory, excluding .git internals and submodule directories.
# Uses -prune so find never descends into excluded dirs (faster in repos with large submodules).
_find_claude_md_files() {
local base="$1"
local -a prune=(-name ".git")
while IFS= read -r sm_path; do
[[ -n "${sm_path}" ]] && prune+=(-o -path "${base}/${sm_path}")
done < <(git -C "${base}" submodule status --recursive 2>/dev/null | awk '{print $2}')
find "${base}" \( "${prune[@]}" \) -prune -o \
-name "CLAUDE.md" -type f -print 2>/dev/null | sort
}
# Return the most recent timestamp subdirectory under save_base, or empty string.
latest_save_dir() {
local save_base="$1"
[[ -d "${save_base}" ]] || return 0
local latest; latest=$(ls "${save_base}" 2>/dev/null | grep -E '^[0-9]+$' | sort -n | tail -1)
[[ -n "${latest}" ]] && echo "${save_base}/${latest}"
}
# Global arrays populated by _compare_claude_files.
_CMP_ONLY_STORAGE=()
_CMP_DIFFERENT=()
_CMP_ONLY_WORKTREE=()
_CMP_SAME=()
# Populate the four _CMP_* globals by comparing worktree wt against save_dir.
_compare_claude_files() {
local wt="$1" save_dir="$2"
_CMP_ONLY_STORAGE=()
_CMP_DIFFERENT=()
_CMP_ONLY_WORKTREE=()
_CMP_SAME=()
local tmp_wt tmp_storage
tmp_wt=$(mktemp) tmp_storage=$(mktemp)
collect_claude_files_in_dir "${wt}" > "$tmp_wt"
collect_claude_files_in_dir "${save_dir}" > "$tmp_storage"
while IFS= read -r f; do _CMP_ONLY_STORAGE+=("$f"); done < <(comm -23 "$tmp_storage" "$tmp_wt")
while IFS= read -r f; do _CMP_ONLY_WORKTREE+=("$f"); done < <(comm -13 "$tmp_storage" "$tmp_wt")
while IFS= read -r f; do
if cmp -s "${wt}/${f}" "${save_dir}/${f}"; then
_CMP_SAME+=("$f")
else
_CMP_DIFFERENT+=("$f")
fi
done < <(comm -12 "$tmp_storage" "$tmp_wt")
rm -f "$tmp_wt" "$tmp_storage"
}
# Apply restore from save_dir into wt using pre-populated _CMP_* globals.
# Prompts only for destructive operations (different content, file only in worktree).
# Non-destructive additions (file only in storage) are applied silently.
# Returns 1 if user aborts; 0 on success.
_apply_restore() {
local wt="$1" save_dir="$2"
local destructive_diffs=$(( ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} ))
_print_compare_output
if [[ ${destructive_diffs} -gt 0 ]]; then
printf "\nSynchronize? (Data loss possible!) [y/N] "
read -r response || response="n"
echo
if [[ ! "${response}" =~ ^[Yy]$ ]]; then
echo "Aborted."
return 1
fi
fi
for f in ${_CMP_ONLY_STORAGE[@]+"${_CMP_ONLY_STORAGE[@]}"}; do
mkdir -p "$(dirname "${wt}/${f}")"
cp "${save_dir}/${f}" "${wt}/${f}"
done
for f in ${_CMP_DIFFERENT[@]+"${_CMP_DIFFERENT[@]}"}; do
mkdir -p "$(dirname "${wt}/${f}")"
cp "${save_dir}/${f}" "${wt}/${f}"
done
for f in ${_CMP_ONLY_WORKTREE[@]+"${_CMP_ONLY_WORKTREE[@]}"}; do
rm -f "${wt}/${f}"
done
echo "Synchronized."
}
# Print compare diff sections using the current _CMP_* globals.
_print_compare_output() {
print_header "Compare"
if [[ ${#_CMP_ONLY_STORAGE[@]} -gt 0 ]]; then
echo " Exists in storage only:"
for f in "${_CMP_ONLY_STORAGE[@]}"; do printf " + %s\n" "$f"; done
fi
if [[ ${#_CMP_DIFFERENT[@]} -gt 0 ]]; then
echo " Different content:"
for f in "${_CMP_DIFFERENT[@]}"; do printf " ~ %s\n" "$f"; done
fi
if [[ ${#_CMP_ONLY_WORKTREE[@]} -gt 0 ]]; then
echo " Exists in worktree only:"
for f in "${_CMP_ONLY_WORKTREE[@]}"; do printf " - %s\n" "$f"; done
fi
}
# ── Commands ──────────────────────────────────────────────────────────────────
cmd_save() {
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
current_worktree=$(git_current_worktree) \
|| die "unable to determine current worktree"
local save_base; save_base=$(repo_save_base "${main_worktree}")
local -a files=()
while IFS= read -r f; do files+=("$f"); done \
< <(collect_claude_files_in_dir "${current_worktree}")
local dest_dir="${save_base}/$(date +%s)"
mkdir -p "${dest_dir}"
# Record the full path used for the hash, for discoverability when browsing storage.
printf '%s\n' "$(realpath "${main_worktree}")" > "${save_base}/full-path.txt"
for f in ${files[@]+"${files[@]}"}; do
mkdir -p "$(dirname "${dest_dir}/${f}")"
cp "${current_worktree}/${f}" "${dest_dir}/${f}"
done
print_header "Saved"
printf " %s\n" "$(short_path "${dest_dir}")"
printf " %d file(s)\n" "${#files[@]}"
}
cmd_compare() {
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
current_worktree=$(git_current_worktree) \
|| die "unable to determine current worktree"
local save_base; save_base=$(repo_save_base "${main_worktree}")
local save_dir; save_dir=$(latest_save_dir "${save_base}")
[[ -n "${save_dir}" ]] || die "no saved state found — run 'clc save' first"
_compare_claude_files "${current_worktree}" "${save_dir}"
local total=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} + ${#_CMP_SAME[@]} ))
local diffs=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} ))
if [[ ${diffs} -eq 0 ]]; then
echo "All ${total} Claude file(s) in current worktree are in sync with storage."
return 0
fi
_print_compare_output
echo
echo "Run 'clc save' to save current state; run 'clc restore' to load saved state."
return 1
}
cmd_diff() {
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
current_worktree=$(git_current_worktree) \
|| die "unable to determine current worktree"
local save_base; save_base=$(repo_save_base "${main_worktree}")
local save_dir; save_dir=$(latest_save_dir "${save_base}")
[[ -n "${save_dir}" ]] || die "no saved state found — run 'clc save' first"
_compare_claude_files "${current_worktree}" "${save_dir}"
local total=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} + ${#_CMP_SAME[@]} ))
local diffs=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} ))
if [[ ${diffs} -eq 0 ]]; then
echo "All ${total} Claude file(s) in current worktree are in sync with storage."
return 0
fi
local -a git_color=()
[[ "${OPT_NO_COLOR}" -eq 1 ]] && git_color=("--no-color")
# Only in storage: file was deleted from worktree — show as deletion
for f in ${_CMP_ONLY_STORAGE[@]+"${_CMP_ONLY_STORAGE[@]}"}; do
git diff --no-index ${git_color[@]+"${git_color[@]}"} -- "${save_dir}/${f}" /dev/null || true
done
# Different content: show storage → worktree delta
for f in ${_CMP_DIFFERENT[@]+"${_CMP_DIFFERENT[@]}"}; do
git diff --no-index ${git_color[@]+"${git_color[@]}"} -- "${save_dir}/${f}" "${current_worktree}/${f}" || true
done
# Only in worktree: new file not yet saved — show as addition
for f in ${_CMP_ONLY_WORKTREE[@]+"${_CMP_ONLY_WORKTREE[@]}"}; do
git diff --no-index ${git_color[@]+"${git_color[@]}"} -- /dev/null "${current_worktree}/${f}" || true
done
return 1
}
cmd_restore() {
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
current_worktree=$(git_current_worktree) \
|| die "unable to determine current worktree"
local save_base; save_base=$(repo_save_base "${main_worktree}")
local save_dir; save_dir=$(latest_save_dir "${save_base}")
[[ -n "${save_dir}" ]] || die "no saved state found — run 'clc save' first"
_compare_claude_files "${current_worktree}" "${save_dir}"
local total=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} + ${#_CMP_SAME[@]} ))
local diffs=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} ))
if [[ ${diffs} -eq 0 ]]; then
echo "All ${total} Claude file(s) in current worktree are in sync with storage."
return 0
fi
_apply_restore "${current_worktree}" "${save_dir}"
}
cmd_new() {
local opt_no_claude=0 full_name="" branch=""
while [[ $# -gt 0 ]]; do
case "$1" in
-n|--no-claude) opt_no_claude=1 ;;
-*) die "unknown option for 'new': $1" ;;
*) if [[ -z "${full_name}" ]]; then full_name="$1"
elif [[ -z "${branch}" ]]; then branch="$1"
else die "unexpected argument: $1"
fi ;;
esac
shift
done
[[ -n "${full_name}" ]] || die "usage: clc new [-n|--no-claude] <name> [<branch>]"
# Derive worktree name: last slash-component, then strip leading ticket prefix.
local name="${full_name##*/}"
if [[ "${name}" =~ ^[A-Z]+-[0-9]+[-_]+(.+)$ ]]; then
name="${BASH_REMATCH[1]}"
fi
[[ "${name}" =~ ^[a-zA-Z0-9]+([-_][a-zA-Z0-9]+)*$ ]] \
|| die "invalid worktree name derived from '${full_name}': '${name}'"
# Branch: explicit arg → full first arg.
[[ -z "${branch}" ]] && branch="${full_name}"
local main_gitdir main_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
local parent base new_path
parent=$(dirname "${main_worktree}")
base=$(basename "${main_worktree}")
new_path="${parent}/${base}-${name}"
[[ -e "${new_path}" ]] && die "directory already exists: ${new_path}"
# Check out existing branch or create a new one.
if git -C "${main_worktree}" rev-parse --verify "refs/heads/${branch}" >/dev/null 2>&1; then
git -C "${main_worktree}" worktree add "${new_path}" "${branch}" >/dev/null 2>&1 \
|| die "failed to create worktree '${name}' on branch '${branch}' (already checked out elsewhere?)"
else
git -C "${main_worktree}" worktree add "${new_path}" -b "${branch}" >/dev/null 2>&1 \
|| die "failed to create worktree '${name}' with new branch '${branch}'"
fi
print_header "Created"
printf " %s %s(%s)%s\n" "$(short_path "${new_path}")" "${CLR_MUTED}" "${branch}" "${CLR_RESET}"
echo
if [[ ${opt_no_claude} -eq 0 ]]; then
local save_base; save_base=$(repo_save_base "${main_worktree}")
local save_dir; save_dir=$(latest_save_dir "${save_base}")
if [[ -n "${save_dir}" ]]; then
_compare_claude_files "${new_path}" "${save_dir}"
local total=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} + ${#_CMP_SAME[@]} ))
local diffs=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} ))
if [[ ${diffs} -eq 0 ]]; then
echo "All ${total} Claude file(s) in new worktree are in sync with storage."
echo
else
_apply_restore "${new_path}" "${save_dir}" || true
echo
fi
else
echo "${CLR_MUTED}(no saved state — run 'clc save' to save Claude files first)${CLR_RESET}"
echo
fi
fi
cmd_status
}
cmd_rm() {
local opt_keep_branch=0 name=""
while [[ $# -gt 0 ]]; do
case "$1" in
-k|--keep-branch) opt_keep_branch=1 ;;
-*) die "unknown option for 'rm': $1" ;;
*) if [[ -z "${name}" ]]; then name="$1"
else die "unexpected argument: $1"
fi ;;
esac
shift
done
[[ -n "${name}" ]] || die "usage: clc rm [-k|--keep-branch] <name>"
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
current_worktree=$(git_current_worktree) \
|| die "unable to determine current worktree"
# Find the peer by name.
local wt_path="" wt_branch="" wt_dirty=""
while IFS=$'\002' read -r type row_name path branch dirty; do
if [[ "${type}" == "peer" && "${row_name}" == "${name}" ]]; then
wt_path="${path}"; wt_branch="${branch}"; wt_dirty="${dirty}"
fi
done < <(list_all_worktrees "${main_worktree}")
[[ -n "${wt_path}" ]] || die "no managed peer worktree named '${name}'"
[[ "${wt_path}" != "${current_worktree}" ]] || die "cannot remove current worktree '${name}'"
[[ -z "${wt_dirty}" ]] || die "worktree '${name}' has uncommitted changes"
git -C "${main_worktree}" worktree remove "${wt_path}" >/dev/null 2>&1 \
|| die "failed to remove worktree '${name}'"
[[ -d "${wt_path}" ]] && rm -rf "${wt_path}"
print_header "Removed"
printf " %s %s(%s)%s\n" "$(short_path "${wt_path}")" "${CLR_MUTED}" "${wt_branch}" "${CLR_RESET}"
if [[ ${opt_keep_branch} -eq 0 ]]; then
local branch_sha
branch_sha=$(git -C "${main_worktree}" rev-parse "${wt_branch}" 2>/dev/null || true)
if git -C "${main_worktree}" branch -d "${wt_branch}" >/dev/null 2>&1; then
printf " %sbranch deleted%s\n" "${CLR_MUTED}" "${CLR_RESET}"
printf " %sgit branch %s %s%s\n" "${CLR_MUTED}" "${wt_branch}" "${branch_sha}" "${CLR_RESET}"
else
print_warning_line "branch '${wt_branch}' not deleted — not fully merged"
fi
fi
echo
cmd_status
}
cmd_prune() {
local opt_keep_branch=0
while [[ $# -gt 0 ]]; do
case "$1" in
-k|--keep-branch) opt_keep_branch=1 ;;
-*) die "unknown option for 'prune': $1" ;;
*) die "unexpected argument: $1" ;;
esac
shift
done
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
current_worktree=$(git_current_worktree) \
|| die "unable to determine current worktree"
# Collect eligible peers first so we can print "(nothing to prune)" before touching anything.
local -a to_remove=()
while IFS=$'\002' read -r type name path branch dirty; do
[[ "${type}" == "peer" ]] || continue
[[ "${path}" != "${current_worktree}" ]] || continue
[[ -z "${dirty}" ]] || continue
to_remove+=("${name}"$'\002'"${path}"$'\002'"${branch}")
done < <(list_all_worktrees "${main_worktree}")
print_header "Pruned"
if [[ ${#to_remove[@]} -eq 0 ]]; then
echo " ${CLR_MUTED}(nothing to prune)${CLR_RESET}"
else
for row in "${to_remove[@]}"; do
local r_name r_path r_branch
IFS=$'\002' read -r r_name r_path r_branch <<< "${row}"
local r_sha
r_sha=$(git -C "${main_worktree}" rev-parse "${r_branch}" 2>/dev/null || true)
git -C "${main_worktree}" worktree remove "${r_path}" >/dev/null 2>&1 \
|| die "failed to remove worktree '${r_name}'"
[[ -d "${r_path}" ]] && rm -rf "${r_path}"
echo " - ${r_name} ${CLR_MUTED}(${r_branch})${CLR_RESET}"
if [[ ${opt_keep_branch} -eq 0 ]]; then
if git -C "${main_worktree}" branch -d "${r_branch}" >/dev/null 2>&1; then
printf " %sbranch deleted%s\n" "${CLR_MUTED}" "${CLR_RESET}"
printf " %sgit branch %s %s%s\n" "${CLR_MUTED}" "${r_branch}" "${r_sha}" "${CLR_RESET}"
else
print_warning_line "branch '${r_branch}' not deleted — not fully merged"
fi
fi
done
fi
echo
cmd_status
}
cmd_ignore() {
local main_gitdir
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
local exclude_file="${main_gitdir}/info/exclude"
mkdir -p "${main_gitdir}/info"
[[ -f "${exclude_file}" ]] || touch "${exclude_file}"
local -a added=()
for pat in "${CLC_PAT_MD}" "${CLC_PAT_DIR}"; do
if ! grep -qxF "${pat}" "${exclude_file}" 2>/dev/null; then
echo "${pat}" >> "${exclude_file}"
added+=("${pat}")
fi
done
print_header "Ignored"
if [[ ${#added[@]} -eq 0 ]]; then
echo " ${CLR_MUTED}(already up to date)${CLR_RESET}"
else
for pat in "${added[@]}"; do echo " + ${pat}"; done
fi
echo
cmd_status
}
cmd_unignore() {
local main_gitdir
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
local exclude_file="${main_gitdir}/info/exclude"
local -a removed=()
if [[ -f "${exclude_file}" ]]; then
for pat in "${CLC_PAT_MD}" "${CLC_PAT_DIR}"; do
if grep -qxF "${pat}" "${exclude_file}" 2>/dev/null; then
grep -vxF "${pat}" "${exclude_file}" > "${exclude_file}.tmp" || true
mv "${exclude_file}.tmp" "${exclude_file}"
removed+=("${pat}")
fi
done
fi
print_header "Unignored"
if [[ ${#removed[@]} -eq 0 ]]; then
echo " ${CLR_MUTED}(nothing to remove)${CLR_RESET}"
else
for pat in "${removed[@]}"; do echo " - ${pat}"; done
fi
echo
cmd_status
}
cmd_ls() {
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
current_worktree=$(git_current_worktree) \
|| die "unable to determine current worktree"
# Show a transient "Searching..." prompt on TTY so the user knows work is happening.
# Skipped when stdout is not a TTY (pipes, test capture) — output stays clean.
[[ -t 1 ]] && printf "Searching..."
local -a items=()
# .claude/ at worktree root
[[ -d "${current_worktree}/.claude" ]] && items+=(".claude/")
# All CLAUDE.md files at any depth, sorted by path
while IFS= read -r abs_path; do
items+=("${abs_path#${current_worktree}/}")
done < <(_find_claude_md_files "${current_worktree}")
# Clear the "Searching..." line, then print the real header
[[ -t 1 ]] && printf "\r\033[K"
print_header "Claude files"
if [[ ${#items[@]} -eq 0 ]]; then
echo " ${CLR_MUTED}<none>${CLR_RESET}"
else
for rel in "${items[@]}"; do
if _claude_item_git_managed "${current_worktree}" "${rel}"; then
printf " %s!%s %s%s%s\n" "${CLR_WARN}" "${CLR_RESET}" "${CLR_WARN}" "${rel}" "${CLR_RESET}"
else
printf " %s %s(properly ignored)%s\n" "${rel}" "${CLR_MUTED}" "${CLR_RESET}"
fi
done
fi
# Storage comparison
local save_base; save_base=$(repo_save_base "${main_worktree}")
local save_dir; save_dir=$(latest_save_dir "${save_base}")
echo
if [[ -z "${save_dir}" ]]; then
echo "${CLR_MUTED}(no saved state — run 'clc save')${CLR_RESET}"
else
_compare_claude_files "${current_worktree}" "${save_dir}"
local total=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} + ${#_CMP_SAME[@]} ))
local diffs=$(( ${#_CMP_ONLY_STORAGE[@]} + ${#_CMP_DIFFERENT[@]} + ${#_CMP_ONLY_WORKTREE[@]} ))
if [[ ${diffs} -eq 0 ]]; then
echo "All ${total} Claude file(s) are in sync with storage."
else
_print_compare_output
echo
echo "Run 'clc save' to save current state; run 'clc restore' to load saved state."
fi
fi
}
cmd_status() {
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") \
|| die "unable to determine main worktree"
current_worktree=$(git_current_worktree) \
|| die "unable to determine current worktree"
# ── Claude-file state for current worktree ────────────────────────────────
local state_tracked=0 state_ignore state_gitignore=0
claude_files_tracked "${current_worktree}" && state_tracked=1
state_ignore=$(claude_local_ignore_state "${main_gitdir}")
claude_in_gitignore "${current_worktree}" && state_gitignore=1
# Warning buckets: main-worktree-level vs current-worktree-level.
local -a main_warnings=() cur_warnings=()
[[ "${state_ignore}" == "no" ]] && main_warnings+=("Claude files not ignored")
[[ "${state_ignore}" == "partial" ]] && main_warnings+=("Claude files only partially ignored")
[[ ${state_tracked} -eq 1 ]] && cur_warnings+=("Claude files detected")
[[ ${state_gitignore} -eq 1 ]] && cur_warnings+=("Claude files in .gitignore")
# Collect worktrees by category
local main_branch="<unknown>"
local -a peer_rows=() unmanaged_rows=()
local max_peer_name_len=0
local main_dirty=""
while IFS=$'\002' read -r type name path branch dirty; do
case "${type}" in
main) main_branch="${branch}"; main_dirty="${dirty}" ;;
peer) peer_rows+=("${name}"$'\002'"${path}"$'\002'"${branch}"$'\002'"${dirty}")
[[ ${#name} -gt ${max_peer_name_len} ]] && max_peer_name_len=${#name} ;;
unmanaged) unmanaged_rows+=("${path}"$'\002'"${branch}"$'\002'"${dirty}") ;;
esac
done < <(list_all_worktrees "${main_worktree}")
# Parent dir is shared by all managed worktrees; printed once in section 1.
local parent_dir_abs parent_dir_disp
parent_dir_abs=$(dirname "${main_worktree}")
parent_dir_disp=$(short_path "${parent_dir_abs}")
# Compute max visible content width across all sections for branch alignment.
# Use basename for main worktree and short names for peers (already names).
local main_name; main_name=$(basename "${main_worktree}")
local max_content_len=${#main_name}
[[ ${max_peer_name_len} -gt ${max_content_len} ]] && max_content_len=${max_peer_name_len}
for row in ${unmanaged_rows[@]+"${unmanaged_rows[@]}"}; do
local u_path u_branch u_display
IFS=$'\002' read -r u_path u_branch <<< "${row}"
if [[ "${u_path}" == "${parent_dir_abs}/"* ]]; then
u_display="${u_path##${parent_dir_abs}/}"
else
u_display=$(short_path "${u_path}")
fi
[[ ${#u_display} -gt ${max_content_len} ]] && max_content_len=${#u_display}
done
# Section 1: Repository & main worktree
print_header "Repository" "parent dir: ${parent_dir_disp}"
local main_pad
main_pad=$(( max_content_len - ${#main_name} ))
local main_dirty_suffix=""
[[ -n "${main_dirty}" ]] && main_dirty_suffix=" ${CLR_MUTED}(dirty)${CLR_RESET}"
if [[ "${main_worktree}" == "${current_worktree}" ]]; then
printf " ${CLR_BOLD}*${CLR_RESET} ${CLR_BOLD}%-*s${CLR_RESET} ${CLR_MUTED}(%s)${CLR_RESET}%s\n" \
"${max_content_len}" "${main_name}" "${main_branch}" "${main_dirty_suffix}"
# Combine main-level and current-level warnings (same line is both).
local -a combined_warnings=()
[[ ${#main_warnings[@]} -gt 0 ]] && combined_warnings+=("${main_warnings[@]}")
[[ ${#cur_warnings[@]} -gt 0 ]] && combined_warnings+=("${cur_warnings[@]}")
if [[ ${#combined_warnings[@]} -gt 0 ]]; then print_warning_line "${combined_warnings[@]}"; fi
else
printf " %-*s ${CLR_MUTED}(%s)${CLR_RESET}%s\n" \
"${max_content_len}" "${main_name}" "${main_branch}" "${main_dirty_suffix}"
if [[ ${#main_warnings[@]} -gt 0 ]]; then print_warning_line "${main_warnings[@]}"; fi
fi
# Section 2: Managed worktrees
echo
print_header "Managed worktrees"
if [[ ${#peer_rows[@]} -eq 0 ]]; then
echo " ${CLR_MUTED}<none>${CLR_RESET}"
else
for row in "${peer_rows[@]}"; do
local name path branch dirty dirty_suffix
IFS=$'\002' read -r name path branch dirty <<< "${row}"
dirty_suffix=""
[[ -n "${dirty}" ]] && dirty_suffix=" ${CLR_MUTED}(dirty)${CLR_RESET}"
if [[ "${path}" == "${current_worktree}" ]]; then
printf " ${CLR_BOLD}*${CLR_RESET} ${CLR_BOLD}%-*s${CLR_RESET} ${CLR_MUTED}(%s)${CLR_RESET}%s\n" \
"${max_content_len}" "${name}" "${branch}" "${dirty_suffix}"
if [[ ${#cur_warnings[@]} -gt 0 ]]; then print_warning_line "${cur_warnings[@]}"; fi
else
printf " %-*s ${CLR_MUTED}(%s)${CLR_RESET}%s\n" \
"${max_content_len}" "${name}" "${branch}" "${dirty_suffix}"
fi
done
fi
# Section 3: Unmanaged worktrees
echo
print_header "Unmanaged worktrees"
if [[ ${#unmanaged_rows[@]} -eq 0 ]]; then
echo " ${CLR_MUTED}<none>${CLR_RESET}"
else
for row in "${unmanaged_rows[@]}"; do
local path branch dirty dirty_suffix u_disp
IFS=$'\002' read -r path branch dirty <<< "${row}"
dirty_suffix=""
[[ -n "${dirty}" ]] && dirty_suffix=" ${CLR_MUTED}(dirty)${CLR_RESET}"
if [[ "${path}" == "${parent_dir_abs}/"* ]]; then
u_disp="${path##${parent_dir_abs}/}"
else
u_disp=$(short_path "${path}")
fi
if [[ "${path}" == "${current_worktree}" ]]; then
printf " ${CLR_BOLD}*${CLR_RESET} %-*s ${CLR_MUTED}(%s)${CLR_RESET}%s\n" \
"${max_content_len}" "${u_disp}" "${branch}" "${dirty_suffix}"
if [[ ${#cur_warnings[@]} -gt 0 ]]; then print_warning_line "${cur_warnings[@]}"; fi
else
printf " %-*s ${CLR_MUTED}(%s)${CLR_RESET}%s\n" \
"${max_content_len}" "${u_disp}" "${branch}" "${dirty_suffix}"
fi
done
fi
}
# ── Transplant ────────────────────────────────────────────────────────────────
# Internal helper for pull/close. Performs sanity checks, optional rebase, and
# merge --squash. Sets _PULL_WT_PATH, _PULL_WT_BRANCH, _PULL_FILE_COUNT for
# the caller. Does NOT commit or remove.
_do_pull() {
local cmd="$1" name="$2"
# ── resolve context ──────────────────────────────────────────────────
local main_gitdir main_worktree current_worktree
main_gitdir=$(git_main_gitdir) || die "not inside a Git repository"
main_worktree=$(git_main_worktree "${main_gitdir}") || die "unable to determine main worktree"
current_worktree=$(git_current_worktree) || die "unable to determine current worktree"
# ── sanity checks (all read-only, no mutations) ──────────────────────
# 1. Must be in main worktree.
[[ "${current_worktree}" == "${main_worktree}" ]] \
|| die "must be run from the main worktree (currently in '$(short_path "${current_worktree}")')"
# 2. Find peer by name.
local wt_path="" wt_branch="" wt_dirty=""
while IFS=$'\002' read -r type row_name path branch dirty; do
if [[ "${type}" == "peer" && "${row_name}" == "${name}" ]]; then
wt_path="${path}"; wt_branch="${branch}"; wt_dirty="${dirty}"
fi
done < <(list_all_worktrees "${main_worktree}")
[[ -n "${wt_path}" ]] || die "no managed peer worktree named '${name}'"
# 3. Main worktree is clean.
[[ -z "$(git -C "${main_worktree}" status --porcelain)" ]] \
|| die "main worktree has uncommitted changes — commit or stash first"
# 4. Peer worktree is clean.
[[ -z "${wt_dirty}" ]] || die "worktree '${name}' has uncommitted changes — commit first"
# 5. Peer is not on a detached HEAD.
[[ -n "${wt_branch}" && "${wt_branch}" != "(detached)" ]] \
|| die "peer '${name}' is on a detached HEAD"
# 6. Resolve branches and verify relationship.
local primary_branch primary_tip peer_tip merge_base
primary_branch=$(git -C "${main_worktree}" symbolic-ref --short HEAD)
primary_tip=$(git -C "${main_worktree}" rev-parse HEAD)
peer_tip=$(git -C "${main_worktree}" rev-parse "${wt_branch}")
merge_base=$(git -C "${main_worktree}" merge-base "${primary_tip}" "${wt_branch}" 2>/dev/null) \
|| die "branches '${primary_branch}' and '${wt_branch}' share no common history"
# 7. Something to transplant.
[[ "${primary_tip}" != "${peer_tip}" ]] \
|| die "nothing to transplant — '${wt_branch}' is identical to '${primary_branch}'"
# ── step 1: rebase peer if needed ────────────────────────────────────
local did_rebase=0
if [[ "${merge_base}" != "${primary_tip}" ]]; then
print_header "Rebasing"
printf " %s onto %s\n\n" "${wt_branch}" "${primary_branch}"
local rebase_out
if rebase_out=$(git ${GIT_SIGN[@]+"${GIT_SIGN[@]}"} -C "${wt_path}" rebase "${primary_branch}" 2>&1); then
: # success — output suppressed
else
git -C "${wt_path}" rebase --abort 2>/dev/null || true
printf "%s\n\n" "${rebase_out}"
die "rebase failed due to conflicts — both worktrees are clean.
To proceed manually:
cd $(short_path "${wt_path}") && git rebase ${primary_branch}
# resolve conflicts, then: git rebase --continue
cd $(short_path "${main_worktree}") && clc ${cmd} ${name}"
fi
did_rebase=1
fi
# ── step 2: transplant via merge --squash ────────────────────────────
git -C "${main_worktree}" merge --squash "${wt_branch}" >/dev/null 2>&1 \
|| die "merge --squash failed unexpectedly"
local file_count
file_count=$(git -C "${main_worktree}" diff --cached --name-only | wc -l | tr -d ' ')
print_header "Pulled"
printf " %s → %s\n" "${wt_branch}" "${primary_branch}"
if [[ ${did_rebase} -eq 1 ]]; then
printf " %sRebased onto %s%s\n" "${CLR_MUTED}" "${primary_branch}" "${CLR_RESET}"
fi
printf " %s file(s) staged\n" "${file_count}"
# Export state for callers.
_PULL_WT_PATH="${wt_path}"
_PULL_WT_BRANCH="${wt_branch}"
_PULL_FILE_COUNT="${file_count}"
}
cmd_pull() {
local opt_commit=0 name=""
while [[ $# -gt 0 ]]; do
case "$1" in
-c|--commit) opt_commit=1 ;;
-*) die "unknown option for 'pull': $1" ;;
*) if [[ -z "${name}" ]]; then name="$1"
else die "unexpected argument: $1"
fi ;;
esac
shift
done
[[ -n "${name}" ]] || die "usage: clc pull [-c|--commit] <name>"
_do_pull "pull" "${name}"
if [[ ${opt_commit} -eq 1 ]]; then
echo
if ! git ${GIT_SIGN[@]+"${GIT_SIGN[@]}"} commit; then
echo
die "commit aborted — changes remain staged"
fi
else
echo
echo "Changes are staged. Review with 'git diff --cached', then commit when ready."
fi
}
cmd_close() {
local opt_commit=0 opt_keep_branch=0 name=""
while [[ $# -gt 0 ]]; do
case "$1" in
-c|--commit) opt_commit=1 ;;
-k|--keep-branch) opt_keep_branch=1 ;;
-*) die "unknown option for 'close': $1" ;;
*) if [[ -z "${name}" ]]; then name="$1"
else die "unexpected argument: $1"