-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreate-worktree.sh
More file actions
executable file
·1023 lines (858 loc) · 29.2 KB
/
create-worktree.sh
File metadata and controls
executable file
·1023 lines (858 loc) · 29.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
#!/bin/bash
set -e
# Preflight checks for required tools
REQUIRED_TOOLS=(curl docker git jq pnpm uv)
MISSING_TOOLS=()
for tool in "${REQUIRED_TOOLS[@]}"; do
if ! command -v "${tool}" >/dev/null 2>&1; then
MISSING_TOOLS+=("${tool}")
fi
done
if [[ ${#MISSING_TOOLS[@]} -gt 0 ]]; then
echo "ERROR: Required tools not found: ${MISSING_TOOLS[*]}" >&2
echo "Please install the missing tools and try again." >&2
exit 1
fi
TYPE_OPTIONS=(feat change chore fix)
resolve_repo_root() {
git rev-parse --show-toplevel 2>/dev/null || {
echo "ERROR: create-worktree.sh must be run from within a git checkout." >&2
exit 1
}
}
resolve_shared_worktree_root() {
local git_common_dir
local main_repo_root
local repo_parent
local repo_name
git_common_dir="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" || {
echo "ERROR: Could not determine the shared git directory." >&2
exit 1
}
main_repo_root="$(cd "${git_common_dir}/.." && pwd -P)" || exit 1
repo_parent="$(dirname "${main_repo_root}")"
repo_name="$(basename "${main_repo_root}")"
echo "${repo_parent}/${repo_name}-worktrees"
}
usage() {
echo "Usage:" >&2
echo " $0 # prompt for branch type and name" >&2
echo " $0 <name> # prompt for branch type" >&2
echo " $0 <type> <name> # create <github-user>/<type>/<name>" >&2
echo " $0 <user> <type> <name>" >&2
echo " $0 <user>/<type>/<name>" >&2
}
is_valid_worktree_name() {
local value="$1"
[[ "${value}" =~ ^[a-zA-Z0-9][a-zA-Z0-9_/-]*$ ]] \
&& [[ "${value}" != *".."* ]] \
&& [[ "${value}" != *"//"* ]] \
&& [[ "${value}" != */ ]]
}
require_valid_worktree_name() {
local value="$1"
if ! is_valid_worktree_name "${value}"; then
echo "ERROR: Invalid worktree name '${value}'" >&2
echo "Names must start with alphanumeric and contain only letters, numbers, hyphens, underscores, or slashes." >&2
echo "Names cannot contain '..', consecutive slashes, or end with a slash." >&2
exit 1
fi
}
is_valid_branch_type() {
local type="$1"
for option in "${TYPE_OPTIONS[@]}"; do
if [[ "${type}" == "${option}" ]]; then
return 0
fi
done
return 1
}
require_valid_branch_type() {
local type="$1"
if ! is_valid_branch_type "${type}"; then
echo "ERROR: Invalid branch type '${type}'." >&2
echo "Allowed types: ${TYPE_OPTIONS[*]}" >&2
exit 1
fi
}
prompt_branch_type() {
local branch_type
while true; do
read -r -p "Branch type [feat/change/chore/fix]: " branch_type
if is_valid_branch_type "${branch_type}"; then
echo "${branch_type}"
return 0
fi
echo "Please enter one of: ${TYPE_OPTIONS[*]}" >&2
done
}
prompt_branch_name() {
local branch_name
while true; do
read -r -p "Branch name: " branch_name
if ! is_valid_worktree_name "${branch_name}"; then
echo "Names must start with alphanumeric and contain only letters, numbers, hyphens, or underscores." >&2
echo "Names cannot contain '..', slashes, consecutive slashes, or end with a slash." >&2
continue
fi
if [[ "${branch_name}" == *"/"* ]]; then
echo "ERROR: Branch name must be a single path segment. Use hyphens or underscores instead of '/'." >&2
continue
fi
echo "${branch_name}"
return 0
done
}
resolve_github_username() {
local username=""
username="${GITHUB_USERNAME:-}"
if [[ -n "${username}" ]]; then
echo "${username}"
return 0
fi
for key in github.user github.username user.github; do
username="$(git config --get "${key}" 2>/dev/null || true)"
if [[ -n "${username}" ]]; then
echo "${username}"
return 0
fi
done
if command -v gh >/dev/null 2>&1; then
username="$(gh api user -q .login 2>/dev/null || true)"
if [[ -n "${username}" ]]; then
echo "${username}"
return 0
fi
fi
echo "ERROR: Could not determine GitHub username." >&2
echo "Set one of git config keys 'github.user', 'github.username', or 'user.github', export GITHUB_USERNAME, or authenticate with gh." >&2
exit 1
}
build_branch_name() {
local username="$1"
local branch_type="$2"
local branch_name="$3"
echo "${username}/${branch_type}/${branch_name}"
}
build_worktree_name() {
local username="$1"
local branch_type="$2"
local branch_name="$3"
echo "${username}_${branch_type}_${branch_name}"
}
parse_branch_input() {
local username=""
local branch_type=""
local branch_name=""
case "$#" in
0)
username="$(resolve_github_username)"
branch_type="$(prompt_branch_type)"
branch_name="$(prompt_branch_name)"
;;
1)
if [[ "${1}" == */* ]]; then
require_valid_worktree_name "${1}"
IFS='/' read -r username branch_type branch_name extra <<< "${1}"
if [[ -n "${extra:-}" || -z "${username}" || -z "${branch_type}" || -z "${branch_name}" ]]; then
echo "ERROR: Expected branch name in the form <user>/<type>/<name>." >&2
exit 1
fi
else
username="$(resolve_github_username)"
branch_type="$(prompt_branch_type)"
branch_name="${1}"
fi
;;
2)
username="$(resolve_github_username)"
branch_type="${1}"
branch_name="${2}"
;;
3)
username="${1}"
branch_type="${2}"
branch_name="${3}"
;;
*)
usage
exit 1
;;
esac
require_valid_worktree_name "${username}"
if [[ "${username}" == *"/"* ]]; then
echo "ERROR: GitHub username must be a single path segment." >&2
exit 1
fi
require_valid_branch_type "${branch_type}"
require_valid_worktree_name "${branch_name}"
if [[ "${branch_name}" == *"/"* ]]; then
echo "ERROR: Branch name must be a single path segment. Use hyphens or underscores instead of '/'." >&2
exit 1
fi
BRANCH_NAME="$(build_branch_name "${username}" "${branch_type}" "${branch_name}")"
WORKTREE_NAME="$(build_worktree_name "${username}" "${branch_type}" "${branch_name}")"
}
parse_branch_input "$@"
REPO_ROOT="$(resolve_repo_root)"
WORKTREE_ROOT="$(resolve_shared_worktree_root)"
PORTS_FILE="${WORKTREE_ROOT}/.worktree-ports.json"
sanitize_db_suffix() {
local raw="$1"
local lower
local cleaned
local max_len=40
lower="$(printf '%s' "${raw}" | tr '[:upper:]' '[:lower:]')"
cleaned="$(printf '%s' "${lower}" | sed -E 's/[^a-z0-9_]+/_/g; s/^_+//; s/_+$//')"
if [[ -z "${cleaned}" ]]; then
cleaned="branch"
fi
if [[ "${cleaned}" =~ ^[0-9] ]]; then
cleaned="b_${cleaned}"
fi
cleaned="${cleaned:0:${max_len}}"
cleaned="$(printf '%s' "${cleaned}" | sed -E 's/_+$//')"
if [[ -z "${cleaned}" ]]; then
cleaned="branch"
fi
echo "${cleaned}"
}
DB_SUFFIX="$(sanitize_db_suffix "${BRANCH_NAME}")"
WORKTREE_PATH="${WORKTREE_ROOT}/${WORKTREE_NAME}"
DB_NAME="pingpong_${DB_SUFFIX}"
AUTHZ_STORE_NAME="pingpong_${DB_SUFFIX}"
# Parse authz settings from config file
CONFIG_FILE="${CONFIG_FILE:-${REPO_ROOT}/config.local.toml}"
if [[ ! -f "${CONFIG_FILE}" ]]; then
echo "ERROR: Config file not found: ${CONFIG_FILE}" >&2
exit 1
fi
# Extract values from [authz] section of TOML config
get_toml_value() {
local file="$1"
local section="$2"
local key="$3"
local default="$4"
# Find section, then extract key value (handles quotes)
awk -v section="[$section]" -v key="$key" '
$0 == section { in_section=1; next }
/^\[/ { in_section=0 }
in_section && $1 == key && $2 == "=" {
val=$3
for(i=4;i<=NF;i++) val=val" "$i
gsub(/^["'\'']|["'\'']$/, "", val)
print val
exit
}
' "$file" || echo "$default"
}
AUTHZ_SCHEME="$(get_toml_value "${CONFIG_FILE}" "authz" "scheme" "https")"
AUTHZ_HOST="$(get_toml_value "${CONFIG_FILE}" "authz" "host" "localhost")"
AUTHZ_TOKEN="$(get_toml_value "${CONFIG_FILE}" "authz" "key" "devkey")"
# Get authz port from docker-compose.yml (first port in authz service ports mapping)
DOCKER_COMPOSE_FILE="${DOCKER_COMPOSE_FILE:-${REPO_ROOT}/docker-compose.yml}"
if [[ -f "${DOCKER_COMPOSE_FILE}" ]]; then
AUTHZ_PORT="$(awk '/^ authz:/,/^ [a-z]/' "${DOCKER_COMPOSE_FILE}" | grep -E '^\s+ports:' | grep -oE '"[0-9]+:' | head -1 | tr -d '":' || echo "8080")"
[[ -z "${AUTHZ_PORT}" ]] && AUTHZ_PORT="8080"
else
echo "WARNING: Docker compose file not found: ${DOCKER_COMPOSE_FILE}. Using default authz port 8080." >&2
AUTHZ_PORT="8080"
fi
AUTHZ_API="${AUTHZ_SCHEME}://${AUTHZ_HOST}:${AUTHZ_PORT}"
# Track created resources for cleanup on failure
CREATED_DB=false
CREATED_AUTHZ_STORE=false
CREATED_AUTHZ_STORE_ID=""
CREATED_WORKTREE=false
CREATED_BRANCH=false
CREATED_PORTS=false
cleanup_on_failure() {
local exit_code=$?
if [[ ${exit_code} -eq 0 ]]; then
return 0
fi
echo "" >&2
echo "ERROR: Script failed. Cleaning up partially created resources..." >&2
# Clean up in reverse order of creation
if [[ "${CREATED_WORKTREE}" == "true" ]]; then
echo "Removing worktree ${WORKTREE_PATH}..." >&2
git worktree remove --force "${WORKTREE_PATH}" 2>/dev/null || rm -rf "${WORKTREE_PATH}"
git worktree prune 2>/dev/null || true
fi
if [[ "${CREATED_BRANCH}" == "true" ]]; then
echo "Removing branch ${BRANCH_NAME}..." >&2
git branch -D "${BRANCH_NAME}" 2>/dev/null || true
fi
if [[ "${CREATED_AUTHZ_STORE}" == "true" && -n "${CREATED_AUTHZ_STORE_ID}" ]]; then
echo "Removing authz store ${AUTHZ_STORE_NAME}..." >&2
curl -sk -X DELETE -H "Authorization: Bearer ${AUTHZ_TOKEN}" "${AUTHZ_API}/stores/${CREATED_AUTHZ_STORE_ID}" 2>/dev/null || true
fi
if [[ "${CREATED_DB}" == "true" ]]; then
echo "Removing database ${DB_NAME}..." >&2
docker exec pingpong-db psql -Upingpong -c "DROP DATABASE IF EXISTS ${DB_NAME};" 2>/dev/null || true
fi
if [[ "${CREATED_PORTS}" == "true" ]]; then
if [[ -f "${PORTS_FILE}" ]]; then
if acquire_ports_lock; then
tmp_ports="$(mktemp)"
jq --arg name "${WORKTREE_NAME}" 'del(.[$name])' "${PORTS_FILE}" > "${tmp_ports}" \
&& mv "${tmp_ports}" "${PORTS_FILE}" || rm -f "${tmp_ports}"
release_ports_lock
else
echo "WARNING: Could not acquire port lock during cleanup; skipping port reservation cleanup." >&2
fi
fi
fi
echo "Cleanup complete." >&2
exit ${exit_code}
}
trap cleanup_on_failure EXIT
authz_api() {
curl -sk -H "Authorization: Bearer ${AUTHZ_TOKEN}" "$@"
}
get_store_id_by_name() {
local name="$1"
authz_api "${AUTHZ_API}/stores" | jq -r --arg name "${name}" '.stores[] | select(.name == $name) | .id'
}
get_worktree_path_for_name() {
local worktree_name="$1"
local target_path
target_path="${WORKTREE_ROOT}/${worktree_name}"
git worktree list --porcelain 2>/dev/null | awk -v target="${target_path}" '
$1 == "worktree" {
path = $0
sub(/^worktree /, "", path)
}
$1 == "branch" {
if (path == target) {
print path
exit
}
}
'
}
get_worktree_path_for_branch() {
local branch_name="$1"
git worktree list --porcelain 2>/dev/null | awk -v branch="refs/heads/${branch_name}" '
$1 == "worktree" {
path = $0
sub(/^worktree /, "", path)
}
$1 == "branch" && $2 == branch {
print path
exit
}
'
}
get_branch_for_worktree_name() {
local worktree_name="$1"
local target_path
target_path="${WORKTREE_ROOT}/${worktree_name}"
git worktree list --porcelain 2>/dev/null | awk -v target="${target_path}" '
$1 == "worktree" {
path = $0
sub(/^worktree /, "", path)
}
$1 == "branch" {
branch = $2
sub(/^refs\/heads\//, "", branch)
if (path == target) {
print branch
exit
}
}
'
}
get_reserved_branch_for_worktree_name() {
local worktree_name="$1"
if [[ ! -f "${PORTS_FILE}" ]]; then
return 0
fi
jq -r --arg name "${worktree_name}" '.[$name].branch // empty' "${PORTS_FILE}" 2>/dev/null
}
report_worktree_name_collision() {
local owner_branch="$1"
local source="$2"
echo "ERROR: Worktree name '${WORKTREE_NAME}' is already in use." >&2
if [[ -n "${owner_branch}" ]]; then
echo "Branch '${BRANCH_NAME}' would collide with existing branch '${owner_branch}'." >&2
else
echo "Branch '${BRANCH_NAME}' would collide with another worktree using the same derived worktree name." >&2
fi
echo "Shared worktree path: ${WORKTREE_PATH}" >&2
if [[ -n "${source}" ]]; then
echo "Conflict source: ${source}" >&2
fi
echo "Remove the existing worktree with ./remove-worktree.sh <full-branch-name>, or choose a different branch name." >&2
}
ensure_container_running() {
local container_name="$1"
local max_attempts=30
local attempt=1
if ! docker ps -a --format '{{.Names}}' | grep -Fxq "${container_name}"; then
echo "${container_name} container not found. Please run ./start-dev-docker.sh first." >&2
exit 1
fi
if ! docker ps --format '{{.Names}}' | grep -Fxq "${container_name}"; then
echo "Starting ${container_name}..."
docker start "${container_name}" >/dev/null
fi
while true; do
if [[ "$(docker inspect -f '{{.State.Running}}' "${container_name}" 2>/dev/null)" == "true" ]]; then
break
fi
if (( attempt >= max_attempts )); then
echo "${container_name} failed to start. Please run ./start-dev-docker.sh first." >&2
exit 1
fi
attempt=$((attempt + 1))
sleep 1
done
}
wait_for_db_ready() {
local max_attempts=30
local attempt=1
until docker exec pingpong-db pg_isready >/dev/null 2>&1; do
if (( attempt >= max_attempts )); then
echo "Database is not ready. Please run ./start-dev-docker.sh first." >&2
exit 1
fi
attempt=$((attempt + 1))
sleep 1
done
}
wait_for_authz_ready() {
local max_attempts=30
local attempt=1
local response=""
while true; do
response="$(authz_api "${AUTHZ_API}/stores" 2>/dev/null || true)"
if [[ -n "${response}" ]] && echo "${response}" | jq -e '.stores' >/dev/null 2>&1; then
return 0
fi
if (( attempt >= max_attempts )); then
echo "Authz API is not ready after ${max_attempts} attempts." >&2
echo "Recent pingpong-authz logs:" >&2
docker logs --tail 20 pingpong-authz >&2 || true
exit 1
fi
if (( attempt == 1 || attempt % 5 == 0 )); then
echo "Waiting for authz API to become ready (attempt ${attempt}/${max_attempts})..."
fi
attempt=$((attempt + 1))
sleep 1
done
}
ensure_container_running "pingpong-db"
wait_for_db_ready
if docker exec pingpong-db psql -Upingpong -tAc "SELECT 1 FROM pg_database WHERE datname = '${DB_NAME}'" | grep -q 1; then
echo "ERROR: Database ${DB_NAME} already exists." >&2
exit 1
fi
if docker ps -a --format '{{.Names}}' | grep -Fxq "pingpong-authz"; then
if docker ps --format '{{.Names}}' | grep -Fxq "pingpong-authz"; then
echo "Stopping pingpong-authz..."
docker stop pingpong-authz >/dev/null
fi
fi
echo "Cloning database pingpong -> ${DB_NAME}..."
docker exec pingpong-db psql -Upingpong -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'pingpong' AND pid <> pg_backend_pid();"
# Wait for connections to fully terminate before cloning
clone_attempt=0
max_clone_attempts=10
while ! docker exec pingpong-db psql -Upingpong -c "CREATE DATABASE ${DB_NAME} WITH TEMPLATE pingpong;" 2>/dev/null; do
clone_attempt=$((clone_attempt + 1))
if (( clone_attempt >= max_clone_attempts )); then
echo "ERROR: Failed to clone database after ${max_clone_attempts} attempts." >&2
exit 1
fi
echo "Waiting for connections to close (attempt ${clone_attempt}/${max_clone_attempts})..."
sleep 0.5
done
CREATED_DB=true
ensure_container_running "pingpong-authz"
wait_for_authz_ready
# Check if authz store already exists
if authz_api "${AUTHZ_API}/stores" | grep -q "\"name\":\"${AUTHZ_STORE_NAME}\""; then
echo "ERROR: Authz store ${AUTHZ_STORE_NAME} already exists." >&2
exit 1
fi
# Get source store ID
SOURCE_STORE_ID="$(get_store_id_by_name "pingpong")"
if [[ -z "${SOURCE_STORE_ID}" ]]; then
echo "ERROR: Source authz store 'pingpong' not found." >&2
exit 1
fi
# Create new store
NEW_STORE_ID="$(authz_api -X POST "${AUTHZ_API}/stores" \
-H "Content-Type: application/json" \
-d "{\"name\":\"${AUTHZ_STORE_NAME}\"}" | grep -o '"id":"[^"]*"' | head -1 | sed 's/"id":"\([^"]*\)"/\1/')"
if [[ -z "${NEW_STORE_ID}" ]]; then
echo "ERROR: Failed to create authz store ${AUTHZ_STORE_NAME}." >&2
exit 1
fi
CREATED_AUTHZ_STORE=true
CREATED_AUTHZ_STORE_ID="${NEW_STORE_ID}"
echo "Cloning authz store pingpong -> ${AUTHZ_STORE_NAME}..."
WORKDIR="$(mktemp -d)"
MODEL_FILE="${WORKDIR}/model.json"
TUPLES_FILE="${WORKDIR}/tuples.json"
SOURCE_READ_URL="${AUTHZ_API}/stores/${SOURCE_STORE_ID}/read"
DEST_WRITE_URL="${AUTHZ_API}/stores/${NEW_STORE_ID}/write"
SOURCE_MODELS_URL="${AUTHZ_API}/stores/${SOURCE_STORE_ID}/authorization-models"
DEST_MODELS_URL="${AUTHZ_API}/stores/${NEW_STORE_ID}/authorization-models"
AUTH_HEADER="Authorization: Bearer ${AUTHZ_TOKEN}"
JSON_HEADER="Content-Type: application/json"
# ====== 1. Copy latest authorization model ======
echo "Fetching latest authorization model from source store..."
curl -sk \
-H "${AUTH_HEADER}" \
"${SOURCE_MODELS_URL}" \
| jq '.authorization_models[0]' \
> "${MODEL_FILE}"
echo "Writing authorization model to destination store..."
DEST_MODEL_ID=$(
curl -sk -X POST \
-H "${AUTH_HEADER}" \
-H "${JSON_HEADER}" \
-d @"${MODEL_FILE}" \
"${DEST_MODELS_URL}" \
| jq -r '.authorization_model_id'
)
# ====== 2. Read all tuples from source store ======
echo "Reading tuples from source store..."
PAGE_SIZE=100
WRITE_BATCH_SIZE=100
PAGE_TOKEN=""
> "${TUPLES_FILE}"
while true; do
if [[ -z "${PAGE_TOKEN}" ]]; then
BODY="{\"page_size\": ${PAGE_SIZE}}"
else
BODY="{\"page_size\": ${PAGE_SIZE}, \"continuation_token\": \"${PAGE_TOKEN}\"}"
fi
RESPONSE=$(curl -sk -X POST \
-H "${AUTH_HEADER}" \
-H "${JSON_HEADER}" \
-d "${BODY}" \
"${SOURCE_READ_URL}")
echo "${RESPONSE}" | jq -c '.tuples[]' >> "${TUPLES_FILE}"
PAGE_TOKEN=$(echo "${RESPONSE}" | jq -r '.continuation_token')
if [[ "${PAGE_TOKEN}" == "null" || -z "${PAGE_TOKEN}" ]]; then
break
fi
done
TUPLE_COUNT=$(wc -l < "${TUPLES_FILE}" | tr -d ' ')
echo "Fetched ${TUPLE_COUNT} tuples."
# ====== 3. Write tuples to destination store (batched) ======
echo "Writing tuples to destination store..."
# Transform tuples: extract .key from each tuple, remove null conditions, batch them, format for write API
# Input: [{key: {user, relation, object, condition}, timestamp}, ...]
# Output: {writes: {tuple_keys: [{user, relation, object}, ...]}}
JQ_BATCH_FILTER="[.[].key | {user, relation, object} + (if .condition then {condition} else {} end)] | . as \$keys | range(0; length; $WRITE_BATCH_SIZE) | {writes: {tuple_keys: \$keys[. : . + $WRITE_BATCH_SIZE]}}"
# Save batches to temp file to avoid subshell variable scope issues
BATCHES_FILE="${WORKDIR}/batches.json"
jq -s '.' "${TUPLES_FILE}" | jq -c "$JQ_BATCH_FILTER" > "${BATCHES_FILE}"
EXPECTED_BATCHES=$(( (TUPLE_COUNT + WRITE_BATCH_SIZE - 1) / WRITE_BATCH_SIZE ))
ACTUAL_BATCHES=$(wc -l < "${BATCHES_FILE}" | tr -d ' ')
BATCH_NUM=0
while read -r BATCH; do
BATCH_NUM=$((BATCH_NUM + 1))
RESULT=$(curl -sk -X POST \
-H "Authorization: Bearer ${AUTHZ_TOKEN}" \
-H "Content-Type: application/json" \
-d "${BATCH}" \
"${DEST_WRITE_URL}")
# Check for errors
if echo "${RESULT}" | jq -e '.code' > /dev/null 2>&1; then
echo "ERROR writing batch ${BATCH_NUM}: ${RESULT}" >&2
exit 1
fi
done < "${BATCHES_FILE}"
echo "Tuple copy complete."
# ====== 4. Verify tuple count in destination store ======
echo "Verifying tuple count in destination store..."
DEST_READ_URL="${AUTHZ_API}/stores/${NEW_STORE_ID}/read"
DEST_TUPLES_FILE="${WORKDIR}/dest_tuples.json"
DEST_PAGE_TOKEN=""
> "${DEST_TUPLES_FILE}"
while true; do
if [[ -z "${DEST_PAGE_TOKEN}" ]]; then
BODY="{\"page_size\": ${PAGE_SIZE}}"
else
BODY="{\"page_size\": ${PAGE_SIZE}, \"continuation_token\": \"${DEST_PAGE_TOKEN}\"}"
fi
RESPONSE=$(curl -sk -X POST \
-H "${AUTH_HEADER}" \
-H "${JSON_HEADER}" \
-d "${BODY}" \
"${DEST_READ_URL}")
echo "${RESPONSE}" | jq -c '.tuples[]' >> "${DEST_TUPLES_FILE}"
DEST_PAGE_TOKEN=$(echo "${RESPONSE}" | jq -r '.continuation_token')
if [[ "${DEST_PAGE_TOKEN}" == "null" || -z "${DEST_PAGE_TOKEN}" ]]; then
break
fi
done
DEST_TUPLE_COUNT=$(wc -l < "${DEST_TUPLES_FILE}" | tr -d ' ')
echo "Source tuples: ${TUPLE_COUNT}, Destination tuples: ${DEST_TUPLE_COUNT}"
if [[ "${TUPLE_COUNT}" -ne "${DEST_TUPLE_COUNT}" ]]; then
echo "ERROR: Tuple count mismatch! Expected ${TUPLE_COUNT}, got ${DEST_TUPLE_COUNT}" >&2
echo "Source tuples saved to: ${TUPLES_FILE}"
echo "Destination tuples saved to: ${DEST_TUPLES_FILE}"
echo "Batches file saved to: ${BATCHES_FILE}"
echo "To compare: diff <(jq -c '.key' ${TUPLES_FILE} | sort) <(jq -c '.key' ${DEST_TUPLES_FILE} | sort)"
exit 1
fi
echo "Tuple verification passed."
# ====== Cleanup ======
rm -rf "${WORKDIR}"
echo "Created authz store ${AUTHZ_STORE_NAME} (${NEW_STORE_ID})"
if [[ -e "${WORKTREE_PATH}" ]]; then
existing_branch="$(get_branch_for_worktree_name "${WORKTREE_NAME}")"
if [[ -n "${existing_branch}" && "${existing_branch}" != "${BRANCH_NAME}" ]]; then
report_worktree_name_collision "${existing_branch}" "existing worktree path"
else
echo "ERROR: Worktree path already exists: ${WORKTREE_PATH}" >&2
fi
exit 1
fi
mkdir -p "${WORKTREE_ROOT}"
mkdir -p "$(dirname "${WORKTREE_PATH}")"
if git show-ref --verify --quiet "refs/heads/${BRANCH_NAME}"; then
git worktree add "${WORKTREE_PATH}" "${BRANCH_NAME}"
CREATED_WORKTREE=true
else
git worktree add -b "${BRANCH_NAME}" "${WORKTREE_PATH}" main
CREATED_WORKTREE=true
CREATED_BRANCH=true
fi
copy_if_exists() {
local source="$1"
local normalized="${source%/}"
if [[ ! -e "${normalized}" ]]; then
return 0
fi
if command -v rsync >/dev/null 2>&1; then
rsync -a "${normalized}" "${WORKTREE_PATH}/"
else
cp -R "${normalized}" "${WORKTREE_PATH}/"
fi
}
copy_if_exists ".vscode/"
copy_if_exists "local_exports/"
copy_if_exists ".claude/"
copy_if_exists "config.dev.toml"
copy_if_exists "config.local.toml"
ensure_ports_file() {
mkdir -p "${WORKTREE_ROOT}"
if [[ ! -f "${PORTS_FILE}" ]]; then
echo '{}' > "${PORTS_FILE}"
fi
}
# Lockfile for port reservation to prevent race conditions
PORTS_LOCKFILE="${WORKTREE_ROOT}/.worktree-ports.lock"
acquire_ports_lock() {
mkdir -p "${WORKTREE_ROOT}"
# Use flock if available, otherwise fall back to mkdir-based locking
if command -v flock >/dev/null 2>&1; then
exec 9>"${PORTS_LOCKFILE}"
if ! flock -w 30 9; then
echo "ERROR: Could not acquire port reservation lock after 30 seconds." >&2
echo "Another create-worktree.sh may be running. If not, remove ${PORTS_LOCKFILE}" >&2
return 1
fi
else
# Fallback: mkdir-based locking (atomic on POSIX)
local max_attempts=60
local attempt=0
while ! mkdir "${PORTS_LOCKFILE}.d" 2>/dev/null; do
attempt=$((attempt + 1))
if (( attempt >= max_attempts )); then
echo "ERROR: Could not acquire port reservation lock after 30 seconds." >&2
echo "Another create-worktree.sh may be running. If not, remove ${PORTS_LOCKFILE}.d" >&2
return 1
fi
sleep 0.5
done
# Store PID for debugging
echo $$ > "${PORTS_LOCKFILE}.d/pid"
fi
}
release_ports_lock() {
if command -v flock >/dev/null 2>&1; then
# flock is released automatically when fd 9 is closed
exec 9>&-
else
rm -rf "${PORTS_LOCKFILE}.d" 2>/dev/null || true
fi
}
# Clean up stale port reservations for non-existent worktrees
cleanup_stale_reservations() {
ensure_ports_file
if [[ ! -f "${PORTS_FILE}" ]]; then
return 0
fi
local tmp_ports stale_count=0
local worktrees
worktrees=$(jq -r 'keys[]' "${PORTS_FILE}" 2>/dev/null) || return 0
for worktree in ${worktrees}; do
local worktree_path="${WORKTREE_ROOT}/${worktree}"
local sanitized_worktree_path="${WORKTREE_ROOT}/$(sanitize_db_suffix "${worktree}")"
local registered_worktree_path
local legacy_registered_worktree_path
registered_worktree_path="$(get_worktree_path_for_name "${worktree}")"
legacy_registered_worktree_path="$(get_worktree_path_for_branch "${worktree}")"
if [[ -d "${worktree_path}" ]] \
|| [[ -d "${sanitized_worktree_path}" ]] \
|| [[ -n "${registered_worktree_path}" ]] \
|| [[ -n "${legacy_registered_worktree_path}" ]]; then
continue
fi
echo "Removing stale port reservation for non-existent worktree: ${worktree}" >&2
tmp_ports="$(mktemp)"
if jq --arg name "${worktree}" 'del(.[$name])' "${PORTS_FILE}" > "${tmp_ports}"; then
mv "${tmp_ports}" "${PORTS_FILE}"
stale_count=$((stale_count + 1))
else
rm -f "${tmp_ports}"
fi
done
if (( stale_count > 0 )); then
echo "Cleaned up ${stale_count} stale port reservation(s)." >&2
fi
}
is_port_reserved() {
local port="$1"
if [[ ! -f "${PORTS_FILE}" ]]; then
return 1
fi
jq -e --argjson port "${port}" \
'to_entries[] | .value | select(.server == $port or .frontend == $port)' \
"${PORTS_FILE}" >/dev/null 2>&1
}
reserve_ports() {
local worktree="$1"
local server="$2"
local frontend="$3"
local branch_name="$4"
local tmp_ports
ensure_ports_file
tmp_ports="$(mktemp)"
if jq --arg name "${worktree}" \
--argjson server "${server}" \
--argjson frontend "${frontend}" \
--arg branch "${branch_name}" \
'. + {($name): {branch: $branch, server: $server, frontend: $frontend, updated_at: (now | todateiso8601)}}' \
"${PORTS_FILE}" > "${tmp_ports}"; then
if mv "${tmp_ports}" "${PORTS_FILE}"; then
return 0
fi
fi
rm -f "${tmp_ports}"
return 1
}
is_port_in_use() {
local port="$1"
if command -v lsof >/dev/null 2>&1; then
lsof -iTCP:"${port}" -sTCP:LISTEN -P -n >/dev/null 2>&1
return $?
fi
if command -v nc >/dev/null 2>&1; then
nc -z localhost "${port}" >/dev/null 2>&1
return $?
fi
if command -v ss >/dev/null 2>&1; then
ss -ltn "sport = :${port}" | grep -q "LISTEN"
return $?
fi
echo "No port-checking tool found (need lsof, nc, or ss)." >&2
return 2
}
find_next_available_port() {
local start_port="$1"
local port=$((start_port + 1))
while true; do
if ! is_port_in_use "${port}" && ! is_port_reserved "${port}"; then
echo "${port}"
return 0
fi
port=$((port + 1))
done
}
# Acquire lock before port operations to prevent race conditions
echo "Acquiring port reservation lock..."
if ! acquire_ports_lock; then
exit 1
fi
# Ensure lock is released on exit (add to existing trap)
release_lock_on_exit() {
release_ports_lock
}
trap 'release_lock_on_exit; cleanup_on_failure' EXIT
# Clean up stale reservations from crashed/killed runs
cleanup_stale_reservations
ensure_ports_file
if jq -e --arg name "${WORKTREE_NAME}" 'has($name)' "${PORTS_FILE}" >/dev/null 2>&1; then
existing_reserved_branch="$(get_reserved_branch_for_worktree_name "${WORKTREE_NAME}")"
if [[ -z "${existing_reserved_branch}" ]]; then
existing_reserved_branch="$(get_branch_for_worktree_name "${WORKTREE_NAME}")"
fi
if [[ -n "${existing_reserved_branch}" && "${existing_reserved_branch}" != "${BRANCH_NAME}" ]]; then
report_worktree_name_collision "${existing_reserved_branch}" "port reservation in ${PORTS_FILE}"
else
echo "ERROR: Port reservation for worktree name '${WORKTREE_NAME}' already exists in ${PORTS_FILE}." >&2
echo "Run ./remove-worktree.sh ${WORKTREE_NAME} or remove the entry manually." >&2
fi
exit 1
fi
SERVER_PORT="$(find_next_available_port 8001)"
FRONTEND_PORT="$(find_next_available_port 5174)"
export SERVER_PORT
export FRONTEND_PORT
if ! reserve_ports "${WORKTREE_NAME}" "${SERVER_PORT}" "${FRONTEND_PORT}" "${BRANCH_NAME}"; then
echo "ERROR: Failed to reserve ports for ${WORKTREE_NAME}." >&2
exit 1
fi
CREATED_PORTS=true
# Release lock now that ports are reserved
release_ports_lock
# Portable sed in-place: macOS requires -i '', GNU sed requires -i without argument
sed_inplace() {
local pattern="$1"
local file="$2"
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' -E "${pattern}" "${file}"
else
sed -i -E "${pattern}" "${file}"
fi
}
# Escape sed replacement special characters (& and \)
sed_escape() {
printf '%s' "$1" | sed 's/[&\\/]/\\&/g'
}
if [[ -f "${WORKTREE_PATH}/config.local.toml" ]]; then
ESCAPED_DB_NAME="$(sed_escape "${DB_NAME}")"
ESCAPED_AUTHZ_STORE_NAME="$(sed_escape "${AUTHZ_STORE_NAME}")"
sed_inplace "s|^public_url = \".*\"|public_url = \"http://localhost:${FRONTEND_PORT}\"|" "${WORKTREE_PATH}/config.local.toml"
sed_inplace "s|^database = \".*\"|database = \"${ESCAPED_DB_NAME}\"|" "${WORKTREE_PATH}/config.local.toml"
sed_inplace "s|^store = \".*\"|store = \"${ESCAPED_AUTHZ_STORE_NAME}\"|" "${WORKTREE_PATH}/config.local.toml"
fi