forked from Dicklesworthstone/beads_rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·1222 lines (1062 loc) · 42.9 KB
/
install.sh
File metadata and controls
executable file
·1222 lines (1062 loc) · 42.9 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
#
# br (beads_rust) installer - Ultra-robust multi-platform installer with beautiful output
#
# One-liner install:
# curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/beads_rust/main/install.sh?$(date +%s)" | bash
#
# Options:
# --version vX.Y.Z Install specific version (default: latest)
# --dest DIR Install to DIR (default: ~/.local/bin)
# --system Install to /usr/local/bin (requires sudo)
# --easy-mode Auto-update PATH in shell rc files
# --verify Run self-test after install
# --artifact-url URL Use a custom release artifact URL
# --checksum SHA Provide expected SHA256 checksum
# --checksum-url URL Provide a custom checksum URL
# --from-source Build from source instead of downloading binary
# --quiet Suppress non-error output
# --no-gum Disable gum formatting even if available
# --skip-skills Don't install Claude Code / Codex skills
# --uninstall Remove br and clean up
# --help Show this help
#
set -euo pipefail
umask 022
shopt -s lastpipe 2>/dev/null || true
# ============================================================================
# Configuration
# ============================================================================
VERSION="${VERSION:-}"
OWNER="${OWNER:-Dicklesworthstone}"
REPO="${REPO:-beads_rust}"
BINARY_NAME="br"
DEST_DEFAULT="$HOME/.local/bin"
DEST="${DEST:-$DEST_DEFAULT}"
EASY=0
QUIET=0
VERIFY=0
FROM_SOURCE=0
UNINSTALL=0
CHECKSUM="${CHECKSUM:-}"
CHECKSUM_URL="${CHECKSUM_URL:-}"
ARTIFACT_URL="${ARTIFACT_URL:-}"
LOCK_FILE="/tmp/br-install.lock"
SYSTEM=0
NO_GUM=0
SKIP_SKILLS=0
MAX_RETRIES=3
DOWNLOAD_TIMEOUT=120
INSTALLER_VERSION="2.0.0"
# Colors for fallback output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
DIM='\033[2m'
ITALIC='\033[3m'
NC='\033[0m'
# Gum availability flag
GUM_AVAILABLE=false
# ============================================================================
# Gum auto-installation (from giil)
# ============================================================================
try_install_gum() {
# Skip if in CI or non-interactive
[[ -z "${CI:-}" ]] || return 1
[[ -t 1 ]] || return 1
# Inline OS detection
local os="unknown"
case "$(uname -s)" in
Darwin*) os="macos" ;;
Linux*) os="linux" ;;
esac
# Try to install gum quietly
case "$os" in
macos)
if command -v brew &> /dev/null; then
brew install gum &>/dev/null && return 0
fi
;;
linux)
# Try common package managers
if command -v apt-get &> /dev/null; then
(
sudo mkdir -p /etc/apt/keyrings 2>/dev/null
curl -fsSL https://repo.charm.sh/apt/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/charm.gpg 2>/dev/null
echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" | sudo tee /etc/apt/sources.list.d/charm.list >/dev/null
sudo apt-get update -qq && sudo apt-get install -y -qq gum
) &>/dev/null && return 0
elif command -v dnf &> /dev/null; then
(
echo '[charm]
name=Charm
baseurl=https://repo.charm.sh/yum/
enabled=1
gpgcheck=1
gpgkey=https://repo.charm.sh/yum/gpg.key' | sudo tee /etc/yum.repos.d/charm.repo >/dev/null
sudo dnf install -y gum
) &>/dev/null && return 0
elif command -v pacman &> /dev/null; then
sudo pacman -S --noconfirm gum &>/dev/null && return 0
fi
# Fallback: download from GitHub releases
local arch
arch=$(uname -m)
case "$arch" in
x86_64) arch="amd64" ;;
aarch64|arm64) arch="arm64" ;;
*) return 1 ;;
esac
local tmp_dir
tmp_dir=$(mktemp -d)
local gum_version="0.14.5"
local gum_url="https://github.com/charmbracelet/gum/releases/download/v${gum_version}/gum_${gum_version}_Linux_${arch}.tar.gz"
(
cd "$tmp_dir"
curl -fsSL "$gum_url" -o gum.tar.gz
tar -xzf gum.tar.gz
if sudo mv gum /usr/local/bin/gum 2>/dev/null; then
:
else
mkdir -p ~/.local/bin
mv gum ~/.local/bin/gum
fi
) &>/dev/null && rm -rf "$tmp_dir" && return 0
rm -rf "$tmp_dir"
;;
esac
return 1
}
check_gum() {
# Respect NO_GUM flag
if [[ "$NO_GUM" -eq 1 ]]; then
GUM_AVAILABLE=false
return 1
fi
if command -v gum &> /dev/null; then
GUM_AVAILABLE=true
return 0
fi
# Only try to install gum if interactive and not disabled
if [[ -t 1 && -z "${CI:-}" ]]; then
if try_install_gum; then
if [[ -x "${HOME}/.local/bin/gum" && ":$PATH:" != *":${HOME}/.local/bin:"* ]]; then
export PATH="${HOME}/.local/bin:${PATH}"
fi
if command -v gum &> /dev/null; then
GUM_AVAILABLE=true
return 0
fi
fi
fi
return 1
}
# ============================================================================
# Styled output functions (gum with ANSI fallback)
# ============================================================================
# Print styled banner
print_banner() {
[ "$QUIET" -eq 1 ] && return 0
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum style \
--border double \
--border-foreground 39 \
--padding "0 2" \
--margin "1 0" \
--bold \
"$(gum style --foreground 42 '🔗 br installer')" \
"$(gum style --foreground 245 'Agent-first issue tracker (beads_rust)')"
else
echo ""
echo -e "${BOLD}${BLUE}╔════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${BLUE}║${NC} ${BOLD}${GREEN}🔗 br installer${NC} ${BOLD}${BLUE}║${NC}"
echo -e "${BOLD}${BLUE}║${NC} ${DIM}Agent-first issue tracker (beads_rust)${NC} ${BOLD}${BLUE}║${NC}"
echo -e "${BOLD}${BLUE}╚════════════════════════════════════════════════╝${NC}"
echo ""
fi
}
# Log functions
log_info() {
[ "$QUIET" -eq 1 ] && return 0
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum log --level info "$1" >&2
else
echo -e "${GREEN}[br]${NC} $1" >&2
fi
}
log_warn() {
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum log --level warn "$1" >&2
else
echo -e "${YELLOW}[br]${NC} $1" >&2
fi
}
log_error() {
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum log --level error "$1" >&2
else
echo -e "${RED}[br]${NC} $1" >&2
fi
}
log_step() {
[ "$QUIET" -eq 1 ] && return 0
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum style --foreground 39 "→ $1" >&2
else
echo -e "${BLUE}→${NC} $1" >&2
fi
}
log_success() {
[ "$QUIET" -eq 1 ] && return 0
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum style --foreground 82 "✓ $1" >&2
else
echo -e "${GREEN}✓${NC} $1" >&2
fi
}
log_debug() {
[[ "${DEBUG:-0}" -eq 1 ]] || return 0
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum log --level debug "$1" >&2
else
echo -e "${CYAN}[br:debug]${NC} $1" >&2
fi
}
# Spinner wrapper for long operations
# Note: gum spin can only execute external binaries, not shell functions.
# We work around this by checking if the command is a function and using bash -c.
run_with_spinner() {
local title="$1"
shift
if [[ "$GUM_AVAILABLE" == "true" && "$QUIET" -eq 0 ]]; then
# Check if first argument is a shell function
if declare -f "$1" >/dev/null 2>&1; then
# Export the function and run via bash -c
local func_name="$1"
shift
# Can't easily export functions to gum subshell, so fall back to no-spinner
log_step "$title"
"$func_name" "$@"
else
gum spin --spinner dot --title "$title" -- "$@"
fi
else
log_step "$title"
"$@"
fi
}
# Die with error
die() {
log_error "$@"
exit 1
}
# ============================================================================
# Usage / Help (gum-styled)
# ============================================================================
usage() {
check_gum || true
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum style \
--border double \
--border-foreground 39 \
--padding "1 2" \
--margin "1" \
--bold \
"$(gum style --foreground 42 '🔗 br installer v'${INSTALLER_VERSION})" \
"$(gum style --foreground 245 'Agent-first issue tracker')"
echo ""
gum style --foreground 214 --bold "SYNOPSIS"
echo " curl -fsSL .../install.sh | bash"
echo " curl -fsSL .../install.sh | bash -s -- [OPTIONS]"
echo ""
gum style --foreground 214 --bold "OPTIONS"
gum style --foreground 39 " Installation"
gum style --faint " --version vX.Y.Z Install specific version (default: latest)"
gum style --faint " --dest DIR Install to DIR (default: ~/.local/bin)"
gum style --faint " --system Install to /usr/local/bin (requires sudo)"
gum style --faint " --artifact-url URL Use a custom release artifact URL"
gum style --faint " --checksum SHA Provide expected SHA256 checksum"
gum style --faint " --checksum-url URL Provide a custom checksum URL"
gum style --faint " --from-source Build from source instead of binary"
echo ""
gum style --foreground 39 " Behavior"
gum style --faint " --easy-mode Auto-update PATH in shell rc files"
gum style --faint " --verify Run self-test after install"
gum style --faint " --quiet Suppress progress messages"
gum style --faint " --no-gum Disable gum formatting"
gum style --faint " --skip-skills Don't install Claude/Codex skills"
echo ""
gum style --foreground 39 " Maintenance"
gum style --faint " --uninstall Remove br and clean up"
gum style --faint " --help Show this help"
echo ""
gum style --foreground 214 --bold "ENVIRONMENT"
gum style --faint " HTTPS_PROXY Use HTTPS proxy for downloads"
gum style --faint " HTTP_PROXY Use HTTP proxy for downloads"
gum style --faint " BR_INSTALL_DIR Override default install directory"
gum style --faint " VERSION Override version to install"
echo ""
gum style --foreground 214 --bold "EXAMPLES"
gum style --foreground 39 " # Default install"
echo " curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/beads_rust/main/install.sh | bash"
echo ""
gum style --foreground 39 " # System install with auto PATH"
echo " curl -fsSL .../install.sh | sudo bash -s -- --system --easy-mode"
echo ""
gum style --foreground 39 " # Force source build"
echo " curl -fsSL .../install.sh | bash -s -- --from-source"
echo ""
gum style --foreground 39 " # Uninstall"
echo " curl -fsSL .../install.sh | bash -s -- --uninstall"
echo ""
gum style --foreground 214 --bold "PLATFORMS"
echo " $(gum style --foreground 82 '✓ Linux x86_64') $(gum style --foreground 245 --faint '(glibc and musl)')"
gum style --foreground 82 " ✓ Linux ARM64"
gum style --foreground 82 " ✓ macOS Intel"
gum style --foreground 82 " ✓ macOS Apple Silicon"
echo " $(gum style --foreground 82 '✓ Windows x64') $(gum style --foreground 245 --faint '(via WSL or manual)')"
echo ""
gum style --foreground 245 --italic "Installer will auto-install gum for beautiful output if not present"
else
cat <<'EOF'
br installer - Install beads_rust (br) CLI tool
Usage:
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/beads_rust/main/install.sh | bash
curl -fsSL .../install.sh | bash -s -- [OPTIONS]
Options:
--version vX.Y.Z Install specific version (default: latest)
--dest DIR Install to DIR (default: ~/.local/bin)
--system Install to /usr/local/bin (requires sudo)
--artifact-url URL Use a custom release artifact URL
--checksum SHA Provide expected SHA256 checksum
--checksum-url URL Provide a custom checksum URL
--easy-mode Auto-update PATH in shell rc files
--verify Run self-test after install
--from-source Build from source instead of downloading binary
--quiet Suppress non-error output
--no-gum Disable gum formatting even if available
--skip-skills Don't install Claude Code / Codex skills
--uninstall Remove br and clean up
Environment Variables:
HTTPS_PROXY Use HTTPS proxy for downloads
HTTP_PROXY Use HTTP proxy for downloads
BR_INSTALL_DIR Override default install directory
VERSION Override version to install
Platforms:
✓ Linux x86_64 (glibc and musl)
✓ Linux ARM64
✓ macOS Intel
✓ macOS Apple Silicon
✓ Windows x64 (via WSL or manual)
Examples:
# Default install
curl -fsSL .../install.sh | bash
# Custom prefix with easy mode
curl -fsSL .../install.sh | bash -s -- --dest=/usr/local/bin --easy-mode
# Force source build
curl -fsSL .../install.sh | bash -s -- --from-source
# Uninstall
curl -fsSL .../install.sh | bash -s -- --uninstall
EOF
fi
exit 0
}
# ============================================================================
# Argument Parsing
# ============================================================================
while [ $# -gt 0 ]; do
case "$1" in
--version) VERSION="$2"; shift 2;;
--version=*) VERSION="${1#*=}"; shift;;
--dest) DEST="$2"; shift 2;;
--dest=*) DEST="${1#*=}"; shift;;
--system) SYSTEM=1; DEST="/usr/local/bin"; shift;;
--easy-mode) EASY=1; shift;;
--verify) VERIFY=1; shift;;
--artifact-url) ARTIFACT_URL="$2"; shift 2;;
--checksum) CHECKSUM="$2"; shift 2;;
--checksum-url) CHECKSUM_URL="$2"; shift 2;;
--from-source) FROM_SOURCE=1; shift;;
--quiet|-q) QUIET=1; shift;;
--no-gum) NO_GUM=1; shift;;
--skip-skills) SKIP_SKILLS=1; shift;;
--uninstall) UNINSTALL=1; shift;;
-h|--help) usage;;
*) shift;;
esac
done
# Environment variable overrides
[ -n "${BR_INSTALL_DIR:-}" ] && DEST="$BR_INSTALL_DIR"
# Initialize gum early for beautiful output
check_gum || true
# ============================================================================
# Uninstall
# ============================================================================
do_uninstall() {
print_banner
log_step "Uninstalling br..."
if [ -f "$DEST/$BINARY_NAME" ]; then
rm -f "$DEST/$BINARY_NAME"
log_success "Removed $DEST/$BINARY_NAME"
else
log_warn "Binary not found at $DEST/$BINARY_NAME"
fi
# Remove PATH modifications from shell rc files
for rc in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" "$HOME/.config/fish/config.fish"; do
if [ -f "$rc" ] && grep -q "# br installer" "$rc" 2>/dev/null; then
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i '' '/# br installer/d' "$rc" 2>/dev/null || true
else
sed -i '/# br installer/d' "$rc" 2>/dev/null || true
fi
log_step "Cleaned $rc"
fi
done
log_success "br uninstalled successfully"
exit 0
}
[ "$UNINSTALL" -eq 1 ] && do_uninstall
# ============================================================================
# Platform Detection
# ============================================================================
detect_platform() {
local os arch
case "$(uname -s)" in
Linux*) os="linux" ;;
Darwin*) os="darwin" ;;
MINGW*|MSYS*|CYGWIN*) os="windows" ;;
*) die "Unsupported OS: $(uname -s)" ;;
esac
case "$(uname -m)" in
x86_64|amd64) arch="amd64" ;;
aarch64|arm64) arch="arm64" ;;
armv7*) arch="armv7" ;;
*) die "Unsupported architecture: $(uname -m)" ;;
esac
echo "${os}_${arch}"
}
# ============================================================================
# Version Resolution (with robust fallbacks)
# ============================================================================
resolve_version() {
if [ -n "$VERSION" ]; then return 0; fi
log_step "Resolving latest version..."
local latest_url="https://api.github.com/repos/${OWNER}/${REPO}/releases/latest"
local tag=""
local attempts=0
# Try GitHub API with retries
while [ $attempts -lt $MAX_RETRIES ] && [ -z "$tag" ]; do
attempts=$((attempts + 1))
if command -v curl &>/dev/null; then
tag=$(curl -fsSL \
--connect-timeout 10 \
--max-time 30 \
-H "Accept: application/vnd.github.v3+json" \
"$latest_url" 2>/dev/null | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/' || echo "")
elif command -v wget &>/dev/null; then
tag=$(wget -qO- --timeout=30 "$latest_url" 2>/dev/null | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/' || echo "")
fi
[ -z "$tag" ] && [ $attempts -lt $MAX_RETRIES ] && sleep 2
done
if [ -n "$tag" ] && [[ "$tag" =~ ^v[0-9] ]]; then
VERSION="$tag"
log_success "Latest version: $VERSION"
return 0
fi
# Fallback: try redirect-based resolution
log_step "Trying redirect-based version resolution..."
local redirect_url="https://github.com/${OWNER}/${REPO}/releases/latest"
if command -v curl &>/dev/null; then
tag=$(curl -fsSL -o /dev/null -w '%{url_effective}' "$redirect_url" 2>/dev/null | sed -E 's|.*/tag/||' || echo "")
fi
if [ -n "$tag" ] && [[ "$tag" =~ ^v[0-9] ]] && [[ "$tag" != *"/"* ]]; then
VERSION="$tag"
log_success "Latest version (via redirect): $VERSION"
return 0
fi
log_warn "Could not resolve latest version; will try building from source"
VERSION=""
}
# ============================================================================
# Cross-platform locking using mkdir (atomic on all POSIX systems)
# ============================================================================
LOCK_DIR="${LOCK_FILE}.d"
LOCKED=0
acquire_lock() {
if mkdir "$LOCK_DIR" 2>/dev/null; then
LOCKED=1
echo $$ > "$LOCK_DIR/pid"
return 0
fi
# Check if existing lock is stale
if [ -f "$LOCK_DIR/pid" ]; then
local old_pid
old_pid=$(cat "$LOCK_DIR/pid" 2>/dev/null || echo "")
# Check if process is still running
if [ -n "$old_pid" ] && ! kill -0 "$old_pid" 2>/dev/null; then
log_warn "Removing stale lock (PID $old_pid not running)"
rm -rf "$LOCK_DIR"
if mkdir "$LOCK_DIR" 2>/dev/null; then
LOCKED=1
echo $$ > "$LOCK_DIR/pid"
return 0
fi
fi
# Check lock age (5 minute timeout)
local lock_age=0
if [[ "$OSTYPE" == "darwin"* ]]; then
lock_age=$(( $(date +%s) - $(stat -f %m "$LOCK_DIR/pid" 2>/dev/null || echo 0) ))
else
lock_age=$(( $(date +%s) - $(stat -c %Y "$LOCK_DIR/pid" 2>/dev/null || echo 0) ))
fi
if [ "$lock_age" -gt 300 ]; then
log_warn "Removing stale lock (age: ${lock_age}s)"
rm -rf "$LOCK_DIR"
if mkdir "$LOCK_DIR" 2>/dev/null; then
LOCKED=1
echo $$ > "$LOCK_DIR/pid"
return 0
fi
fi
fi
if [ "$LOCKED" -eq 0 ]; then
die "Another installation is running. If incorrect, run: rm -rf $LOCK_DIR"
fi
}
# ============================================================================
# Cleanup
# ============================================================================
TMP=""
cleanup() {
[ -n "$TMP" ] && rm -rf "$TMP"
[ "$LOCKED" -eq 1 ] && rm -rf "$LOCK_DIR"
}
trap cleanup EXIT
# ============================================================================
# PATH modification
# ============================================================================
maybe_add_path() {
case ":$PATH:" in
*:"$DEST":*) return 0;;
*)
if [ "$EASY" -eq 1 ]; then
local updated=0
for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
if [ -f "$rc" ] && [ -w "$rc" ]; then
if ! grep -qF "$DEST" "$rc" 2>/dev/null; then
echo "" >> "$rc"
echo "export PATH=\"$DEST:\$PATH\" # br installer" >> "$rc"
fi
updated=1
fi
done
# Handle fish shell
local fish_config="$HOME/.config/fish/config.fish"
if [ -f "$fish_config" ] && [ -w "$fish_config" ]; then
if ! grep -qF "$DEST" "$fish_config" 2>/dev/null; then
echo "" >> "$fish_config"
echo "set -gx PATH $DEST \$PATH # br installer" >> "$fish_config"
fi
updated=1
fi
if [ "$updated" -eq 1 ]; then
log_warn "PATH updated; restart shell or run: export PATH=\"$DEST:\$PATH\""
else
log_warn "Add $DEST to PATH to use br"
fi
else
log_warn "Add $DEST to PATH to use br"
fi
;;
esac
}
# ============================================================================
# Fix shell alias conflicts
# ============================================================================
fix_alias_conflicts() {
# Check if 'br' is aliased to something else (common: bun run)
for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
if [ -f "$rc" ]; then
# Add unalias after any potential alias definitions
if ! grep -q "unalias br.*# br installer" "$rc" 2>/dev/null; then
if grep -q "alias br=" "$rc" 2>/dev/null || grep -q "\.bun" "$rc" 2>/dev/null; then
echo "" >> "$rc"
echo "unalias br 2>/dev/null # br installer - remove conflicting alias" >> "$rc"
log_step "Added unalias to $rc to prevent conflicts"
fi
fi
fi
done
}
# ============================================================================
# Install Claude Code / Codex skills
# ============================================================================
install_skills() {
if [ "$SKIP_SKILLS" -eq 1 ]; then
log_step "Skipping skills installation (--skip-skills)"
return 0
fi
log_step "Installing Claude Code / Codex skills..."
local skills_base_url="https://raw.githubusercontent.com/${OWNER}/${REPO}/main/skills"
local claude_skills_dir="$HOME/.claude/skills"
local codex_skills_dir="${CODEX_HOME:-$HOME/.codex}/skills"
# List of skills to install (skill_name:files separated by commas)
local skills=(
"bd-to-br-migration:SKILL.md,SELF-TEST.md,references/TRANSFORMS.md,references/BULK.md,references/PITFALLS.md,scripts/find-bd-refs.sh,scripts/verify-migration.sh,subagents/batch-migrator.md"
)
local skill
for skill in "${skills[@]}"; do
local skill_name="${skill%%:*}"
local files_str="${skill#*:}"
log_step "Installing skill: $skill_name"
# Create skill directories
mkdir -p "$claude_skills_dir/$skill_name/references" 2>/dev/null || true
mkdir -p "$claude_skills_dir/$skill_name/scripts" 2>/dev/null || true
mkdir -p "$claude_skills_dir/$skill_name/subagents" 2>/dev/null || true
mkdir -p "$codex_skills_dir/$skill_name/references" 2>/dev/null || true
mkdir -p "$codex_skills_dir/$skill_name/scripts" 2>/dev/null || true
mkdir -p "$codex_skills_dir/$skill_name/subagents" 2>/dev/null || true
# Download each file
IFS=',' read -ra files <<< "$files_str"
local file
local files_installed=0
for file in "${files[@]}"; do
local url="$skills_base_url/$skill_name/$file"
local claude_dest="$claude_skills_dir/$skill_name/$file"
local codex_dest="$codex_skills_dir/$skill_name/$file"
local tmp_file="${claude_dest}.tmp.$$"
# Download to temp file first to avoid leaving empty files on failure
if download_file "$url" "$tmp_file"; then
mv "$tmp_file" "$claude_dest"
# Make scripts executable
[[ "$file" == scripts/* ]] && chmod +x "$claude_dest" 2>/dev/null || true
log_debug "Downloaded $file to Claude skills"
files_installed=$((files_installed + 1))
# Copy to Codex skills
cp "$claude_dest" "$codex_dest" 2>/dev/null || true
[[ "$file" == scripts/* ]] && chmod +x "$codex_dest" 2>/dev/null || true
else
rm -f "$tmp_file" 2>/dev/null || true
log_debug "Could not download $file (may not exist)"
fi
done
if [ "$files_installed" -gt 0 ]; then
log_success "Installed skill: $skill_name ($files_installed files)"
else
log_warn "Skill $skill_name: no files could be downloaded"
fi
done
# Print fancy skills summary
print_skills_summary "$claude_skills_dir" "$codex_skills_dir"
}
# Print beautiful skills installation summary
print_skills_summary() {
local claude_dir="$1"
local codex_dir="$2"
[ "$QUIET" -eq 1 ] && return 0
echo ""
if [[ "$GUM_AVAILABLE" == "true" ]]; then
gum style \
--border rounded \
--border-foreground 213 \
--padding "1 2" \
--margin "1 0" \
"$(gum style --foreground 213 --bold '🎯 AI Coding Skills Installed!')" \
"" \
"$(gum style --foreground 245 'Skills help AI agents migrate from bd → br')"
echo ""
gum style --foreground 214 --bold "📍 Installed Locations"
gum style --foreground 39 " Claude Code: $(gum style --foreground 82 "$claude_dir")"
gum style --foreground 39 " Codex: $(gum style --foreground 82 "$codex_dir")"
echo ""
gum style \
--border rounded \
--border-foreground 39 \
--padding "1 2" \
"$(gum style --foreground 39 --bold '⚡ How to Use Skills')" \
"" \
"$(gum style --foreground 214 'Claude Code') $(gum style --faint '(slash command):')" \
" $(gum style --foreground 82 '/bd-to-br-migration')" \
"" \
"$(gum style --foreground 214 'Codex') $(gum style --faint '(dollar command):')" \
" $(gum style --foreground 82 '$bd-to-br-migration')"
echo ""
gum style --foreground 245 --italic "Skills auto-trigger when agents detect bd→br migration needs"
else
echo ""
echo -e "${MAGENTA}${BOLD}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${MAGENTA}${BOLD}║${NC} ${BOLD}🎯 AI Coding Skills Installed!${NC} ${MAGENTA}${BOLD}║${NC}"
echo -e "${MAGENTA}${BOLD}║${NC} ${DIM}Skills help AI agents migrate from bd → br${NC} ${MAGENTA}${BOLD}║${NC}"
echo -e "${MAGENTA}${BOLD}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}${BOLD}📍 Installed Locations${NC}"
echo -e " ${CYAN}Claude Code:${NC} ${GREEN}$claude_dir${NC}"
echo -e " ${CYAN}Codex:${NC} ${GREEN}$codex_dir${NC}"
echo ""
echo -e "${BLUE}${BOLD}╭────────────────────────────────────────────────────────────╮${NC}"
echo -e "${BLUE}${BOLD}│${NC} ${BOLD}⚡ How to Use Skills${NC} ${BLUE}${BOLD}│${NC}"
echo -e "${BLUE}${BOLD}│${NC} ${BLUE}${BOLD}│${NC}"
echo -e "${BLUE}${BOLD}│${NC} ${YELLOW}Claude Code${NC} ${DIM}(slash command):${NC} ${BLUE}${BOLD}│${NC}"
echo -e "${BLUE}${BOLD}│${NC} ${GREEN}/bd-to-br-migration${NC} ${BLUE}${BOLD}│${NC}"
echo -e "${BLUE}${BOLD}│${NC} ${BLUE}${BOLD}│${NC}"
echo -e "${BLUE}${BOLD}│${NC} ${YELLOW}Codex${NC} ${DIM}(dollar command):${NC} ${BLUE}${BOLD}│${NC}"
echo -e "${BLUE}${BOLD}│${NC} ${GREEN}\$bd-to-br-migration${NC} ${BLUE}${BOLD}│${NC}"
echo -e "${BLUE}${BOLD}╰────────────────────────────────────────────────────────────╯${NC}"
echo ""
echo -e "${DIM}${ITALIC}Skills auto-trigger when agents detect bd→br migration needs${NC}"
fi
}
# ============================================================================
# Rust installation for source builds
# ============================================================================
ensure_rust() {
if [ "${RUSTUP_INIT_SKIP:-0}" != "0" ]; then
log_step "Skipping rustup (RUSTUP_INIT_SKIP set)"
return 0
fi
if command -v cargo >/dev/null 2>&1; then
return 0
fi
if [ "$EASY" -ne 1 ] && [ -t 0 ]; then
if [[ "$GUM_AVAILABLE" == "true" ]]; then
if ! gum confirm "Rust not found. Install via rustup?"; then
log_warn "Skipping rustup"
return 1
fi
else
echo -n "Rust not found. Install via rustup? (Y/n): "
read -r ans
case "$ans" in n|N) log_warn "Skipping rustup"; return 1;; esac
fi
fi
log_step "Installing Rust via rustup..."
run_with_spinner "Installing Rust toolchain..." \
curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal
export PATH="$HOME/.cargo/bin:$PATH"
# Source cargo env
[ -f "$HOME/.cargo/env" ] && source "$HOME/.cargo/env"
}
# ============================================================================
# Pre-build cleanup for source builds
# ============================================================================
prepare_for_build() {
# Kill any stuck cargo processes
pkill -9 -f "cargo build" 2>/dev/null || true
# Clear cargo locks
rm -f ~/.cargo/.package-cache 2>/dev/null || true
rm -f ~/.cargo/registry/.crate-cache.lock 2>/dev/null || true
# Clean up old br build directories
rm -rf /tmp/br-build-* 2>/dev/null || true
# Check disk space (need at least 1GB)
local avail_kb
if [[ "$OSTYPE" == "darwin"* ]]; then
avail_kb=$(df -k /tmp | tail -1 | awk '{print $4}')
else
avail_kb=$(df -k /tmp | tail -1 | awk '{print $4}')
fi
if [ "$avail_kb" -lt 1048576 ]; then
log_warn "Low disk space in /tmp ($(( avail_kb / 1024 ))MB). Cleaning up..."
rm -rf /tmp/cargo-target 2>/dev/null || true
rm -rf ~/.cargo/registry/cache 2>/dev/null || true
fi
sleep 1
}
# ============================================================================
# Download with retry and progress
# ============================================================================
download_file() {
local url="$1"
local dest="$2"
local attempt=0
local partial="${dest}.part"
local proxy_env=()
local proxy_http="${HTTP_PROXY:-${http_proxy:-}}"
local proxy_https="${HTTPS_PROXY:-${https_proxy:-}}"
[ -n "$proxy_http" ] && proxy_env+=(HTTP_PROXY="$proxy_http" http_proxy="$proxy_http")
[ -n "$proxy_https" ] && proxy_env+=(HTTPS_PROXY="$proxy_https" https_proxy="$proxy_https")
local show_progress=0
if [ "$QUIET" -eq 0 ] && [ -t 2 ]; then
show_progress=1
fi
while [ $attempt -lt $MAX_RETRIES ]; do
attempt=$((attempt + 1))
log_debug "Download attempt $attempt for $url"
local use_resume=0
if [ -s "$partial" ]; then
use_resume=1
fi
if command -v curl &>/dev/null; then
local curl_args=(
-fL
--connect-timeout 30
--max-time "$DOWNLOAD_TIMEOUT"
--retry 2
-o "$partial"
"$url"
)
if [ "$use_resume" -eq 1 ]; then
curl_args=(--continue-at - "${curl_args[@]}")
fi
if [ "$show_progress" -eq 1 ]; then
curl_args=(--progress-bar "${curl_args[@]}")
else
curl_args=(-sS "${curl_args[@]}")
fi
if env ${proxy_env[@]+"${proxy_env[@]}"} curl "${curl_args[@]}"; then
mv -f "$partial" "$dest"
return 0
fi
elif command -v wget &>/dev/null; then
local wget_args=(
--timeout="$DOWNLOAD_TIMEOUT"
-O "$partial"
"$url"
)
if [ "$use_resume" -eq 1 ]; then
wget_args=(--continue "${wget_args[@]}")
fi
if [ "$show_progress" -eq 1 ]; then
wget_args=(--show-progress "${wget_args[@]}")
else
wget_args=(--quiet "${wget_args[@]}")
fi
if env ${proxy_env[@]+"${proxy_env[@]}"} wget "${wget_args[@]}"; then
mv -f "$partial" "$dest"
return 0
fi
else
die "Neither curl nor wget found"
fi
[ $attempt -lt $MAX_RETRIES ] && {
log_warn "Download failed, retrying in 3s..."
sleep 3
}
done
return 1
}
# ============================================================================
# Atomic binary install
# ============================================================================
install_binary_atomic() {
local src="$1"
local dest="$2"
local tmp_dest="${dest}.tmp.$$"
install -m 0755 "$src" "$tmp_dest"
if ! mv -f "$tmp_dest" "$dest"; then
rm -f "$tmp_dest" 2>/dev/null || true
die "Failed to move binary into place"
fi
}
# ============================================================================
# Build from source
# ============================================================================
build_from_source() {
log_step "Building from source..."
if ! ensure_rust; then
die "Rust is required for source builds"
fi
prepare_for_build
local build_dir="$TMP/src"
run_with_spinner "Cloning repository..." \
git clone --depth 1 "https://github.com/${OWNER}/${REPO}.git" "$build_dir"
if [ ! -d "$build_dir" ]; then
die "Failed to clone repository"
fi
log_step "Building with Cargo (this may take a few minutes)..."
# Build with explicit target dir to avoid conflicts
local target_dir="$TMP/target"
if [[ "$GUM_AVAILABLE" == "true" && "$QUIET" -eq 0 ]]; then
if ! gum spin --spinner dot --title "Compiling br (release mode)..." -- \