-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·3368 lines (3019 loc) · 106 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·3368 lines (3019 loc) · 106 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
#
# dcg installer
#
# One-liner install (with cache buster):
# curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)" | bash
#
# Or without cache buster:
# curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh | 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
# --from-source Build from source instead of downloading binary
# --quiet Suppress non-error output
# --no-gum Disable gum formatting even if available
# --no-configure Skip AI agent hook configuration
# --no-verify Skip checksum + signature verification (for testing only)
# --offline Skip network preflight checks
#
set -euo pipefail
umask 022
shopt -s lastpipe 2>/dev/null || true
VERSION="${VERSION:-}"
OWNER="${OWNER:-Dicklesworthstone}"
REPO="${REPO:-destructive_command_guard}"
DEST_DEFAULT="$HOME/.local/bin"
DEST="${DEST:-$DEST_DEFAULT}"
EASY=0
QUIET=0
VERIFY=0
FROM_SOURCE=0
CHECKSUM="${CHECKSUM:-}"
CHECKSUM_URL="${CHECKSUM_URL:-}"
SIGSTORE_BUNDLE_URL="${SIGSTORE_BUNDLE_URL:-}"
COSIGN_IDENTITY_RE="${COSIGN_IDENTITY_RE:-^https://github.com/${OWNER}/${REPO}/.github/workflows/dist.yml@refs/tags/.*$}"
COSIGN_OIDC_ISSUER="${COSIGN_OIDC_ISSUER:-https://token.actions.githubusercontent.com}"
ARTIFACT_URL="${ARTIFACT_URL:-}"
LOCK_FILE="/tmp/dcg-install.lock"
SYSTEM=0
NO_GUM=0
NO_CONFIGURE=0
NO_CHECKSUM=0
FORCE_INSTALL=0
OFFLINE="${DCG_OFFLINE:-0}"
AGENT_VERSION_LOOKUP="${DCG_INSTALLER_AGENT_VERSIONS:-0}"
AGENT_VERSION_TIMEOUT="${DCG_INSTALLER_AGENT_VERSION_TIMEOUT:-1}"
# Detect gum for fancy output (https://github.com/charmbracelet/gum)
HAS_GUM=0
if command -v gum &> /dev/null && [ -t 1 ]; then
HAS_GUM=1
fi
# Logging functions with optional gum formatting
log() { [ "$QUIET" -eq 1 ] && return 0; echo -e "$@"; }
info() {
[ "$QUIET" -eq 1 ] && return 0
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
gum style --foreground 39 "→ $*"
else
echo -e "\033[0;34m→\033[0m $*"
fi
}
ok() {
[ "$QUIET" -eq 1 ] && return 0
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
gum style --foreground 42 "✓ $*"
else
echo -e "\033[0;32m✓\033[0m $*"
fi
}
warn() {
[ "$QUIET" -eq 1 ] && return 0
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
gum style --foreground 214 "⚠ $*"
else
echo -e "\033[1;33m⚠\033[0m $*"
fi
}
err() {
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
gum style --foreground 196 "✗ $*"
else
echo -e "\033[0;31m✗\033[0m $*"
fi
}
# Spinner wrapper for long operations
run_with_spinner() {
local title="$1"
shift
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ] && [ "$QUIET" -eq 0 ]; then
gum spin --spinner dot --title "$title" -- "$@"
else
info "$title"
"$@"
fi
}
# Draw a box around text with automatic width calculation
# Usage: draw_box "color_code" "line1" "line2" ...
# color_code: ANSI color (e.g., "1;33" for yellow bold, "0;32" for green)
draw_box() {
local color="$1"
shift
local lines=("$@")
local max_width=0
local esc
esc=$(printf '\033')
local strip_ansi_sed="s/${esc}\\[[0-9;]*m//g"
# Calculate max width (strip ANSI codes for accurate measurement)
for line in "${lines[@]}"; do
local stripped
stripped=$(printf '%b' "$line" | LC_ALL=C sed "$strip_ansi_sed")
local len=${#stripped}
if [ "$len" -gt "$max_width" ]; then
max_width=$len
fi
done
# Add padding
local inner_width=$((max_width + 4))
local border=""
for ((i=0; i<inner_width; i++)); do
border+="═"
done
# Draw top border
printf "\033[%sm╔%s╗\033[0m\n" "$color" "$border"
# Draw each line with padding
for line in "${lines[@]}"; do
local stripped
stripped=$(printf '%b' "$line" | LC_ALL=C sed "$strip_ansi_sed")
local len=${#stripped}
local padding=$((max_width - len))
local pad_str=""
for ((i=0; i<padding; i++)); do
pad_str+=" "
done
printf "\033[%sm║\033[0m %b%s \033[%sm║\033[0m\n" "$color" "$line" "$pad_str" "$color"
done
# Draw bottom border
printf "\033[%sm╚%s╝\033[0m\n" "$color" "$border"
}
# ═══════════════════════════════════════════════════════════════════════════════
# AI Agent Detection
# ═══════════════════════════════════════════════════════════════════════════════
# Arrays to track detected agents
DETECTED_AGENTS=()
CLAUDE_VERSION=""
CODEX_VERSION=""
GEMINI_VERSION=""
AIDER_VERSION=""
CONTINUE_VERSION=""
CURSOR_VERSION=""
COPILOT_VERSION=""
HERMES_VERSION=""
print_agent_scan_notice() {
[ "$QUIET" -eq 1 ] && return 0
local line1="Scanning for installed coding agents..."
local line2="This can take several minutes depending on your machine."
local line3="The installer is still running - thanks for your patience."
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
echo ""
gum style \
--border normal \
--border-foreground 244 \
--padding "0 1" \
"$(gum style --foreground 212 --bold 'Agent scan')" \
"$(gum style --foreground 247 "$line1")" \
"$(gum style --foreground 245 "$line2")" \
"$(gum style --foreground 245 "$line3")"
echo ""
else
echo ""
draw_box "0;36" "$line1" "$line2" "$line3"
echo ""
fi
}
try_version() {
local cmd="$1"
[[ "$AGENT_VERSION_LOOKUP" == "1" ]] || return 0
command -v "$cmd" >/dev/null 2>&1 || return 0
local timeout_secs="${AGENT_VERSION_TIMEOUT:-1}"
if ! [[ "$timeout_secs" =~ ^[0-9]+$ ]]; then
timeout_secs=1
fi
if command -v timeout >/dev/null 2>&1; then
timeout "$timeout_secs" "$cmd" --version 2>/dev/null | head -1 || true
elif command -v gtimeout >/dev/null 2>&1; then
gtimeout "$timeout_secs" "$cmd" --version 2>/dev/null | head -1 || true
else
"$cmd" --version 2>/dev/null | head -1 || true
fi
}
detect_agents() {
DETECTED_AGENTS=()
# Claude Code
if [[ -d "$HOME/.claude" ]] || command -v claude &>/dev/null; then
DETECTED_AGENTS+=("claude-code")
CLAUDE_VERSION=$(try_version claude)
fi
# Codex CLI
if [[ -d "$HOME/.codex" ]] || command -v codex &>/dev/null; then
DETECTED_AGENTS+=("codex-cli")
CODEX_VERSION=$(try_version codex)
fi
# Gemini CLI (check both ~/.gemini and ~/.gemini-cli for compatibility)
if [[ -d "$HOME/.gemini" ]] || [[ -d "$HOME/.gemini-cli" ]] || command -v gemini &>/dev/null; then
DETECTED_AGENTS+=("gemini-cli")
GEMINI_VERSION=$(try_version gemini)
fi
# Aider
if command -v aider &>/dev/null; then
DETECTED_AGENTS+=("aider")
AIDER_VERSION=$(try_version aider)
fi
# GitHub Copilot CLI
if command -v copilot &>/dev/null || [[ -d "$HOME/.copilot" ]]; then
DETECTED_AGENTS+=("github-copilot-cli")
COPILOT_VERSION=$(try_version copilot)
fi
# Continue
if [[ -d "$HOME/.continue" ]]; then
DETECTED_AGENTS+=("continue")
# Continue doesn't have a standard CLI version command
if [[ -f "$HOME/.continue/config.json" ]]; then
CONTINUE_VERSION="config present"
fi
fi
# Cursor IDE
local cursor_detected=0
local cursor_settings_mac="$HOME/Library/Application Support/Cursor/User/settings.json"
local cursor_settings_linux="$HOME/.config/Cursor/User/settings.json"
if [[ -d "$HOME/.cursor" ]] || [[ -f "$cursor_settings_mac" ]] || [[ -f "$cursor_settings_linux" ]] || command -v cursor &>/dev/null; then
cursor_detected=1
elif command -v pgrep >/dev/null 2>&1; then
if pgrep -fl "[Cc]ursor" 2>/dev/null | grep -qv 'CursorUIViewService\|/System/Library/'; then
cursor_detected=1
fi
fi
if [ "$cursor_detected" -eq 1 ]; then
DETECTED_AGENTS+=("cursor-ide")
CURSOR_VERSION=$(try_version cursor)
fi
# Hermes Agent (NousResearch) — config dir at ~/.hermes, optional `hermes`
# CLI on PATH.
if [[ -d "$HOME/.hermes" ]] || command -v hermes &>/dev/null; then
DETECTED_AGENTS+=("hermes")
HERMES_VERSION=$(try_version hermes)
fi
}
print_detected_agents() {
if [[ ${#DETECTED_AGENTS[@]} -eq 0 ]]; then
info "No AI coding agents detected"
return
fi
local count=${#DETECTED_AGENTS[@]}
local plural=""
[[ $count -gt 1 ]] && plural="s"
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
echo ""
gum style --foreground 39 --bold "Detected AI Coding Agent${plural}:"
for agent in "${DETECTED_AGENTS[@]}"; do
case "$agent" in
claude-code)
local ver_info=""
[[ -n "$CLAUDE_VERSION" ]] && ver_info=" (${CLAUDE_VERSION})"
gum style --foreground 42 " ✓ Claude Code${ver_info}"
;;
codex-cli)
local ver_info=""
[[ -n "$CODEX_VERSION" ]] && ver_info=" (${CODEX_VERSION})"
gum style --foreground 42 " ✓ Codex CLI${ver_info}"
;;
gemini-cli)
local ver_info=""
[[ -n "$GEMINI_VERSION" ]] && ver_info=" (${GEMINI_VERSION})"
gum style --foreground 42 " ✓ Gemini CLI${ver_info}"
;;
aider)
local ver_info=""
[[ -n "$AIDER_VERSION" ]] && ver_info=" (${AIDER_VERSION})"
gum style --foreground 42 " ✓ Aider${ver_info}"
;;
github-copilot-cli)
local ver_info=""
[[ -n "$COPILOT_VERSION" ]] && ver_info=" (${COPILOT_VERSION})"
gum style --foreground 42 " ✓ GitHub Copilot CLI${ver_info}"
;;
continue)
local ver_info=""
[[ -n "$CONTINUE_VERSION" ]] && ver_info=" (${CONTINUE_VERSION})"
gum style --foreground 42 " ✓ Continue${ver_info}"
;;
cursor-ide)
local ver_info=""
[[ -n "$CURSOR_VERSION" ]] && ver_info=" (${CURSOR_VERSION})"
gum style --foreground 42 " ✓ Cursor IDE${ver_info}"
;;
hermes)
local ver_info=""
[[ -n "$HERMES_VERSION" ]] && ver_info=" (${HERMES_VERSION})"
gum style --foreground 42 " ✓ Hermes Agent${ver_info}"
;;
esac
done
echo ""
else
echo ""
echo -e "\033[1;39mDetected AI Coding Agent${plural}:\033[0m"
for agent in "${DETECTED_AGENTS[@]}"; do
case "$agent" in
claude-code)
local ver_info=""
[[ -n "$CLAUDE_VERSION" ]] && ver_info=" (${CLAUDE_VERSION})"
echo -e " \033[0;32m✓\033[0m Claude Code${ver_info}"
;;
codex-cli)
local ver_info=""
[[ -n "$CODEX_VERSION" ]] && ver_info=" (${CODEX_VERSION})"
echo -e " \033[0;32m✓\033[0m Codex CLI${ver_info}"
;;
gemini-cli)
local ver_info=""
[[ -n "$GEMINI_VERSION" ]] && ver_info=" (${GEMINI_VERSION})"
echo -e " \033[0;32m✓\033[0m Gemini CLI${ver_info}"
;;
aider)
local ver_info=""
[[ -n "$AIDER_VERSION" ]] && ver_info=" (${AIDER_VERSION})"
echo -e " \033[0;32m✓\033[0m Aider${ver_info}"
;;
github-copilot-cli)
local ver_info=""
[[ -n "$COPILOT_VERSION" ]] && ver_info=" (${COPILOT_VERSION})"
echo -e " \033[0;32m✓\033[0m GitHub Copilot CLI${ver_info}"
;;
continue)
local ver_info=""
[[ -n "$CONTINUE_VERSION" ]] && ver_info=" (${CONTINUE_VERSION})"
echo -e " \033[0;32m✓\033[0m Continue${ver_info}"
;;
cursor-ide)
local ver_info=""
[[ -n "$CURSOR_VERSION" ]] && ver_info=" (${CURSOR_VERSION})"
echo -e " \033[0;32m✓\033[0m Cursor IDE${ver_info}"
;;
hermes)
local ver_info=""
[[ -n "$HERMES_VERSION" ]] && ver_info=" (${HERMES_VERSION})"
echo -e " \033[0;32m✓\033[0m Hermes Agent${ver_info}"
;;
esac
done
echo ""
fi
}
# Check if a specific agent was detected
is_agent_detected() {
local target="$1"
for agent in "${DETECTED_AGENTS[@]}"; do
[[ "$agent" == "$target" ]] && return 0
done
return 1
}
# Check if installed version matches target
# Returns 0 if versions match, 1 if they differ or dcg not installed
check_installed_version() {
local target_version="$1"
if [ ! -x "$DEST/dcg" ]; then
return 1
fi
local installed_version
# dcg >= 0.4.1 prints bare version to stdout; some older/test binaries
# print "dcg 1.2.3". Accept either shape for idempotent reinstalls.
installed_version=$("$DEST/dcg" --version 2>/dev/null | \
sed -n \
-e 's/.*dcg[[:space:]]\+v\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' \
-e 's/^[[:space:]]*v\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)[[:space:]]*$/\1/p' | head -1)
if [ -z "$installed_version" ]; then
# Older versions output only to stderr — parse the decorative box
installed_version=$(NO_COLOR=1 "$DEST/dcg" --version 2>&1 | \
sed -n 's/.*dcg v\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1)
fi
if [ -z "$installed_version" ]; then
return 1
fi
# Normalize versions (strip 'v' prefix)
local target_clean="${target_version#v}"
local installed_clean="${installed_version#v}"
if [ "$target_clean" = "$installed_clean" ]; then
return 0
fi
return 1
}
resolve_version() {
if [ -n "$VERSION" ]; then return 0; fi
if [ "$FROM_SOURCE" -eq 1 ] || [ -n "$ARTIFACT_URL" ]; then return 0; fi
info "Resolving latest version..."
local latest_url="https://api.github.com/repos/${OWNER}/${REPO}/releases/latest"
local tag
if ! tag=$(curl -fsSL -H "Accept: application/vnd.github.v3+json" "$latest_url" 2>/dev/null | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/'); then
tag=""
fi
if [ -n "$tag" ]; then
VERSION="$tag"
info "Resolved latest version: $VERSION"
else
# Try redirect-based resolution as fallback
local redirect_url="https://github.com/${OWNER}/${REPO}/releases/latest"
if tag=$(curl -fsSL -o /dev/null -w '%{url_effective}' "$redirect_url" 2>/dev/null | sed -E 's|.*/tag/||'); then
# Validate: tag must be non-empty, start with 'v' + digit, and not contain URL chars
if [ -n "$tag" ] && [[ "$tag" =~ ^v[0-9] ]] && [[ "$tag" != *"/"* ]]; then
VERSION="$tag"
info "Resolved latest version via redirect: $VERSION"
return 0
fi
fi
err "Could not resolve latest release. Re-run with --version vX.Y.Z or --from-source."
exit 1
fi
}
detect_platform() {
OS=$(uname -s | tr 'A-Z' 'a-z')
ARCH=$(uname -m)
case "$ARCH" in
x86_64|amd64) ARCH="x86_64" ;;
arm64|aarch64) ARCH="aarch64" ;;
*) warn "Unknown arch $ARCH, using as-is" ;;
esac
TARGET=""
case "${OS}-${ARCH}" in
# Linux x86_64 ships as a fully-static musl binary so the published
# artifact runs on every glibc generation, including the LTS releases
# (Ubuntu 22.04 ships glibc 2.35; RHEL 8/9, Amazon Linux 2, etc.).
# The previous gnu mapping linked against the build runner's glibc
# and rejected any older host with `GLIBC_2.39 not found`. See #114.
linux-x86_64) TARGET="x86_64-unknown-linux-musl" ;;
linux-aarch64) TARGET="aarch64-unknown-linux-gnu" ;;
darwin-x86_64) TARGET="x86_64-apple-darwin" ;;
darwin-aarch64) TARGET="aarch64-apple-darwin" ;;
*) :;;
esac
if [ -z "$TARGET" ] && [ "$FROM_SOURCE" -eq 0 ] && [ -z "$ARTIFACT_URL" ]; then
warn "No prebuilt artifact for ${OS}/${ARCH}; falling back to build-from-source"
FROM_SOURCE=1
fi
}
set_artifact_url() {
TAR=""
URL=""
if [ "$FROM_SOURCE" -eq 0 ]; then
if [ -n "$ARTIFACT_URL" ]; then
TAR=$(basename "$ARTIFACT_URL")
URL="$ARTIFACT_URL"
elif [ -n "$TARGET" ]; then
TAR="dcg-${TARGET}.tar.xz"
URL="https://github.com/${OWNER}/${REPO}/releases/download/${VERSION}/${TAR}"
# Backward-compat fallback for the Linux x86_64 musl transition
# (#114). Releases v0.5.2+ ship musl artifacts; v0.5.1 and earlier
# ship gnu. If the operator pinned an older version that doesn't
# have a musl asset, fall back to the gnu naming so they still
# get a working binary. We probe with a HEAD request so this
# adds at most one round-trip on the older-release path.
if [ "$TARGET" = "x86_64-unknown-linux-musl" ] && command -v curl >/dev/null 2>&1; then
local http_code
http_code=$(curl -sSL -o /dev/null -w '%{http_code}' -I --max-time 10 "$URL" || echo "000")
if [ "$http_code" != "200" ] && [ "$http_code" != "302" ]; then
local legacy_target="x86_64-unknown-linux-gnu"
local legacy_url="https://github.com/${OWNER}/${REPO}/releases/download/${VERSION}/dcg-${legacy_target}.tar.xz"
local legacy_code
legacy_code=$(curl -sSL -o /dev/null -w '%{http_code}' -I --max-time 10 "$legacy_url" || echo "000")
if [ "$legacy_code" = "200" ] || [ "$legacy_code" = "302" ]; then
warn "No musl artifact for ${VERSION}; falling back to gnu (host glibc must be >= the build runner's, see #114)"
TARGET="$legacy_target"
TAR="dcg-${TARGET}.tar.xz"
URL="$legacy_url"
fi
fi
fi
else
warn "No prebuilt artifact for ${OS}/${ARCH}; falling back to build-from-source"
FROM_SOURCE=1
fi
fi
}
check_disk_space() {
local min_kb=10240
local path="$DEST"
if [ ! -d "$path" ]; then
path=$(dirname "$path")
fi
if command -v df >/dev/null 2>&1; then
local avail_kb
avail_kb=$(df -Pk "$path" | awk 'NR==2 {print $4}')
if [ -n "$avail_kb" ] && [ "$avail_kb" -lt "$min_kb" ]; then
err "Insufficient disk space in $path (need at least 10MB)"
exit 1
fi
else
warn "df not found; skipping disk space check"
fi
}
check_write_permissions() {
if [ ! -d "$DEST" ]; then
if ! mkdir -p "$DEST" 2>/dev/null; then
err "Cannot create $DEST (insufficient permissions)"
err "Try running with sudo or choose a writable --dest"
exit 1
fi
fi
if [ ! -w "$DEST" ]; then
err "No write permission to $DEST"
err "Try running with sudo or choose a writable --dest"
exit 1
fi
}
check_existing_install() {
if [ -x "$DEST/dcg" ]; then
local current
current=$("$DEST/dcg" --version 2>/dev/null | head -1 || echo "")
if [ -n "$current" ]; then
info "Existing dcg detected: $current"
fi
fi
}
check_network() {
if [ "$OFFLINE" -eq 1 ]; then
info "Offline mode enabled; skipping network preflight"
return 0
fi
if [ "$FROM_SOURCE" -eq 1 ]; then
return 0
fi
if [ -z "$URL" ]; then
return 0
fi
if ! command -v curl >/dev/null 2>&1; then
warn "curl not found; skipping network check"
return 0
fi
if ! curl -fsSL --connect-timeout 3 --max-time 5 -o /dev/null "$URL"; then
warn "Network check failed for $URL"
warn "Continuing; download may fail"
fi
}
preflight_checks() {
info "Running preflight checks"
check_disk_space
check_write_permissions
check_existing_install
check_network
}
maybe_add_path() {
case ":$PATH:" in
*:"$DEST":*) return 0;;
*)
if [ "$EASY" -eq 1 ]; then
UPDATED=0
for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
if [ -e "$rc" ] && [ -w "$rc" ]; then
if ! grep -F "$DEST" "$rc" >/dev/null 2>&1; then
echo "export PATH=\"$DEST:\$PATH\"" >> "$rc"
fi
UPDATED=1
fi
done
if [ "$UPDATED" -eq 1 ]; then
warn "PATH updated in ~/.zshrc/.bashrc; restart shell to use dcg"
else
warn "Add $DEST to PATH to use dcg"
fi
else
warn "Add $DEST to PATH to use dcg"
fi
;;
esac
}
DCG_SHELL_CHECK_MARKER="# dcg: warn if hook was silently removed"
maybe_add_shell_check() {
# Add a shell startup check that warns if the DCG hook has been silently
# removed from ~/.claude/settings.json. Silent when present, fast (ms),
# and only runs when both dcg and jq are on PATH.
local snippet
snippet=$(cat <<'EOFSNIPPET'
# dcg: warn if hook was silently removed from Claude Code settings
if command -v dcg &>/dev/null && command -v jq &>/dev/null; then
if [ -f "$HOME/.claude/settings.json" ] && \
! jq -e '.hooks.PreToolUse[]? | select(.hooks[]?.command | test("dcg$"))' \
"$HOME/.claude/settings.json" &>/dev/null; then
printf '\033[1;33m[dcg] Hook missing from ~/.claude/settings.json — run: dcg install\033[0m\n'
fi
fi
EOFSNIPPET
)
local added=0
for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
if [ -e "$rc" ] && [ -w "$rc" ]; then
if grep -qF "$DCG_SHELL_CHECK_MARKER" "$rc" 2>/dev/null; then
added=1 # Already present — don't trigger fallback
continue
fi
printf '%s\n' "$snippet" >> "$rc"
added=1
ok "Added shell startup check to $rc"
fi
done
if [ "$added" -eq 0 ]; then
# No RC files found or none writable — try to pick one based on shell
local target_rc="$HOME/.bashrc"
case "${SHELL:-}" in
*zsh) target_rc="$HOME/.zshrc" ;;
esac
printf '%s\n' "$snippet" >> "$target_rc"
ok "Added shell startup check to $target_rc"
fi
}
# caller_user — the human who actually invoked the installer.
#
# Under `sudo`, the EUID is root and $SHELL/$HOME/$USER have been env_reset'd
# to root's values, which is the wrong identity for "whose shell completions
# are we installing." If $SUDO_USER is set and isn't itself root, that is the
# real caller. Otherwise fall back to $USER or the OS-reported login name.
caller_user() {
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != "root" ]; then
printf '%s\n' "$SUDO_USER"
return 0
fi
if [ -n "${USER:-}" ]; then
printf '%s\n' "$USER"
return 0
fi
id -un 2>/dev/null
}
# caller_home / caller_login_shell — resolve the caller's home directory and
# login shell from the OS user database, so they're stable under sudo where
# $HOME and $SHELL have been rewritten. Uses dscl on macOS (where /etc/passwd
# is not authoritative for user records) and getent on every other Unix.
caller_home() {
local user
user=$(caller_user) || return 1
[ -z "$user" ] && return 1
case "$(uname -s)" in
Darwin)
dscl . -read "/Users/$user" NFSHomeDirectory 2>/dev/null \
| awk '/^NFSHomeDirectory:/ {print $2}'
;;
*)
getent passwd "$user" 2>/dev/null | cut -d: -f6
;;
esac
}
caller_login_shell() {
local user
user=$(caller_user) || return 1
[ -z "$user" ] && return 1
case "$(uname -s)" in
Darwin)
dscl . -read "/Users/$user" UserShell 2>/dev/null \
| awk '/^UserShell:/ {print $2}'
;;
*)
getent passwd "$user" 2>/dev/null | cut -d: -f7
;;
esac
}
# detect_default_shell — pick which completion flavor to install.
#
# $SHELL is the obvious source, but `sudo` defaults to env_reset (since
# sudo 1.7.4), which rewrites $SHELL to the *target user's* login shell
# (root's). On Linux that's typically /bin/bash and produces a silent
# misplace into /root/.local/share/bash-completion. On macOS root's shell
# is /bin/sh and we'd print "skipped (unknown shell)" instead.
#
# When EUID==0 and $SUDO_USER is the actual caller, look up that user's
# login shell from the OS user database before falling back to $SHELL.
detect_default_shell() {
local shell=""
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != "root" ]; then
shell=$(caller_login_shell || true)
fi
[ -z "$shell" ] && shell="${SHELL:-}"
[ -z "$shell" ] && return 1
shell=$(basename "$shell")
case "$shell" in
bash|zsh|fish) echo "$shell"; return 0 ;;
*) return 1 ;;
esac
}
install_completions_for_shell() {
local shell="$1"
local bin="$DEST/dcg"
if [ ! -x "$bin" ]; then
warn "dcg binary not found at $bin; skipping completions"
return 1
fi
# Check if the completions subcommand exists (added in v0.2.11+)
if ! "$bin" completions --help >/dev/null 2>&1; then
info "Shell completions: skipped (not supported in this version)"
return 0
fi
# Resolve the *caller's* XDG paths, not root's. Under sudo $HOME points at
# /root and $XDG_DATA_HOME/$XDG_CONFIG_HOME (if exported by the user's shell)
# were stripped by env_reset, so we'd silently install into /root's home —
# invisible to the user who actually ran the installer.
local home xdg_data xdg_config running_sudo=0
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != "root" ]; then
running_sudo=1
home=$(caller_home || true)
if [ -z "$home" ]; then
warn "Could not resolve home directory for caller $SUDO_USER; falling back to \$HOME"
home="$HOME"
fi
# Force defaults from caller's home; ignore root-shell-leaked XDG_*.
xdg_data="$home/.local/share"
xdg_config="$home/.config"
else
home="$HOME"
xdg_data="${XDG_DATA_HOME:-$home/.local/share}"
xdg_config="${XDG_CONFIG_HOME:-$home/.config}"
fi
local target=""
case "$shell" in
bash)
target="$xdg_data/bash-completion/completions/dcg"
;;
zsh)
target="$xdg_data/zsh/site-functions/_dcg"
;;
fish)
target="$xdg_config/fish/completions/dcg.fish"
;;
*)
return 1
;;
esac
# Ensure target directory exists
if ! mkdir -p "$(dirname "$target")" 2>/dev/null; then
warn "Failed to create completions directory for $shell"
return 1
fi
# Generate and install completions
local error_output
if error_output=$("$bin" completions "$shell" 2>&1) && [ -n "$error_output" ]; then
printf '%s\n' "$error_output" > "$target"
# When the installer is running as root under sudo, the directory tree we
# just (potentially) created and the completion file itself are owned by
# root. The caller's shell loads completions as the caller, not as root —
# ownership matters for any tooling that later re-writes these paths
# (next dcg upgrade, package manager hooks). Hand the path back to them.
if [ "$running_sudo" -eq 1 ]; then
local caller_group
caller_group=$(id -gn "$SUDO_USER" 2>/dev/null || printf '%s' "$SUDO_USER")
chown "$SUDO_USER:$caller_group" "$target" 2>/dev/null || true
# Walk up from the target's directory to (but not past) the caller's
# $HOME, chowning anything we just created. Don't recurse into
# pre-existing trees — that could clobber legitimate ownership of
# files we didn't write.
local dir
dir=$(dirname "$target")
while [ "$dir" != "$home" ] && [ "$dir" != "/" ] && [ -n "$dir" ]; do
chown "$SUDO_USER:$caller_group" "$dir" 2>/dev/null || true
dir=$(dirname "$dir")
done
fi
ok "Installed $shell completions to $target"
return 0
fi
warn "Failed to install $shell completions"
return 1
}
maybe_install_completions() {
local shell=""
if ! shell=$(detect_default_shell); then
# Distinguish the "running as root with no caller to attribute" case
# (e.g. logged in directly as root, no sudo) from "user has an exotic
# shell we don't generate completions for" — the remediation differs.
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -z "${SUDO_USER:-}" ]; then
info "Shell completions: skipped (no caller user detected; install as a regular user or via sudo)"
else
info "Shell completions: skipped (unsupported login shell; bash/zsh/fish only)"
fi
return 0
fi
install_completions_for_shell "$shell" || true
}
ensure_rust() {
if [ "${RUSTUP_INIT_SKIP:-0}" != "0" ]; then
info "Skipping rustup install (RUSTUP_INIT_SKIP set)"
return 0
fi
if command -v cargo >/dev/null 2>&1 && rustc --version 2>/dev/null | grep -q nightly; then return 0; fi
if [ "$EASY" -ne 1 ]; then
if [ -t 0 ]; then
echo -n "Install Rust nightly via rustup? (y/N): "
read -r ans
case "$ans" in y|Y) :;; *) warn "Skipping rustup install"; return 0;; esac
fi
fi
info "Installing rustup (nightly)"
curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain nightly --profile minimal
export PATH="$HOME/.cargo/bin:$PATH"
rustup component add rustfmt clippy || true
}
# Verify SHA256 checksum of a file
# Usage: verify_checksum <file> <expected_checksum>
# Returns 0 on success, 1 on failure
verify_checksum() {
local file="$1"
local expected="$2"
local actual=""
if [ ! -f "$file" ]; then
err "File not found: $file"
return 1
fi
# Try sha256sum first (Linux), then shasum (macOS)
if command -v sha256sum &>/dev/null; then
actual=$(sha256sum "$file" | cut -d' ' -f1)
elif command -v shasum &>/dev/null; then
# macOS fallback
actual=$(shasum -a 256 "$file" | cut -d' ' -f1)
else
warn "No SHA256 tool found (sha256sum or shasum), skipping verification"
return 0
fi
if [ "$actual" != "$expected" ]; then
err "Checksum verification FAILED!"
err "Expected: $expected"
err "Got: $actual"
err "The downloaded file may be corrupted or tampered with."
# Clean up the corrupted file
rm -f "$file"
return 1
fi
ok "Checksum verified: ${actual:0:16}..."
return 0
}
# Verify Sigstore/cosign bundle for a file (best-effort).
# Usage: verify_sigstore_bundle <file> <artifact_url>
# Returns 0 on success or when verification is skipped, 1 on verification failure.
verify_sigstore_bundle() {
local file="$1"
local artifact_url="$2"
if ! command -v cosign &>/dev/null; then
warn "cosign not found; skipping signature verification (install cosign for stronger authenticity checks)"
return 0
fi
local bundle_url="$SIGSTORE_BUNDLE_URL"
if [ -z "$bundle_url" ]; then
bundle_url="${artifact_url}.sigstore.json"
fi
local bundle_file="$TMP/$(basename "$bundle_url")"
info "Fetching sigstore bundle from ${bundle_url}"
if ! curl -fsSL "$bundle_url" -o "$bundle_file"; then
warn "Sigstore bundle not found; skipping signature verification"
return 0
fi
# The release is signed by cosign v3.x (sigstore/cosign-installer in
# dist.yml), which emits the modern Sigstore protobuf bundle
# (mediaType "application/vnd.dev.sigstore.bundle.v0.3+json", with the
# signing cert under verificationMaterial.certificate). cosign only knows
# how to parse that bundle shape from --bundle when --new-bundle-format is
# passed; that flag was introduced in cosign v2.4.0 (PR sigstore/cosign#3796).
#
# Two failure modes have to be kept distinct (issue #140):
# 1. A cosign that DOES understand the modern bundle but the signature
# genuinely does not verify -> a real tamper/corruption signal -> abort.
# 2. A cosign too old to know --new-bundle-format (< 2.4.0). Passing the
# flag makes it die with "unknown flag: --new-bundle-format" (exit 1),
# and even without the flag it cannot parse a v0.3 protobuf bundle at all
# (it would fall back to the legacy shape and fail with "bundle does not
# contain cert for verification, please provide public key"). Such a
# client simply cannot verify this bundle no matter what we pass.
#
# The earlier form of this function unconditionally passed --new-bundle-format
# and treated ANY non-zero cosign exit as fatal, so an honest user whose only
# sin was an old cosign on PATH had their install / `dcg update` aborted on the
# "unknown flag" error. That is strictly worse than the pre-#140 behaviour.
#
# Signature verification is best-effort here (the SHA256 checksum is already
# verified and required just above the call site; the same "cosign not found"
# and "bundle not found" branches above warn-and-skip rather than abort). So:
# only pass --new-bundle-format when this cosign actually supports it, and if
# it does not, warn and skip rather than fail the whole install. A cosign that
# supports the flag is the only one that can meaningfully verify the bundle,
# and for that one a non-zero exit is a real failure we still abort on.
local nbf_flag="--new-bundle-format"
if ! cosign verify-blob --help 2>/dev/null | grep -q -- "$nbf_flag"; then
warn "cosign is too old to verify the modern Sigstore bundle (needs >= 2.4.0 for ${nbf_flag}); skipping signature verification (checksum already verified)"
return 0
fi
if ! cosign verify-blob \
"$nbf_flag" \
--bundle "$bundle_file" \
--certificate-identity-regexp "$COSIGN_IDENTITY_RE" \
--certificate-oidc-issuer "$COSIGN_OIDC_ISSUER" \
"$file"; then
return 1
fi
ok "Signature verified (cosign)"
return 0
}
usage() {
cat <<EOFU
Usage: install.sh [--version vX.Y.Z] [--dest DIR] [--system] [--easy-mode] [--verify] \\
[--artifact-url URL] [--checksum HEX] [--checksum-url URL] [--quiet] \\
[--offline] [--no-gum] [--no-configure] [--no-verify] [--force]
Options:
--version vX.Y.Z Install specific version (default: latest)
--dest DIR Install to DIR (default: ~/.local/bin)