-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshipyard.sh
More file actions
executable file
·2164 lines (1789 loc) · 71.3 KB
/
Copy pathshipyard.sh
File metadata and controls
executable file
·2164 lines (1789 loc) · 71.3 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
# ==============================================================================
# Shipyard - Laravel Sail Project Setup Script
# ==============================================================================
# Sets up Laravel Sail projects with automatic port assignment, SSL certificates,
# and local domain configuration. Manages a shared registry to prevent port
# conflicts across multiple projects.
#
# Usage: shipyard [options]
# ==============================================================================
set -euo pipefail
# Require Bash 3.2+
if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 3 ] || { [ "${BASH_VERSINFO[0]}" -eq 3 ] && [ "${BASH_VERSINFO[1]}" -lt 2 ]; }; then
echo "Error: Shipyard requires Bash 3.2 or newer. Detected: ${BASH_VERSION:-unknown}" >&2
exit 1
fi
# ==============================================================================
# VERSION
# ==============================================================================
readonly VERSION="0.4.0"
# ==============================================================================
# CONSTANTS & CONFIGURATION
# ==============================================================================
# Exit codes
readonly EXIT_SUCCESS=0
readonly EXIT_COMPOSE_NOT_FOUND=1
readonly EXIT_ENV_NOT_FOUND=2
readonly EXIT_ENV_HAS_PORTS=3
readonly EXIT_LOCK_TIMEOUT=4
readonly EXIT_REGISTRY_WRITE_FAILED=5
readonly EXIT_ENV_WRITE_FAILED=6
readonly EXIT_NO_PORTS_AVAILABLE=7
readonly EXIT_ALREADY_REGISTERED=8
readonly EXIT_REGISTRY_CORRUPTED=9
readonly EXIT_DOCKER_NOT_INSTALLED=10
readonly EXIT_DOCKER_NOT_RUNNING=11
readonly EXIT_ENV_ALREADY_CONFIGURED=12
readonly EXIT_USER_CANCELLED=130
# File paths
readonly REGISTRY_DIR="$HOME/.config/shipyard"
readonly REGISTRY_FILE="$REGISTRY_DIR/projects.conf"
readonly LOCK_FILE="$REGISTRY_DIR/projects.conf.lock"
readonly LOCK_TIMEOUT=10
readonly COMPOSE_FILE="docker-compose.yml"
readonly ENV_FILE=".env"
# Valet/Herd configuration
readonly VALET_CERT_DIR="$HOME/.config/valet/Certificates"
readonly HERD_CERT_DIR="$HOME/Library/Application Support/Herd/config/valet/Certificates"
readonly PROJECT_CERT_DIR="certificates"
readonly DOMAIN_TLD="test"
# Lock state
readonly LOCK_FD=200
LOCK_ACQUIRED=false
# Registry storage (associative arrays simulated with naming convention)
declare -a REGISTRY_PROJECTS=()
declare -a REGISTRY_ALL_PORTS=()
# Port assignments for current project (Bash 3.2 compatible key/value storage)
declare -a PORT_ASSIGNMENT_KEYS=()
declare -a PORT_ASSIGNMENT_VALUES=()
# Project state
PROJECT_NAME=""
# Domain registration state
DOMAIN_REGISTERED=false
REGISTERED_DOMAIN=""
SELECTED_DEV_TOOL="" # "valet" or "herd"
VALET_AVAILABLE=false
HERD_AVAILABLE=false
USE_SECURE_PROXY=true # Whether to use --secure flag for HTTPS
# User input collection (collected upfront)
declare -a COMPOSER_REPO_USERNAMES=()
declare -a COMPOSER_REPO_PASSWORDS=()
REGISTER_DOMAIN=false
USER_DOMAIN_NAME=""
RUN_POST_SETUP=""
# ==============================================================================
# COLORS & STYLING
# ==============================================================================
# Check if colors should be disabled
if [[ -z "${NO_COLOR:-}" ]] && [[ -t 1 ]]; then
# Color codes
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly GREEN='\033[0;32m'
readonly RED='\033[0;31m'
readonly YELLOW='\033[1;33m'
readonly BOLD='\033[1m'
readonly DIM='\033[2m'
readonly NC='\033[0m' # No Color
else
# No colors
readonly BLUE=""
readonly CYAN=""
readonly GREEN=""
readonly RED=""
readonly YELLOW=""
readonly BOLD=""
readonly DIM=""
readonly NC=""
fi
# ==============================================================================
# LOGGING FUNCTIONS
# ==============================================================================
log_info() {
echo "$1"
}
log_success() {
echo -e "${GREEN}✓${NC} $1"
}
log_error() {
echo -e "${RED}Error:${NC} $1" >&2
}
exit_with_error() {
local exit_code=$1
shift
log_error "$*"
exit "$exit_code"
}
# ==============================================================================
# HELP & VERSION FUNCTIONS
# ==============================================================================
show_version() {
echo "Shipyard v$VERSION"
}
show_help() {
show_title
echo ""
cat << EOF
Usage:
shipyard init Initialize a Laravel Sail project
shipyard list List all registered projects
shipyard cleanup Clean up Docker resources and stale projects
shipyard [options]
Commands:
init Set up the Laravel Sail project in current directory
(automatic port assignment, domain configuration, etc.)
list Show all registered projects from config file
cleanup Clean up stale projects from registry
Options:
--version, -v Show version
--update Update to latest version
--help, -h Show this help
Examples:
shipyard init # Set up project in current directory
shipyard list # Show all registered projects
shipyard cleanup # Clean up Docker resources and stale projects
shipyard --update # Update Shipyard to latest version
Features:
• Automatic port assignment with conflict detection
• Local domain registration (Valet/Herd)
• SSL certificate management
• Composer installation with private repo support
• Interactive setup wizard
Documentation: https://github.com/wotzebra/shipyard
EOF
}
show_title() {
echo -e "${CYAN}"
cat << 'EOF'
_____ __ _ _
/ ___// /_ (_)___ __ ______ ___________//
\__ \/ __ \/ / __ \/ / / / __ `/ ___/ __ /
___/ / / / / / /_/ / /_/ / /_/ / / / /_/ /
/____/_/ /_/_/ .___/\__, /\__,_/_/ \__,_/
/_/ /____/
EOF
echo -e "${NC}"
echo -e "⚓ ${DIM}v${VERSION} - Laravel Sail Project Setup${NC}"
echo ""
}
# ==============================================================================
# UPDATE FUNCTIONS
# ==============================================================================
fetch_latest_version() {
# Fetch latest version from GitHub API
# Args:
# $1 - timeout in seconds (optional, default: no timeout)
# Returns:
# 0 if successful (sets LATEST_VERSION variable)
# 1 if failed
local timeout_args=""
if [ -n "${1:-}" ]; then
timeout_args="--connect-timeout $1 --max-time $1"
fi
local API_RESPONSE
API_RESPONSE=$(curl -fsSL $timeout_args https://api.github.com/repos/wotzebra/shipyard/releases/latest 2>/dev/null)
if [ -z "$API_RESPONSE" ]; then
return 1
fi
# Extract version tag (remove 'v' prefix)
LATEST_VERSION=$(echo "$API_RESPONSE" | grep '"tag_name"' | sed -E 's/.*"v([^"]+)".*/\1/')
if [ -z "$LATEST_VERSION" ]; then
return 1
fi
return 0
}
perform_update() {
# Perform the actual update download and installation
# Args:
# $1 - latest version string
local latest_version="$1"
log_info "Updating to v$latest_version..."
# Get script path
local SCRIPT_PATH
SCRIPT_PATH=$(realpath "$0")
local TEMP_FILE="${SCRIPT_PATH}.tmp"
# Download latest release
local DOWNLOAD_URL="https://github.com/wotzebra/shipyard/releases/download/v${latest_version}/shipyard.sh"
if ! curl -fsSL "$DOWNLOAD_URL" -o "$TEMP_FILE"; then
log_error "Failed to download update"
rm -f "$TEMP_FILE"
echo ""
echo "Download URL: $DOWNLOAD_URL"
echo ""
echo "Please try again or download manually from:"
echo "https://github.com/wotzebra/shipyard/releases"
exit 1
fi
# Verify download is not empty
if [ ! -s "$TEMP_FILE" ]; then
log_error "Downloaded file is empty"
rm -f "$TEMP_FILE"
exit 1
fi
# Replace current script atomically
chmod +x "$TEMP_FILE"
if ! mv "$TEMP_FILE" "$SCRIPT_PATH"; then
log_error "Failed to replace script"
rm -f "$TEMP_FILE"
exit 1
fi
echo ""
log_success "Successfully updated to v$latest_version"
}
update_self() {
log_info "Checking for updates..."
if ! fetch_latest_version; then
log_error "Could not fetch latest version from GitHub"
echo ""
echo "This might be due to:"
echo " • Network connectivity issues"
echo " • GitHub API rate limiting"
echo ""
echo "Try again later or check: https://github.com/wotzebra/shipyard/releases"
exit 1
fi
# Compare versions
if [ "$VERSION" = "$LATEST_VERSION" ]; then
log_success "Already at latest version (v$VERSION)"
return 0
fi
echo ""
log_info "Current version: v$VERSION"
log_info "Latest version: v$LATEST_VERSION"
echo ""
perform_update "$LATEST_VERSION"
echo ""
echo "Run 'shipyard --version' to verify"
}
check_for_updates() {
# Silently check for updates (don't block on failure)
# Uses 5-second timeout to avoid hanging
if ! fetch_latest_version 5; then
# Silently continue if check fails
return 0
fi
# If we're on the latest version, continue silently
if [ "$VERSION" = "$LATEST_VERSION" ]; then
return 0
fi
# Show update warning
echo ""
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}⚠️ UPDATE AVAILABLE${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e " ${DIM}Current version:${NC} v$VERSION"
echo -e " ${BOLD}Latest version:${NC} ${GREEN}v$LATEST_VERSION${NC}"
echo ""
echo " It's recommended to update before continuing."
echo ""
# Prompt user
read -r -p "Do you want to update now? [y/N] " response
if [[ "$response" =~ ^[Yy]$ ]]; then
echo ""
perform_update "$LATEST_VERSION"
echo ""
echo "Please run 'shipyard' again to continue with the updated version."
exit 0
fi
echo ""
echo "Continuing with current version..."
echo ""
}
# ==============================================================================
# ARGUMENT PARSING
# ==============================================================================
parse_arguments() {
case "${1:-}" in
init)
# Run main setup
return 0
;;
cleanup)
# Run cleanup command
run_cleanup_command
exit 0
;;
list)
# List registered projects
run_list_command
exit 0
;;
--version|-v)
show_version
exit 0
;;
--update)
update_self
exit 0
;;
--help|-h)
show_help
exit 0
;;
"")
# No arguments, show help
show_help
exit 0
;;
*)
log_error "Unknown command or option: $1"
echo ""
show_help
exit 1
;;
esac
}
# ==============================================================================
# CLEANUP & LOCKING FUNCTIONS
# ==============================================================================
cleanup_on_exit() {
local exit_code=$?
# Release lock if acquired
release_lock
# If interrupted (Ctrl+C), print a message
if [ $exit_code -eq 130 ]; then
echo ""
log_info "Script interrupted by user. Cleaning up..."
fi
}
handle_interrupt() {
echo ""
log_info "Received interrupt signal (Ctrl+C). Exiting..."
exit $EXIT_USER_CANCELLED
}
acquire_lock() {
# Create directory if it doesn't exist
mkdir -p "$REGISTRY_DIR"
# Use mkdir as atomic lock (works on all Unix systems without flock)
local attempts=0
local max_attempts=$((LOCK_TIMEOUT * 10)) # Check every 0.1 seconds
while [ $attempts -lt $max_attempts ]; do
# Try to create lock directory (atomic operation)
if mkdir "$LOCK_FILE" 2>/dev/null; then
LOCK_ACQUIRED=true
return 0
fi
# Lock exists, wait and retry
sleep 0.1
attempts=$((attempts + 1))
done
# Timeout reached
exit_with_error $EXIT_LOCK_TIMEOUT \
"Failed to acquire lock after ${LOCK_TIMEOUT}s. Another process may be using the project registry."
}
release_lock() {
if [ "$LOCK_ACQUIRED" = true ]; then
# Remove lock directory
rmdir "$LOCK_FILE" 2>/dev/null || true
LOCK_ACQUIRED=false
fi
}
# ==============================================================================
# VALIDATION FUNCTIONS
# ==============================================================================
validate_docker() {
# Check if Docker is installed
if ! command -v docker >/dev/null 2>&1; then
exit_with_error $EXIT_DOCKER_NOT_INSTALLED \
"Docker is not installed or not in PATH.
Please install Docker Desktop from https://www.docker.com/products/docker-desktop"
fi
log_success "Docker is installed"
# Check if Docker daemon is running
if ! docker info >/dev/null 2>&1; then
exit_with_error $EXIT_DOCKER_NOT_RUNNING \
"Docker is installed but not running.
Please start Docker Desktop and try again."
fi
log_success "Docker is running"
}
check_docker_networks() {
# Check for Docker network address pool exhaustion
# This is a common issue when too many unused networks exist
# Count total bridge networks (excluding default bridge)
local total_networks
total_networks=$(docker network ls --filter "driver=bridge" --format "{{.Name}}" 2>/dev/null | grep -v "^bridge$" | wc -l | tr -d ' ')
# If there are many networks, check if cleanup might help
if [ "$total_networks" -gt 20 ]; then
echo ""
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}⚠️ WARNING: Many Docker networks detected (${BOLD}$total_networks${NC}${YELLOW})${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e " ${DIM}Docker may fail to create new networks due to IP address pool exhaustion.${NC}"
echo -e " ${DIM}This commonly happens with error:${NC}"
echo -e " ${RED}'could not find an available, non-overlapping IPv4 address pool'${NC}"
echo ""
echo -e " Cleaning up unused Docker networks can help prevent this issue."
echo ""
read -r -p "Clean up unused networks now? [y/N] " response
if [[ "$response" =~ ^[Yy]$ ]]; then
echo ""
echo "Cleaning up unused Docker networks..."
local before_count
before_count=$(docker network ls --filter "driver=bridge" --format "{{.Name}}" 2>/dev/null | grep -v "^bridge$" | wc -l | tr -d ' ')
if docker network prune -f >/dev/null 2>&1; then
local after_count
after_count=$(docker network ls --filter "driver=bridge" --format "{{.Name}}" 2>/dev/null | grep -v "^bridge$" | wc -l | tr -d ' ')
local removed=$((before_count - after_count))
log_success "Removed $removed unused network(s)"
else
log_error "Failed to clean up networks"
echo -e "${DIM}You may need to run: docker network prune -f${NC}"
fi
echo ""
else
echo ""
echo -e "${DIM}→ Skipping network cleanup. If you encounter network errors, run:${NC}"
echo -e "${DIM} docker network prune -f${NC}"
echo ""
fi
fi
}
validate_docker_compose() {
if [ ! -f "$COMPOSE_FILE" ]; then
exit_with_error $EXIT_COMPOSE_NOT_FOUND "docker-compose file not found: $COMPOSE_FILE"
fi
log_success "docker-compose.yml found"
}
validate_env_file() {
if [ ! -f "$ENV_FILE" ]; then
# Check if .env.example exists
if [ -f ".env.example" ]; then
log_info "Creating .env from .env.example..."
cp .env.example "$ENV_FILE"
log_success ".env file created from .env.example"
else
exit_with_error $EXIT_ENV_NOT_FOUND \
".env file not found and .env.example does not exist.
Please create a .env file or .env.example before running this script."
fi
else
log_success ".env file found"
fi
}
extract_composer_repositories() {
# Extract repository URLs from composer.json
if [ ! -f "composer.json" ]; then
echo ""
log_error "composer.json not found in current directory"
exit 1
fi
# Use grep and sed to extract repository URLs (simple parsing, works for most cases)
# This extracts URLs from the "repositories" array and removes https:// prefix
grep -A 2 '"type".*"composer"' composer.json | grep '"url"' | sed -E 's/.*"url"[[:space:]]*:[[:space:]]*"https?:\/\/([^"]+)".*/\1/'
}
detect_php_version() {
# Detect PHP version from docker-compose.yml
# Looks for patterns like: ./vendor/laravel/sail/runtimes/8.4 or sail-8.4/app
local php_version=""
if [ ! -f "$COMPOSE_FILE" ]; then
log_warning "docker-compose.yml not found, defaulting to PHP 8.4"
echo "84"
return
fi
# Try to extract version from context path (e.g., ./vendor/laravel/sail/runtimes/8.4)
php_version=$(grep -E 'context:.*runtimes/[0-9]+\.[0-9]+' "$COMPOSE_FILE" | sed -E 's/.*runtimes\/([0-9]+)\.([0-9]+).*/\1\2/' | head -n 1)
# If not found, try to extract from image name (e.g., sail-8.4/app)
if [ -z "$php_version" ]; then
php_version=$(grep -E 'image:.*sail-[0-9]+\.[0-9]+' "$COMPOSE_FILE" | sed -E 's/.*sail-([0-9]+)\.([0-9]+).*/\1\2/' | head -n 1)
fi
# Default to 8.4 if not found
if [ -z "$php_version" ]; then
log_warning "Could not detect PHP version from docker-compose.yml, defaulting to PHP 8.4"
echo "84"
else
echo "$php_version"
fi
}
is_vite_installed() {
[ -f "package.json" ] && grep -q '"vite"' package.json
}
is_laravel_mix_installed() {
[ -f "package.json" ] && grep -q '"laravel-mix"' package.json
}
write_composer_auth_json() {
local repositories=($(extract_composer_repositories))
if [ ${#repositories[@]} -eq 0 ]; then
return 0
fi
log_info "Writing auth.json with private repository credentials..."
# Build the http-basic JSON block
local http_basic_entries=""
local repo_index=0
for repo in "${repositories[@]}"; do
local username="${COMPOSER_REPO_USERNAMES[$repo_index]}"
local password="${COMPOSER_REPO_PASSWORDS[$repo_index]}"
if [ -n "$http_basic_entries" ]; then
http_basic_entries="$http_basic_entries,"$'\n'
fi
http_basic_entries="${http_basic_entries} \"$repo\": {\"username\": \"$username\", \"password\": \"$password\"}"
repo_index=$((repo_index + 1))
done
cat > auth.json <<EOF
{
"http-basic": {
$http_basic_entries
}
}
EOF
log_success "auth.json written"
# Ensure auth.json is in .gitignore
if [ -f ".gitignore" ]; then
if ! grep -qxF "auth.json" .gitignore; then
echo "auth.json" >> .gitignore
log_success "auth.json added to .gitignore"
fi
else
echo "auth.json" > .gitignore
log_success ".gitignore created with auth.json"
fi
echo ""
}
run_composer_install() {
echo ""
log_info "=========================================="
log_info "Installing Composer dependencies..."
log_info "=========================================="
echo ""
# Detect PHP version from docker-compose.yml
local php_version=$(detect_php_version)
local composer_php_version="$php_version"
# Use PHP 8.4 composer image when project runtime is 8.5 (see https://github.com/laravel/sail-server/pull/35)
if [ "$php_version" = "85" ]; then
composer_php_version="84"
fi
local composer_image="laravelsail/php${composer_php_version}-composer:latest"
if [ "$php_version" = "$composer_php_version" ]; then
log_info "Using PHP ${php_version:0:1}.${php_version:1} composer image: $composer_image"
else
log_info "Detected PHP ${php_version:0:1}.${php_version:1}; using PHP ${composer_php_version:0:1}.${composer_php_version:1} composer image: $composer_image"
fi
echo ""
log_info "Running composer install via Docker..."
echo ""
docker run --rm -u "$(id -u):$(id -g)" -v "$(pwd):/var/www/html" -w /var/www/html "$composer_image" composer install --ignore-platform-reqs
if [ $? -ne 0 ]; then
echo ""
log_error "Composer install failed. Please check your credentials and try again."
exit 9
fi
log_success "Composer dependencies installed"
echo ""
}
check_env_already_initialized() {
# Check if .env file exists
if [ -f "$ENV_FILE" ]; then
exit_with_error $EXIT_ENV_ALREADY_CONFIGURED \
".env file already exists in this project.
File: $ENV_FILE
To run 'shipyard init', please remove or rename the .env file first."
fi
}
check_env_for_ports() {
local found_ports=()
local line_num=0
while IFS= read -r line; do
line_num=$((line_num + 1))
# Match Docker Sail port variables: APP_PORT, VITE_PORT, FORWARD_*_PORT
# This specifically targets ports that are managed by this script
if [[ "$line" =~ (^|[[:space:]])(APP_PORT|VITE_PORT|FORWARD_[A-Z_]*_PORT)[[:space:]]*= ]]; then
local var_name="${BASH_REMATCH[2]}"
found_ports+=(" - $var_name (line $line_num)")
fi
done < "$ENV_FILE"
if [ ${#found_ports[@]} -gt 0 ]; then
log_error ".env already contains port definitions."
echo "" >&2
echo "Found these port variables:" >&2
printf '%s\n' "${found_ports[@]}" >&2
echo "" >&2
echo "Please remove all *_PORT variables from .env before running this script." >&2
exit $EXIT_ENV_HAS_PORTS
fi
log_success "No existing port definitions in .env"
}
# ==============================================================================
# PORT CONVERSION FUNCTION (EXISTING LOGIC PRESERVED)
# ==============================================================================
convert_port() {
local port=$1
# If port is already 4+ digits and ends with 00, return as-is
if [ ${#port} -ge 4 ] && [[ $port =~ 00$ ]]; then
echo "$port"
return
fi
# Convert port to at least 4 digits ending in 00
if [ ${#port} -eq 2 ]; then
# 80 -> 8000
echo "${port}00"
elif [ ${#port} -eq 3 ]; then
# 100 -> 10000
echo "${port}00"
elif [ ${#port} -eq 4 ]; then
# 5173 -> 5100
# Strip last 2 digits and add 00
echo "$((${port:0:2}00))"
elif [ ${#port} -gt 4 ]; then
# For 5+ digit ports, round down to nearest 100
local base=$((port / 100))
echo "$((base * 100))"
else
# Single digit: 6 -> 6000
echo "${port}000"
fi
}
# ==============================================================================
# REGISTRY FUNCTIONS (INI FILE HANDLING)
# ==============================================================================
# Sanitize project name for use in bash variable names (replace - with _)
sanitize_project_name() {
echo "$1" | tr '-' '_' | tr '.' '_'
}
add_registry_key() {
local project_sanitized=$1
local key=$2
local keys_var="registry_${project_sanitized}__keys"
local existing_keys
eval "existing_keys=\"\${$keys_var:-}\""
case " $existing_keys " in
*" $key "*) ;;
*)
if [ -n "$existing_keys" ]; then
existing_keys="$existing_keys $key"
else
existing_keys="$key"
fi
eval "$keys_var=\"\$existing_keys\""
;;
esac
}
get_registry_keys() {
local project_sanitized=$1
local keys_var="registry_${project_sanitized}__keys"
local existing_keys
eval "existing_keys=\"\${$keys_var:-}\""
if [ -z "$existing_keys" ]; then
return 0
fi
printf '%s\n' $existing_keys
}
parse_ini_file() {
# Reset global arrays so repeated calls don't accumulate duplicates
REGISTRY_PROJECTS=()
REGISTRY_ALL_PORTS=()
# Reset parsed registry variables from previous parse runs
local parsed_var
while IFS= read -r parsed_var; do
unset "$parsed_var"
done < <(compgen -v | grep '^registry_' || true)
# If registry doesn't exist yet, that's OK (first run)
if [ ! -f "$REGISTRY_FILE" ]; then
return 0
fi
local current_section=""
local current_section_sanitized=""
local line_num=0
while IFS= read -r line; do
line_num=$((line_num + 1))
# Skip empty lines and comments
[[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
# Section header: [project-name]
if [[ "$line" =~ ^[[:space:]]*\[([^]]+)\][[:space:]]*$ ]]; then
current_section="${BASH_REMATCH[1]}"
current_section_sanitized=$(sanitize_project_name "$current_section")
REGISTRY_PROJECTS+=("$current_section")
eval "registry_${current_section_sanitized}__keys=''"
# Key=value pair
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*=[[:space:]]*(.+)[[:space:]]*$ ]]; then
local key="${BASH_REMATCH[1]}"
local value="${BASH_REMATCH[2]}"
if [ -z "$current_section" ]; then
exit_with_error $EXIT_REGISTRY_CORRUPTED \
"Registry file is corrupted (line $line_num): Key outside of section"
fi
# Store in global variables with naming convention: registry_{project}_{key}
# Use sanitized name for variable names
eval "registry_${current_section_sanitized}_${key}=\"${value}\""
add_registry_key "$current_section_sanitized" "$key"
# If this is a port value, add to all ports list
if [[ "$key" =~ _PORT$ ]] && [[ "$value" =~ ^[0-9]+$ ]]; then
REGISTRY_ALL_PORTS+=("$value")
fi
else
# Malformed line
exit_with_error $EXIT_REGISTRY_CORRUPTED \
"Registry file is corrupted or malformed.
File: $REGISTRY_FILE
Invalid line $line_num: \"$line\"
Please fix the registry file manually or delete it to start fresh."
fi
done < "$REGISTRY_FILE"
}
cleanup_stale_projects() {
# Remove projects from registry whose paths no longer exist
# If registry doesn't exist, nothing to clean
if [ ! -f "$REGISTRY_FILE" ]; then
return 0
fi
local projects_to_remove=()
local removed_count=0
# Check each project's path
for project in "${REGISTRY_PROJECTS[@]}"; do
local project_sanitized=$(sanitize_project_name "$project")
local path_var="registry_${project_sanitized}_path"
local project_path="${!path_var}"
if [ -n "$project_path" ] && [ ! -d "$project_path" ]; then
projects_to_remove+=("$project")
log_info " × Project '$project' path no longer exists: $project_path"
# Check if project has a domain and proxy service registered
local domain_var="registry_${project_sanitized}_domain"
local proxy_var="registry_${project_sanitized}_proxy_service"
local project_domain="${!domain_var:-}"
local project_proxy="${!proxy_var:-}"
# Clean up proxy if it exists
if [ -n "$project_domain" ] && [ -n "$project_proxy" ]; then
log_info " Removing proxy: $project_domain (via $project_proxy)"
# Extract domain name without TLD
local domain_name="${project_domain%.*}"
# Run unproxy command silently
if $project_proxy unproxy "$domain_name" >/dev/null 2>&1; then
log_info " ✓ Proxy removed successfully"
else
log_info " ! Failed to remove proxy (may have been already removed)"
fi
fi
# Clean up Sail volumes if they exist
# The project name is already normalized (lowercase, valid Docker Compose format)
log_info " Checking for Sail volumes to clean up..."
# Find all volumes matching the pattern: project_sail-*
local sail_volumes=$(docker volume ls --format "{{.Name}}" 2>/dev/null | grep "^${project}_sail-" || true)
if [ -n "$sail_volumes" ]; then
local volume_count=0
while IFS= read -r volume_name; do
if [ -n "$volume_name" ]; then
if docker volume rm "$volume_name" >/dev/null 2>&1; then
log_info " ✓ Removed volume: $volume_name"
volume_count=$((volume_count + 1))
else
log_info " ! Failed to remove volume: $volume_name (may be in use)"
fi
fi
done <<< "$sail_volumes"
if [ $volume_count -gt 0 ]; then
log_info " ✓ Removed $volume_count Sail volume(s)"
fi
else
log_info " No Sail volumes found"
fi
removed_count=$((removed_count + 1))
fi
done
# If no projects to remove, we're done
if [ ${#projects_to_remove[@]} -eq 0 ]; then
return 0
fi
echo ""
log_info "Cleaning up $removed_count stale project(s) from registry..."
# Remove stale projects from REGISTRY_PROJECTS array
local updated_projects=()
for project in "${REGISTRY_PROJECTS[@]}"; do
local should_keep=true
for remove_project in "${projects_to_remove[@]}"; do
if [ "$project" = "$remove_project" ]; then
should_keep=false
break
fi
done
if [ "$should_keep" = true ]; then
updated_projects+=("$project")
fi
done
REGISTRY_PROJECTS=("${updated_projects[@]}")
# Rebuild REGISTRY_ALL_PORTS array (exclude removed projects)
REGISTRY_ALL_PORTS=()
for project in "${REGISTRY_PROJECTS[@]}"; do
local project_sanitized=$(sanitize_project_name "$project")
for key in $(get_registry_keys "$project_sanitized"); do
local var="registry_${project_sanitized}_${key}"
local value="${!var:-}"
# If this is a port value, add to all ports list
if [[ "$key" =~ _PORT$ ]] && [[ "$value" =~ ^[0-9]+$ ]]; then
REGISTRY_ALL_PORTS+=("$value")
fi
done
done
# Rewrite the registry file without stale projects
local temp_file="$REGISTRY_FILE.tmp"
{
echo "# Shipyard Project Registry"
echo "# This file tracks project configurations including ports, domains, and proxy services"
echo "# Format: INI with [project-name] sections"
echo ""
# Write only existing projects
for project in "${REGISTRY_PROJECTS[@]}"; do