forked from ModelEarth/team
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.sh
More file actions
executable file
·2638 lines (2302 loc) · 104 KB
/
Copy pathgit.sh
File metadata and controls
executable file
·2638 lines (2302 loc) · 104 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
# git.sh - Streamlined git operations for webroot repository
# Usage: ./git.sh [command] [options]
# Push commands automatically pull first unless 'nopull' or 'no pull' is specified
#
# IMPORTANT: This script includes safeguards against submodule rollbacks
# - Uses safe_submodule_update() to keep submodule pointers current
# - Advances stale parent pointers to the newest remote commit; never reverts submodules backward
set -e # Exit on any error
# Global setting for safe submodule updates (can be overridden with overwrite-local)
SAFE_SUBMODULE_UPDATES=true
# Store the webroot directory at script start
WEBROOT_DIR=""
# Derive parent repo name from origin URL (instead of hardcoding "webroot")
_origin_url=$(git remote get-url origin 2>/dev/null || echo "")
PARENT_REPO_NAME="${_origin_url%.git}"
PARENT_REPO_NAME="${PARENT_REPO_NAME##*/}"
PARENT_REPO_NAME="${PARENT_REPO_NAME:-webroot}"
# Parse command line arguments for global flags
for arg in "$@"; do
case $arg in
overwrite-local)
SAFE_SUBMODULE_UPDATES=false
echo "⚠️ WARNING: Will overwrite local commits with parent repository state"
;;
esac
done
# CLAUDE_COMMIT_DATA parsing and commit message functions
parse_claude_commit_data() {
local repo_name="$1"
if [ -z "$CLAUDE_COMMIT_DATA" ]; then
return 1
fi
# Simple YAML parsing for commit data
# Extract message for the specific repository
local message=$(echo "$CLAUDE_COMMIT_DATA" | grep -A2 "^${repo_name}:" | grep "message:" | sed "s/.*message: *['\"]*//" | sed "s/['\"]* *$//" | head -1)
if [ -n "$message" ]; then
echo "$message"
return 0
fi
return 1
}
# Generate enhanced default commit message from modified files
generate_default_commit_message() {
local repo_name="$1"
local repo_path="${2:-.}"
# Get list of modified files
local modified_files=$(cd "$repo_path" && git status --porcelain | grep -E "^(M|A|D|R|C)" | awk '{print $2}' | sort | uniq)
if [ -z "$modified_files" ]; then
echo "Updated $repo_name"
return
fi
# Convert to array and get unique filenames (not full paths)
local unique_files=()
local seen_names=()
for file in $modified_files; do
local filename=$(basename "$file")
local already_seen=false
for seen in "${seen_names[@]}"; do
if [ "$seen" = "$filename" ]; then
already_seen=true
break
fi
done
if [ "$already_seen" = false ]; then
unique_files+=("$filename")
seen_names+=("$filename")
# Stop at 3 unique files
if [ ${#unique_files[@]} -ge 3 ]; then
break
fi
fi
done
# Build commit message
if [ ${#unique_files[@]} -eq 1 ]; then
echo "Updated ${unique_files[0]}"
elif [ ${#unique_files[@]} -eq 2 ]; then
echo "Updated ${unique_files[0]}, ${unique_files[1]}"
elif [ ${#unique_files[@]} -eq 3 ]; then
local total_files=$(echo "$modified_files" | wc -w)
if [ "$total_files" -gt 3 ]; then
echo "Updated ${unique_files[0]}, ${unique_files[1]}, ${unique_files[2]}..."
else
echo "Updated ${unique_files[0]}, ${unique_files[1]}, ${unique_files[2]}"
fi
else
echo "Updated $repo_name"
fi
}
# Get commit message for a repository (Claude or default)
get_commit_message() {
local repo_name="$1"
local repo_path="${2:-.}"
# Try Claude commit data first
local claude_message=$(parse_claude_commit_data "$repo_name")
if [ $? -eq 0 ] && [ -n "$claude_message" ]; then
echo "$claude_message"
return
fi
# Fall back to enhanced default message
generate_default_commit_message "$repo_name" "$repo_path"
}
# Validate and fix repository remote URLs to prevent corruption
validate_and_fix_remotes() {
# Silent validation - only output if corruption is found
# Check team repository - Enhanced detection
local team_remote=""
local team_upstream=""
# Multiple ways to check team repository
if [ -f "../.gitmodules" ] && [ -f ".git" ]; then
# We're in team submodule directory
team_remote=$(git remote get-url origin 2>/dev/null || echo "")
team_upstream=$(git remote get-url upstream 2>/dev/null || echo "")
elif [ -d "team" ] && [ -f "team/.git" ]; then
# We're in webroot, checking team submodule
team_remote=$(git -C "team" remote get-url origin 2>/dev/null || echo "")
team_upstream=$(git -C "team" remote get-url upstream 2>/dev/null || echo "")
fi
# Fix team repository if corrupted
if [[ -n "$team_remote" ]] && [[ "$team_remote" =~ /webroot(\.git)?$ ]]; then
echo "🚨 CRITICAL: Team repository origin pointing to webroot URL - fixing..."
if [ -f "../.gitmodules" ] && [ -f ".git" ]; then
git remote set-url origin "https://github.com/ModelEarth/team.git"
elif [ -d "team" ]; then
git -C "team" remote set-url origin "https://github.com/ModelEarth/team.git"
fi
echo "✅ Fixed team origin remote URL"
fi
if [[ -n "$team_upstream" ]] && [[ "$team_upstream" =~ /webroot(\.git)?$ ]]; then
echo "🚨 CRITICAL: Team repository upstream pointing to webroot URL - fixing..."
if [ -f "../.gitmodules" ] && [ -f ".git" ]; then
git remote set-url upstream "https://github.com/ModelEarth/team.git"
elif [ -d "team" ]; then
git -C "team" remote set-url upstream "https://github.com/ModelEarth/team.git"
fi
echo "✅ Fixed team upstream remote URL"
fi
# Validation completed silently
}
# Helper function to check if we're in webroot
check_webroot() {
# Check for nested webroot directories (prevent confusion) - but only if we're in team subdirectory
if [ -f "../.gitmodules" ] && [ -d "webroot" ]; then
echo "⚠️ WARNING: Found nested 'webroot' directory in team submodule!"
echo " This can cause confusion. Consider removing: $(pwd)/webroot"
fi
# Determine context: are we operating on webroot or team?
local CURRENT_REMOTE=""
OPERATING_ON_WEBROOT=false
# Check if we were called from webroot's git.sh (WEBROOT_CONTEXT env var set)
if [ -n "$WEBROOT_CONTEXT" ]; then
# Called from webroot's git.sh - operate on webroot
OPERATING_ON_WEBROOT=true
CURRENT_REMOTE=$(git -C "$WEBROOT_CONTEXT" remote get-url origin 2>/dev/null || echo "")
elif [ -f ".gitmodules" ] && [ -d ".git" ]; then
# We're in webroot directory - operate on webroot
OPERATING_ON_WEBROOT=true
CURRENT_REMOTE=$(git remote get-url origin 2>/dev/null || echo "")
elif [ -f "../.gitmodules" ] && [ -d "../.git" ]; then
# We're in team subdirectory - operate on team
OPERATING_ON_WEBROOT=false
CURRENT_REMOTE=$(git remote get-url origin 2>/dev/null || echo "")
else
# Try to find webroot by going up directories
local current_dir=$(pwd)
while [ "$current_dir" != "/" ]; do
if [ -f "$current_dir/.gitmodules" ] && [ -d "$current_dir/.git" ]; then
OPERATING_ON_WEBROOT=true
CURRENT_REMOTE=$(git -C "$current_dir" remote get-url origin 2>/dev/null || echo "")
break
fi
current_dir=$(dirname "$current_dir")
done
fi
# Validate the context matches the expected repository
if [ "$OPERATING_ON_WEBROOT" = true ]; then
# Check if team submodule exists in .gitmodules
if [ -f ".gitmodules" ]; then
if ! grep -q "path = team" .gitmodules 2>/dev/null; then
echo "⚠️ WARNING: Operating on parent repository but 'team' submodule not found in .gitmodules"
echo " Current directory: $(pwd)"
echo " Remote: $CURRENT_REMOTE"
fi
fi
else
# Operating on team submodule - verify parent has .gitmodules
if [ ! -f "../.gitmodules" ]; then
echo "⚠️ WARNING: Operating on team but parent .gitmodules not found"
echo " Current directory: $(pwd)"
fi
fi
# Store the webroot directory for later use
if [ -z "$WEBROOT_DIR" ]; then
if [ -f ".gitmodules" ] && [ -d ".git" ]; then
WEBROOT_DIR=$(pwd)
elif [ -f "../.gitmodules" ] && [ -d "../.git" ]; then
WEBROOT_DIR=$(cd .. && pwd)
else
# Find webroot by going up directories
local current_dir=$(pwd)
while [ "$current_dir" != "/" ]; do
if [ -f "$current_dir/.gitmodules" ] && [ -d "$current_dir/.git" ]; then
WEBROOT_DIR="$current_dir"
break
fi
current_dir=$(dirname "$current_dir")
done
fi
fi
}
# Helper function to return to webroot directory
cd_webroot() {
if [ -n "$WEBROOT_DIR" ]; then
cd "$WEBROOT_DIR"
else
echo "⚠️ ERROR: Webroot directory not set"
return 1
fi
}
# Check if .gitmodules has a token-embedded URL for a submodule and apply it to the remote.
# This allows pushing to private repos when the current GitHub CLI account lacks access.
# Usage: apply_gitmodules_token "submodule_name"
# Returns 0 if a token URL was found and applied, 1 otherwise.
apply_gitmodules_token() {
local name="$1"
local gitmodules="$WEBROOT_DIR/.gitmodules"
if [ ! -f "$gitmodules" ]; then
return 1
fi
# Extract the URL for this submodule from .gitmodules
local token_url=$(awk "/\\[submodule \"$name\"\\]/{found=1} found && /url =/{print \$3; exit}" "$gitmodules")
if [[ "$token_url" == *"@github.com"* ]]; then
local current_url=$(git remote get-url origin 2>/dev/null || echo "")
if [[ "$current_url" != "$token_url" ]]; then
echo "🔑 Applying token URL from .gitmodules for $name"
git remote set-url origin "$token_url"
return 0
fi
fi
return 1
}
# Safe directory management for submodule operations
# Usage: safe_submodule_operation "submodule_name" "operation_function"
safe_submodule_operation() {
local sub="$1"
local operation="$2"
shift 2 # Remove first two arguments, pass rest to operation
# Save current directory
local original_dir=$(pwd)
local operation_success=true
# Set up error handling
set +e # Don't exit on error, handle it ourselves
if [ -d "$sub" ]; then
cd "$sub" || {
echo "⚠️ ERROR: Failed to enter directory: $sub"
return 1
}
# Execute the operation with error handling
if ! eval "$operation" "$@"; then
operation_success=false
fi
# Always return to original directory, even if operation failed
cd "$original_dir" || {
echo "🚨 CRITICAL: Failed to return to original directory: $original_dir"
echo "📁 Current directory: $(pwd)"
echo "🔧 Attempting to return to webroot..."
cd_webroot
}
else
echo "⚠️ WARNING: Directory does not exist: $sub"
operation_success=false
fi
# Restore error handling
set -e
if [ "$operation_success" = "true" ]; then
return 0
else
return 1
fi
}
# Safe wrapper for operations that need to iterate through directories
safe_directory_iterator() {
local dirs=("$@")
local operation="$1"
shift 1
local original_dir=$(pwd)
local failed_operations=()
for dir in "${dirs[@]}"; do
if [ -d "$dir" ]; then
echo "🔄 Processing $dir..."
if ! safe_submodule_operation "$dir" "$operation" "$@"; then
failed_operations+=("$dir")
fi
else
echo "⚠️ Skipping non-existent directory: $dir"
failed_operations+=("$dir")
fi
done
# Ensure we're back in the original directory
if [ "$(pwd)" != "$original_dir" ]; then
echo "🔧 Returning to original directory: $original_dir"
cd "$original_dir"
fi
# Report any failures
if [ ${#failed_operations[@]} -gt 0 ]; then
echo "⚠️ Operations failed for: ${failed_operations[*]}"
return 1
fi
return 0
}
# Helper function to run git commands in webroot context
git_webroot() {
# If we're in webroot directory (has .gitmodules), run git directly
if [ -f ".gitmodules" ]; then
git "$@"
# If we're in team subdirectory, use git -C ..
elif [ -f "../.gitmodules" ]; then
git -C .. "$@"
else
echo "⚠️ ERROR: Cannot determine webroot context"
return 1
fi
}
# Parse submodules from .gitmodules file in webroot directory
get_submodules() {
local webroot_dir
if [ -f ".gitmodules" ]; then
# We're in webroot directory
grep "^\[submodule" ".gitmodules" | sed 's/\[submodule "\(.*\)"\]/\1/'
elif [ -f "../.gitmodules" ]; then
# We're in team subdirectory
grep "^\[submodule" "../.gitmodules" | sed 's/\[submodule "\(.*\)"\]/\1/'
else
echo "⚠️ ERROR: .gitmodules file not found" >&2
return 1
fi
}
get_gitmodules_file() {
if [ -f ".gitmodules" ]; then
echo ".gitmodules"
elif [ -f "../.gitmodules" ]; then
echo "../.gitmodules"
fi
}
get_submodule_config() {
local repo_name="$1"
local key="$2"
local gitmodules_file
gitmodules_file=$(get_gitmodules_file)
[ -z "$gitmodules_file" ] && return 1
git config -f "$gitmodules_file" --get "submodule.$repo_name.$key" 2>/dev/null
}
# Parse site repos from .siterepos file in webroot directory
get_site_repos() {
local siterepos_file
if [ -f ".siterepos" ]; then
# We're in webroot directory
siterepos_file=".siterepos"
elif [ -f "../.siterepos" ]; then
# We're in team subdirectory
siterepos_file="../.siterepos"
else
return 0 # Not an error, just no site repos
fi
# Parse .siterepos file (same format as .gitmodules)
grep "^\[siterepo" "$siterepos_file" | sed 's/\[siterepo "\(.*\)"\]/\1/'
}
# Check if repo has capital M (ModelEarth) based on .gitmodules URL
# Get the upstream account name for a repo from .gitmodules URL casing
get_upstream_account() {
local repo_name="$1"
local gitmodules_file
gitmodules_file=$(get_gitmodules_file)
if [ -z "$gitmodules_file" ]; then
# Fallback to hardcoded check
if [[ "$repo_name" == "localsite" ]] || [[ "$repo_name" == "home" ]] || [[ "$repo_name" == "webroot" ]]; then
echo "ModelEarth"
else
echo "modelearth"
fi
return
fi
local url=$(grep -A2 "^\[submodule \"$repo_name\"\]" "$gitmodules_file" | grep "url" | head -1)
if [[ "$url" == *"ModelEarth"* ]]; then
echo "ModelEarth"
else
echo "modelearth"
fi
}
# Extract account and repo name from origin remote URL
get_origin_account() {
local origin_url=$(git remote get-url origin 2>/dev/null || echo "")
# Extract account: second-to-last path component
local without_git="${origin_url%.git}"
local account="${without_git%/*}"
account="${account##*/}"
echo "$account"
}
get_origin_repo_name() {
local origin_url=$(git remote get-url origin 2>/dev/null || echo "")
local repo_name="${origin_url%.git}"
repo_name="${repo_name##*/}"
echo "$repo_name"
}
# Add upstream remote if it doesn't exist
add_upstream() {
local repo_name="$1"
local account="$2"
local configured_upstream=$(get_submodule_config "$repo_name" "upstream")
if [ -z "$(git remote | grep '^upstream$')" ]; then
if [ -n "$configured_upstream" ]; then
git remote add upstream "$configured_upstream"
else
git remote add upstream "https://github.com/$account/$repo_name.git"
fi
elif [ -n "$configured_upstream" ]; then
local current_upstream=$(git remote get-url upstream 2>/dev/null || echo "")
if [ "$current_upstream" != "$configured_upstream" ]; then
git remote set-url upstream "$configured_upstream"
fi
fi
}
submodule_upstream_policy() {
local repo_name="$1"
get_submodule_config "$repo_name" "upstream-policy"
}
prepare_submodule_for_upstream_merge() {
local repo_name="$1"
local policy=$(submodule_upstream_policy "$repo_name")
[ "$policy" != "merge-if-clean" ] && return 0
if [ -n "$(git status --porcelain 2>/dev/null)" ]; then
echo "⏭️ Skipping branch checkout for $repo_name due to local changes"
return 0
fi
if [ -n "$(git symbolic-ref -q HEAD 2>/dev/null)" ]; then
return 0
fi
if git show-ref --verify --quiet refs/heads/main; then
git checkout main >/dev/null 2>&1 || return 1
return 0
fi
if git show-ref --verify --quiet refs/heads/master; then
git checkout master >/dev/null 2>&1 || return 1
return 0
fi
echo "⏭️ Skipping upstream merge prep for $repo_name (no local main/master branch)"
return 0
}
# Merge from upstream with fallback branches
merge_upstream() {
local repo_name="$1"
if ! git fetch upstream 2>/dev/null; then
echo "⏭️ Skipping upstream merge for $repo_name (since not a contributor's fork)"
return 0
fi
# Try main/master first for all repos
local merge_output
merge_output=$(git merge upstream/main --no-edit 2>&1) || true
if [[ "$merge_output" == *"unrelated histories"* ]]; then
echo "⏭️ Skipping upstream merge for $repo_name (unrelated histories)"
return 0
elif [[ "$merge_output" != *"fatal"* ]] && [[ "$merge_output" != *"CONFLICT"* ]]; then
if [[ "$merge_output" != *"Already up to date"* ]]; then
echo "$merge_output"
fi
return 0
fi
# Abort before trying the fallback branch; without this, upstream/master runs
# on top of a conflicting merge and produces nested conflict markers.
git merge --abort 2>/dev/null || true
merge_output=$(git merge upstream/master --no-edit 2>&1) || true
if [[ "$merge_output" == *"unrelated histories"* ]]; then
echo "⏭️ Skipping upstream merge for $repo_name (unrelated histories)"
return 0
elif [[ "$merge_output" != *"fatal"* ]] && [[ "$merge_output" != *"CONFLICT"* ]]; then
if [[ "$merge_output" != *"Already up to date"* ]]; then
echo "$merge_output"
fi
return 0
fi
git merge --abort 2>/dev/null || true
local conflict_files
conflict_files=$(echo "$merge_output" | grep "^CONFLICT" | sed 's/CONFLICT.*: //' | tr '\n' ' ')
echo "⏭️ Skipping upstream merge for $repo_name — conflicts in: ${conflict_files}(repo left clean)"
return 1
}
# Detect parent repository account (modelearth or partnertools)
get_parent_account() {
local repo_name="$1"
# Check if upstream remote exists and points to expected parent
local upstream_url=$(git remote get-url upstream 2>/dev/null || echo "")
if [[ "$upstream_url" == *"modelearth/$repo_name"* ]]; then
echo "modelearth"
elif [[ "$upstream_url" == *"partnertools/$repo_name"* ]]; then
echo "partnertools"
else
# Fallback: try to determine from typical parent structure
if [[ "$repo_name" == "localsite" ]] || [[ "$repo_name" == "home" ]] || [[ "$repo_name" == "webroot" ]]; then
echo "ModelEarth" # Capital M for these repos
else
echo "modelearth" # lowercase for others
fi
fi
}
# Get current GitHub user account
get_current_user() {
local user=$(gh api user --jq .login 2>/dev/null || echo "")
if [ -z "$user" ]; then
# Don't echo error message, just return failure
return 1
fi
echo "$user"
return 0
}
# Check if current user owns the repository or has write access
is_repo_owner() {
local repo_name="$1"
local current_origin=$(git remote get-url origin 2>/dev/null || echo "")
# Extract username from origin URL using actual repo name in URL
local origin_repo="${current_origin%.git}"
origin_repo="${origin_repo##*/}"
if [[ "$current_origin" =~ github\.com[:/]([^/]+)/$origin_repo ]]; then
local repo_owner="${BASH_REMATCH[1]}"
# Try to get GitHub CLI user first
local gh_user=$(get_current_user)
local gh_result=$?
if [ $gh_result -eq 0 ] && [ "$gh_user" = "$repo_owner" ]; then
return 0 # User owns the repo via GitHub CLI
fi
# If GitHub CLI confirms user but doesn't match owner, not the owner
if [ $gh_result -eq 0 ] && [ "$gh_user" != "$repo_owner" ]; then
return 1 # Confirmed different user
fi
# If GitHub CLI fails, check if it's a personal fork (not ModelEarth/modelearth)
if [[ "$repo_owner" != "ModelEarth" ]] && [[ "$repo_owner" != "modelearth" ]]; then
return 0 # Likely a fork owned by the user
fi
fi
return 1 # Not the owner or couldn't determine
}
# Clear git credentials and setup fresh authentication for current GitHub user
refresh_git_credentials() {
local current_user="$1"
echo "🔄 Refreshing git credentials for $current_user..."
# Clear cached git credentials
git credential-manager-core erase 2>/dev/null || true
git credential erase 2>/dev/null || true
# Clear macOS keychain git credentials
if command -v security >/dev/null 2>&1; then
security delete-internet-password -s github.com 2>/dev/null || true
fi
# Setup git to use GitHub CLI credentials
gh auth setup-git
echo "✅ Git credentials refreshed for $current_user"
}
# Store last known user in a temporary file for comparison
USER_CACHE_FILE="/tmp/git_sh_last_user"
# Check if current user has changed and update remotes accordingly
check_user_change() {
local name="$1"
# CRITICAL FIX: When operating on webroot from team context, don't update team repo's remote
if [[ "$name" == "webroot" ]] && [[ "$OPERATING_ON_WEBROOT" == "true" ]] && [[ -n "$WEBROOT_CONTEXT" ]]; then
# We're in team directory but operating on webroot - check current directory's actual repo
local current_remote=$(git remote get-url origin 2>/dev/null || echo "")
if [[ "$current_remote" =~ /team(\.git)?$ ]]; then
echo "🛡️ Skipping remote update for team repository (operating on webroot context)"
return 0
fi
fi
# If user owns the repo, skip GitHub CLI requirement
if is_repo_owner "$name"; then
return 0 # User owns the repo, no need to update remotes
fi
# Try to get current user via GitHub CLI
local current_user=$(get_current_user)
if [ $? -ne 0 ] || [ -z "$current_user" ]; then
# GitHub CLI not authenticated, but check if we can proceed without it
local current_origin=$(git remote get-url origin 2>/dev/null || echo "")
if [[ "$current_origin" =~ github\.com[:/]([^/]+)/$name ]]; then
local repo_owner="${BASH_REMATCH[1]}"
if [[ "$repo_owner" != "ModelEarth" ]] && [[ "$repo_owner" != "modelearth" ]]; then
echo "ℹ️ GitHub CLI not authenticated, but using existing fork remote"
return 0
elif [[ "$repo_owner" == "ModelEarth" ]] && [[ "$name" == "webroot" ]]; then
echo "ℹ️ GitHub CLI not authenticated, but have access to ModelEarth/webroot"
return 0
fi
fi
echo "⚠️ GitHub CLI not authenticated and repository requires it for operations"
return 1
fi
# Check if user has changed since last run
local last_user=""
if [ -f "$USER_CACHE_FILE" ]; then
last_user=$(cat "$USER_CACHE_FILE" 2>/dev/null)
fi
# If user has changed, refresh git credentials
if [ -n "$last_user" ] && [ "$last_user" != "$current_user" ]; then
echo "👤 GitHub user changed from $last_user to $current_user"
refresh_git_credentials "$current_user"
fi
# Store current user for next comparison
echo "$current_user" > "$USER_CACHE_FILE"
# Check current origin remote
local current_origin=$(git remote get-url origin 2>/dev/null || echo "")
# Derive actual repo name from current origin URL (don't assume name matches)
local origin_repo_name="${current_origin%.git}"
origin_repo_name="${origin_repo_name##*/}"
local expected_origin="https://github.com/$current_user/$origin_repo_name.git"
# ADDITIONAL SAFEGUARD: Verify we're in the correct repository before updating remote
# Check for context mismatch - if we're trying to update the wrong repository
if [[ "$name" == "webroot" ]] && [[ "$current_origin" =~ /team(\.git)?$ ]]; then
echo "⚠️ ERROR: Attempted to update team repository remote to webroot URL - skipping"
echo " Current remote: $current_origin"
echo " Intended remote: $expected_origin"
return 1
elif [[ "$name" == "team" ]] && [[ "$current_origin" =~ /webroot(\.git)?$ ]]; then
echo "⚠️ ERROR: Attempted to update webroot repository remote to team URL - skipping"
echo " Current remote: $current_origin"
echo " Intended remote: $expected_origin"
return 1
fi
# CRITICAL FIX: When called from webroot context but in team directory,
# ensure we're operating on the correct repository
if [[ -n "$WEBROOT_CONTEXT" ]] && [[ "$name" == "webroot" ]] && [[ "$current_origin" =~ /webroot(\.git)?$ ]]; then
# We're correctly operating on webroot - use git -C to ensure we modify the right repo
current_origin=$(git -C "$WEBROOT_CONTEXT" remote get-url origin 2>/dev/null || echo "")
if [[ "$current_origin" != "$expected_origin" ]]; then
echo "🔄 GitHub user changed to $current_user - updating webroot origin remote..."
git -C "$WEBROOT_CONTEXT" remote set-url origin "$expected_origin" 2>/dev/null || {
echo "⚠️ Failed to update webroot origin remote for $current_user"
return 1
}
echo "🔧 Updated webroot origin to point to $current_user/webroot"
return 0
else
return 0 # Already correct
fi
fi
# For contributors who don't have direct push access to the parent repo.
# Updates origin to the current user's fork only when the current origin owner
# already matches the authenticated GitHub user.
# If origin is owned by a different account/org (for example, an org repo the
# user can push to directly), keep origin as-is; permission handling happens later
# in the push flow, with fork fallback on permission errors.
if [[ "$current_origin" != "$expected_origin" ]]; then
local current_owner="${current_origin#https://github.com/}"
current_owner="${current_owner%%/*}"
if [[ "$(echo "$current_owner" | tr '[:upper:]' '[:lower:]')" != "$(echo "$current_user" | tr '[:upper:]' '[:lower:]')" ]]; then
return 0
fi
echo "🔄 GitHub user changed to $current_user - updating origin remote..."
git remote set-url origin "$expected_origin" 2>/dev/null || {
echo "⚠️ Failed to update origin remote for $current_user"
return 1
}
echo "🔧 Updated origin to point to $current_user/$name"
fi
return 0
}
# Create fork and update remote to user's fork
setup_fork() {
local name="$1"
local parent_account="$2"
# CRITICAL SAFEGUARD: Prevent cross-repository URL corruption
local current_remote=$(git remote get-url origin 2>/dev/null || echo "")
if [[ "$name" == "webroot" ]] && [[ "$current_remote" =~ /team(\.git)?$ ]]; then
echo "⚠️ ERROR: Attempted to setup webroot fork while in team repository - aborting"
return 1
elif [[ "$name" == "team" ]] && [[ "$current_remote" =~ /webroot(\.git)?$ ]]; then
echo "⚠️ ERROR: Attempted to setup team fork while in webroot repository - aborting"
return 1
fi
# If user already owns the repo, no need to fork
if is_repo_owner "$name"; then
echo "ℹ️ Already using user's repository, no fork needed"
return 0
fi
local current_user=$(get_current_user)
if [ $? -ne 0 ]; then
echo "⚠️ Cannot create fork - GitHub CLI not authenticated"
return 1
fi
echo "🍴 Creating fork of $parent_account/$name for $current_user..."
# Create fork (gh handles case where fork already exists)
local fork_url=$(gh repo fork "$parent_account/$name" --clone=false 2>/dev/null || echo "")
if [ -n "$fork_url" ]; then
echo "✅ Fork created/found: $fork_url"
# Update origin to point to user's fork
git remote set-url origin "$fork_url.git" 2>/dev/null || \
git remote set-url origin "https://github.com/$current_user/$name.git"
echo "🔧 Updated origin remote to point to $current_user fork"
return 0
else
echo "⚠️ Failed to create/find fork for $current_user"
return 1
fi
}
# Update webroot submodule reference to point to user's fork
update_webroot_submodule_reference() {
local name="$1"
local commit_hash="$2"
# Get current user login
local user_login=$(get_current_user)
if [ $? -ne 0 ]; then
echo "⚠️ Could not determine GitHub username"
return 1
fi
echo "🔄 Updating webroot submodule reference..."
cd $(git rev-parse --show-toplevel)
# Update .gitmodules to point to user's fork
git config -f .gitmodules submodule.$name.url "https://github.com/$user_login/$name.git"
# Sync the submodule URL change
git submodule sync "$name"
# Update submodule to point to the specific commit
cd "$name"
git checkout "$commit_hash" 2>/dev/null
cd_webroot
# Commit the submodule reference update
if [ -n "$(git status --porcelain | grep -E "($name|\.gitmodules)")" ]; then
git add "$name" .gitmodules
git commit -m "Update $name submodule to point to $user_login fork (commit $commit_hash)"
if git push origin main 2>/dev/null; then
echo "✅ Updated webroot submodule reference to your fork"
else
echo "⚠️ Failed to push webroot submodule reference update"
fi
fi
}
# Safely update submodules without reverting to older commits
safe_submodule_update() {
if [ "$SAFE_SUBMODULE_UPDATES" = "false" ]; then
echo "⚠️ Using UNSAFE submodule update (may revert to older commits)"
git submodule update --remote --recursive
return
fi
echo "🛡️ Performing safe submodule update (advancing stale parent pointers to latest remote commits)..."
# Get all submodules from .gitmodules file
local submodules=($(get_submodules))
for sub in "${submodules[@]}"; do
if [ -d "$sub" ] && [ -e "$sub/.git" ]; then
cd "$sub"
# Always fetch latest from parent repository first
echo "📥 Fetching latest from parent repository for $sub..."
git fetch origin main 2>/dev/null || git fetch origin master 2>/dev/null || echo "⚠️ Could not fetch from origin"
# Also try to fetch from upstream if it exists
if git remote | grep -q upstream; then
git fetch upstream main 2>/dev/null || git fetch upstream master 2>/dev/null || echo "⚠️ Could not fetch from upstream"
fi
local upstream_policy=$(submodule_upstream_policy "$sub")
# Get current commit hash and timestamp
local current_commit=$(git rev-parse HEAD 2>/dev/null || echo "")
local current_timestamp=""
if [ -n "$current_commit" ]; then
current_timestamp=$(git show -s --format=%ct "$current_commit" 2>/dev/null || echo "0")
fi
# Get latest commit from origin/main (or master)
local latest_origin_commit=$(git rev-parse origin/main 2>/dev/null || git rev-parse origin/master 2>/dev/null || echo "")
local latest_origin_timestamp=""
if [ -n "$latest_origin_commit" ]; then
latest_origin_timestamp=$(git show -s --format=%ct "$latest_origin_commit" 2>/dev/null || echo "0")
fi
# Get latest commit from upstream if available
local latest_upstream_commit=""
local latest_upstream_timestamp=""
if git remote | grep -q upstream; then
latest_upstream_commit=$(git rev-parse upstream/main 2>/dev/null || git rev-parse upstream/master 2>/dev/null || echo "")
if [ -n "$latest_upstream_commit" ]; then
latest_upstream_timestamp=$(git show -s --format=%ct "$latest_upstream_commit" 2>/dev/null || echo "0")
fi
fi
# Determine the newest available commit
local newest_commit="$current_commit"
local newest_timestamp="$current_timestamp"
local update_source="current"
# Check if origin has newer commits
if [ -n "$latest_origin_commit" ] && [ "$latest_origin_timestamp" -gt "$newest_timestamp" ]; then
newest_commit="$latest_origin_commit"
newest_timestamp="$latest_origin_timestamp"
update_source="origin"
fi
# Check if upstream has even newer commits
if [ -n "$latest_upstream_commit" ] && [ "$latest_upstream_timestamp" -gt "$newest_timestamp" ]; then
newest_commit="$latest_upstream_commit"
newest_timestamp="$latest_upstream_timestamp"
update_source="upstream"
fi
# Check what commit the parent repository wants
cd_webroot
local expected_commit=$(git ls-tree HEAD "$sub" | awk '{print $3}' || echo "")
if [ -n "$expected_commit" ] && [ -n "$current_commit" ]; then
cd "$sub"
# Get timestamp of expected commit
local expected_timestamp=$(git show -s --format=%ct "$expected_commit" 2>/dev/null || echo "0")
# For submodules configured to merge upstream changes conservatively,
# never jump to upstream/origin by timestamp here. Let the pull flow
# perform a regular merge on a branch instead.
if [ "$upstream_policy" = "merge-if-clean" ] && [ "$expected_timestamp" -lt "$current_timestamp" ]; then
echo "📌 Parent pointer is stale for $sub — advancing to current commit: $current_commit ($(git show -s --format='%ci' "$current_commit" 2>/dev/null || echo 'unknown date'))"
cd_webroot
git add "$sub"
echo "🔵 Updated parent repo pointer for $sub to current merged commit"
# Update to the newest available commit if it's newer than current
elif [ "$newest_timestamp" -gt "$current_timestamp" ] && [ "$newest_commit" != "$current_commit" ]; then
echo "⬆️ Updating $sub to newer commit from $update_source: $newest_commit ($(git show -s --format='%ci' "$newest_commit" 2>/dev/null || echo 'unknown date'))"
git checkout "$newest_commit" 2>/dev/null || echo "⚠️ Failed to checkout $newest_commit in $sub"
# Update parent repo to point to the newest commit
cd_webroot
git add "$sub"
echo "🔵 Updated parent repo to use newer $sub commit from $update_source"
elif [ "$expected_timestamp" -gt "$current_timestamp" ]; then
echo "⬆️ Updating $sub to parent's expected commit: $expected_commit ($(git show -s --format='%ci' "$expected_commit" 2>/dev/null || echo 'unknown date'))"
git checkout "$expected_commit" 2>/dev/null || echo "⚠️ Failed to checkout $expected_commit in $sub"
elif [ "$expected_timestamp" -lt "$current_timestamp" ]; then
echo "📌 Parent pointer is stale for $sub — advancing to: $current_commit ($(git show -s --format='%ci' "$current_commit" 2>/dev/null || echo 'unknown date'))"
echo " ↳ Parent repo had stale pointer to: $expected_commit ($(git show -s --format='%ci' "$expected_commit" 2>/dev/null || echo 'unknown date'))"
# Update parent repo to point to the newer commit
cd_webroot
git add "$sub"
echo "🔵 Updated parent repo pointer for $sub to latest remote commit"
else
echo "✅ $sub is already at the correct commit"
fi
cd_webroot
else
echo "⚠️ Could not determine commit information for $sub"
cd_webroot
fi
fi
done
echo "✅ Safe submodule update completed"
}
# Safely update a single submodule without reverting to older commits
safe_single_submodule_update() {
local sub="$1"
echo "🛡️ Safely updating submodule: $sub"
if [ -d "$sub" ] && [ -e "$sub/.git" ]; then
cd "$sub"
# Always fetch latest from parent repository first
echo "📥 Fetching latest from parent repository for $sub..."
git fetch origin main 2>/dev/null || git fetch origin master 2>/dev/null || echo "⚠️ Could not fetch from origin"
# Also try to fetch from upstream if it exists
if git remote | grep -q upstream; then
git fetch upstream main 2>/dev/null || git fetch upstream master 2>/dev/null || echo "⚠️ Could not fetch from upstream"
fi
local upstream_policy=$(submodule_upstream_policy "$sub")
# Get current commit hash and timestamp
local current_commit=$(git rev-parse HEAD 2>/dev/null || echo "")
local current_timestamp=""
if [ -n "$current_commit" ]; then
current_timestamp=$(git show -s --format=%ct "$current_commit" 2>/dev/null || echo "0")
fi
# Get latest commit from origin/main (or master)
local latest_origin_commit=$(git rev-parse origin/main 2>/dev/null || git rev-parse origin/master 2>/dev/null || echo "")
local latest_origin_timestamp=""