-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathphpvm.sh
More file actions
executable file
·1889 lines (1676 loc) · 65.3 KB
/
phpvm.sh
File metadata and controls
executable file
·1889 lines (1676 loc) · 65.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
#!/bin/bash
# phpvm - PHP Version Manager v2.6.1
if (( BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 3) )); then
echo "phpvm requires bash 4.3+. Current: ${BASH_VERSION}" >&2
exit 1
fi
VERSION="2.6.1"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
REVERSE='\033[7m'
selected_index=0
tui_wrap=false
# helpers
get_php_versions() {
update-alternatives --list php 2>/dev/null | sort -V
}
get_current_php() {
readlink /etc/alternatives/php 2>/dev/null
}
require_update_alternatives() {
if ! command -v update-alternatives &>/dev/null; then
echo -e "${RED}Error: update-alternatives not found.${NC}" >&2
exit 1
fi
}
find_version_by_query() {
local query="$1"
local versions
mapfile -t versions < <(get_php_versions)
for v in "${versions[@]}"; do
local name
name=$(basename "$v")
if [[ "$name" == "$query" ]] || [[ "$name" == "php${query}" ]] || [[ "$v" == "$query" ]]; then
echo "$v"
return 0
fi
done
return 1
}
# normalize raw version string (e.g. "php8.2", "8.2.0", " 8.2\n") → "8.2"
normalize_version() {
local raw="$1"
raw="${raw//[[:space:]]/}"
raw="${raw#php}"
if [[ "$raw" =~ ^([0-9]+\.[0-9]+) ]]; then
echo "${BASH_REMATCH[1]}"
return 0
fi
return 1
}
# true when a controlling terminal is reachable, even under `curl | sudo bash`
# (the pipe replaces stdin, so a bare `-t 0` test is not enough, same trick
# install.sh uses).
_tty_interactive() {
[[ -t 0 ]] || { true < /dev/tty; } 2>/dev/null
}
# Map /etc/os-release to the upstream PHP repo we drive. Echoes "<kind> <codename>"
# where kind is ubuntu | debian | unsupported. PHPVM_OS_RELEASE overrides the path
# (test seam). Ubuntu is checked first so Ubuntu derivatives (Mint, Pop!_OS, etc.),
# which carry `ubuntu` in ID_LIKE, take the PPA path.
detect_distro_repo() {
local osr="${PHPVM_OS_RELEASE:-/etc/os-release}"
if [[ ! -r "$osr" ]]; then
echo "unsupported "
return 0
fi
(
ID=""; ID_LIKE=""; VERSION_CODENAME=""
# shellcheck disable=SC1090
. "$osr" 2>/dev/null
local kind="unsupported"
if [[ "$ID" == "ubuntu" || " ${ID_LIKE} " == *" ubuntu "* ]]; then
kind="ubuntu"
elif [[ "$ID" == "debian" || " ${ID_LIKE} " == *" debian "* ]]; then
kind="debian"
fi
echo "${kind} ${VERSION_CODENAME}"
)
}
# true when apt knows about the package (repo already provides it)
apt_pkg_available() {
apt-cache show "$1" 2>/dev/null | grep -q .
}
# apt-get under sudo with a non-interactive debconf frontend, so an unattended
# `--yes` install can't wedge on a postinst prompt (e.g. tzdata). sudo resets the
# environment, so we set DEBIAN_FRONTEND via `env` rather than an inline
# assignment, which sudo would strip. apt stays password-gated as before.
_sudo_apt() {
sudo env DEBIAN_FRONTEND=noninteractive apt-get "$@"
}
# project detection
find_php_version_file() {
local dir="${1:-$PWD}"
while :; do
if [[ -f "$dir/.php-version" ]]; then
echo "$dir/.php-version"
return 0
fi
[[ "$dir" == "/" ]] && break
dir=$(dirname "$dir")
done
return 1
}
find_composer_json() {
local dir="${1:-$PWD}"
while :; do
if [[ -f "$dir/composer.json" ]]; then
echo "$dir/composer.json"
return 0
fi
[[ "$dir" == "/" ]] && break
dir=$(dirname "$dir")
done
return 1
}
detect_from_composer() {
local dir="${1:-$PWD}"
local composer
composer=$(find_composer_json "$dir") || return 1
# pick highest installed PHP minor that the constraint allows.
# falls back to first version token if no installed match.
local installed
installed=$(get_php_versions | sed -E 's|.*/php([0-9]+\.[0-9]+)$|\1|' | sort -V | tr '\n' ' ')
if command -v python3 &>/dev/null; then
python3 - "$composer" "$installed" <<'PYEOF' 2>/dev/null
import json, sys, re
try:
with open(sys.argv[1]) as f:
data = json.load(f)
req = data.get('require', {}).get('php', '')
if not req:
sys.exit(0)
installed = [v for v in sys.argv[2].split() if v]
def parse(v):
return tuple(int(x) for x in v.split('.'))
def matches(ver, expr):
ver_t = parse(ver)
for clause in expr.split('|'):
clause = clause.strip().lstrip('v')
if not clause:
continue
ok = True
for part in re.split(r'\s*,\s*|\s+', clause):
if not part:
continue
m = re.match(r'^(\^|~|>=|<=|>|<|=)?\s*v?(\d+(?:\.\d+){0,2})', part)
if not m:
ok = False
break
op = m.group(1) or '='
bound = parse(m.group(2))
while len(bound) < 2:
bound = bound + (0,)
bv = bound[:2]
vt = ver_t[:2]
if op == '^':
if vt < bv or vt[0] != bv[0]:
ok = False
break
elif op == '~':
if len(bound) >= 2:
if vt < bv or vt[0] != bv[0]:
ok = False
break
elif op == '>=':
if vt < bv: ok = False; break
elif op == '<=':
if vt > bv: ok = False; break
elif op == '>':
if vt <= bv: ok = False; break
elif op == '<':
if vt >= bv: ok = False; break
else:
if vt != bv: ok = False; break
if ok:
return True
return False
matched = [v for v in installed if matches(v, req)]
if matched:
print(sorted(matched, key=parse)[-1])
else:
m = re.search(r'(\d+\.\d+)', req)
if m:
print(m.group(1))
except Exception:
pass
PYEOF
else
grep -o '"php"[[:space:]]*:[[:space:]]*"[^"]*"' "$composer" \
| grep -oE '[0-9]+\.[0-9]+' | head -1
fi
}
detect_project_php() {
local dir="${1:-$PWD}"
local vfile
vfile=$(find_php_version_file "$dir")
if [[ -n "$vfile" ]]; then
local raw
raw=$(< "$vfile")
local norm
if norm=$(normalize_version "$raw"); then
echo "$norm"
return 0
fi
return 1
fi
local cver
cver=$(detect_from_composer "$dir")
if [[ -n "$cver" ]]; then
normalize_version "$cver" || echo "$cver"
return 0
fi
return 1
}
# switching
do_switch() {
local target="$1"
local quiet="${2:-false}"
local err
err=$(sudo -p "[phpvm] switching PHP, password for %u: " update-alternatives --set php "$target" 2>&1 >/dev/null)
local code=$?
if [[ "$quiet" != "true" ]]; then
if [[ "$code" -eq 0 ]]; then
echo -e "${GREEN}✓${NC} Switched to ${BOLD}$(basename "$target")${NC} ${DIM}($(php --version 2>/dev/null | head -1))${NC}"
else
echo -e "${RED}✗${NC} Failed to switch." >&2
[[ -n "$err" ]] && echo -e "${DIM}${err}${NC}" >&2
return 1
fi
fi
return "$code"
}
# cli commands
cmd_list() {
require_update_alternatives
local show_paths=false as_json=false
for arg in "$@"; do
case "$arg" in
--paths) show_paths=true ;;
--json) as_json=true ;;
--help|-h)
echo "Usage: phpvm --list [--paths|--json]"
echo " (no flag) human-readable, shows active marker"
echo " --paths add the absolute binary path column (for IDE / script use)"
echo " --json emit [{version,path,active}, ...] for tooling"
return 0
;;
esac
done
local current
current=$(get_current_php)
mapfile -t versions < <(get_php_versions)
if [[ "${#versions[@]}" -eq 0 ]]; then
if [[ "$as_json" == "true" ]]; then
echo "[]"
return 0
fi
echo -e "${RED}No PHP alternatives registered.${NC}" >&2
exit 1
fi
if [[ "$as_json" == "true" ]]; then
# hand-rolled JSON keeps the output dependency-free. fields are tight
# so jq/grep can consume it; no trailing comma; one object per line for
# readable diffs and easy line-wise tooling.
local first=true
echo "["
for v in "${versions[@]}"; do
local name="${v##*/}"
local ver="${name#php}"
local active="false"
[[ "$v" == "$current" ]] && active="true"
if [[ "$first" == "true" ]]; then first=false; else echo ","; fi
printf ' {"version":"%s","path":"%s","active":%s}' "$ver" "$v" "$active"
done
echo ""
echo "]"
return 0
fi
for v in "${versions[@]}"; do
local name="${v##*/}"
local marker=" "; local style_open=""; local style_close=""
if [[ "$v" == "$current" ]]; then
marker=" ${GREEN}●${NC}"
style_open="${BOLD}"
style_close="${NC}"
else
style_open="${DIM}"
style_close="${NC}"
fi
if [[ "$show_paths" == "true" ]]; then
local suffix=""
[[ "$v" == "$current" ]] && suffix=" ${DIM}(active)${NC}"
echo -e " ${marker} ${style_open}${name}${style_close} ${DIM}${v}${NC}${suffix}"
else
if [[ "$v" == "$current" ]]; then
echo -e " ${marker} ${style_open}${name}${style_close} ${DIM}(active)${NC}"
else
echo -e " ${marker} ${style_open}${name}${style_close}"
fi
fi
done
# In --paths mode, point at the per-IDE recipes so the discovery path
# is one prompt away. Skipped for plain --list to keep that output tight.
if [[ "$show_paths" == "true" ]]; then
echo ""
echo -e " ${DIM}Use these in your IDE's PHP interpreter setting.${NC}"
echo -e " ${DIM}Per-IDE recipes: https://github.com/rijverse/phpvm#using-with-your-ide${NC}"
fi
}
# Print the absolute binary path for one installed version. Mirrors
# `nvm which`, `pyenv which`, `rbenv which` so scripts and IDE config tools
# can pipe the result directly into wherever a PHP interpreter path is
# needed (PhpStorm, VS Code, Sublime LSP, NetBeans, Zed, CI configs, etc).
# Output is the bare path on stdout, nothing else, so this composes.
cmd_which() {
require_update_alternatives
local query="$1"
if [[ -z "$query" ]]; then
echo -e "${RED}Usage: phpvm which <version>${NC}" >&2
echo -e "${DIM}Example: phpvm which 8.2${NC}" >&2
exit 1
fi
local norm
norm=$(normalize_version "$query") || norm="$query"
local target
target=$(find_version_by_query "$norm") || target=$(find_version_by_query "$query")
if [[ -z "$target" ]]; then
echo -e "${RED}PHP ${query} is not installed.${NC}" >&2
echo -e "${DIM}Run: phpvm --list${NC}" >&2
exit 1
fi
echo "$target"
}
cmd_current() {
# Headline is ground truth: whatever `php` resolves to right now (the shim
# when the hook is loaded, else /usr/bin/php). The breakdown below shows the
# three resolution layers that feed it. The env vars are inherited from the
# caller's shell, so this is accurate when run through the wrapper.
local phpbin actual
phpbin=$(command -v php 2>/dev/null)
actual=$(php --version 2>/dev/null | head -1)
local global_link global_name=""
global_link=$(get_current_php)
[[ -n "$global_link" ]] && global_name="${global_link##*/}"
if [[ -z "$actual" && -z "$global_name" ]]; then
echo -e "${YELLOW}No active PHP version found.${NC}" >&2
exit 1
fi
if [[ -n "$actual" ]]; then
echo -e "${GREEN}${BOLD}${actual}${NC}"
[[ -n "$phpbin" ]] && echo -e " ${DIM}via ${phpbin}${NC}"
fi
echo ""
local shell_pin="${PHPVM_SHELL_VERSION:-}"
local auto_pin="${PHPVM_AUTO_VERSION:-}"
local proj=""
[[ -z "$auto_pin" ]] && proj=$(detect_project_php 2>/dev/null || true)
if [[ -n "$shell_pin" ]]; then
echo -e " ${DIM}shell:${NC} ${CYAN}${shell_pin}${NC} ${DIM}(this terminal, phpvm shell)${NC}"
else
echo -e " ${DIM}shell:${NC} ${DIM}not pinned${NC}"
fi
if [[ -n "$auto_pin" ]]; then
echo -e " ${DIM}project:${NC} ${CYAN}${auto_pin}${NC} ${DIM}(auto, from cd-hook)${NC}"
elif [[ -n "$proj" ]]; then
echo -e " ${DIM}project:${NC} ${CYAN}${proj}${NC} ${DIM}(.php-version / composer.json)${NC}"
else
echo -e " ${DIM}project:${NC} ${DIM}none${NC}"
fi
if [[ -n "$global_name" ]]; then
echo -e " ${DIM}global:${NC} ${CYAN}${global_name#php}${NC} ${DIM}(system default, phpvm global)${NC}"
else
echo -e " ${DIM}global:${NC} ${DIM}none${NC}"
fi
# inactive-pin hint: a shell/project pin is set but `php` resolves to
# something other than the shim, so the pin has no effect in this terminal.
# Distinct from "no hook installed", here the hook exists but this shell
# never sourced it (common after a fresh install in an already-open shell).
if [[ -n "$shell_pin" || -n "$auto_pin" ]]; then
local _hook_dir
_hook_dir=$(detect_hook_dir 2>/dev/null || echo "")
case "$(shim_status)" in
absent)
echo ""
echo -e " ${YELLOW}!${NC} ${BOLD}Pin is set but inactive in this terminal${NC} ${DIM}(php resolves to ${phpbin:-none}, not the shim)${NC}"
echo -e " ${DIM}Activate: source ${_hook_dir}/php-auto.bash (zsh: php-auto.zsh, fish: php-auto.fish)${NC}"
echo -e " ${DIM}Or just open a new terminal.${NC}"
;;
shadowed)
echo ""
echo -e " ${YELLOW}!${NC} ${BOLD}Pin set but the shim is shadowed${NC} ${DIM}(php resolves to ${phpbin:-none})${NC}"
echo -e " ${DIM}Self-corrects on your next cd or 'phpvm shell ${shell_pin:-$auto_pin}'.${NC}"
;;
esac
fi
}
cmd_global() {
require_update_alternatives
local query="$1"
if [[ -z "$query" ]]; then
echo -e "${RED}Usage: phpvm global <version>${NC}" >&2
echo -e "${DIM}Example: phpvm global 8.2${NC}" >&2
exit 1
fi
local target
target=$(find_version_by_query "$query")
if [[ -z "$target" ]]; then
echo -e "${RED}Version not found: ${query}${NC}" >&2
echo -e "${DIM}Run: phpvm --list${NC}" >&2
exit 1
fi
do_switch "$target"
}
cmd_auto() {
local quiet="${1:-false}"
local print_only="${2:-false}"
local dir="${3:-$PWD}"
if [[ "$print_only" != "true" ]]; then
require_update_alternatives
fi
local ver
ver=$(detect_project_php "$dir")
if [[ -z "$ver" ]]; then
[[ "$quiet" != "true" && "$print_only" != "true" ]] && echo -e "${DIM}No .php-version or composer.json found.${NC}"
return 1
fi
if [[ "$print_only" == "true" ]]; then
echo "$ver"
return 0
fi
local current
current=$(get_current_php)
local current_name
current_name=$(basename "$current")
if [[ "$current_name" == "php${ver}" ]]; then
[[ "$quiet" != "true" ]] && echo -e "${DIM}Already on PHP ${ver}.${NC}"
return 0
fi
local target
target=$(find_version_by_query "$ver")
if [[ -z "$target" ]]; then
[[ "$quiet" != "true" ]] && echo -e "${YELLOW}PHP ${ver} required but not installed.${NC}" >&2
return 1
fi
do_switch "$target" "$quiet"
local rc=$?
if [[ "$quiet" == "true" ]]; then
if [[ "$rc" -eq 0 ]]; then
echo -e "${GREEN}phpvm:${NC} switched to PHP ${BOLD}${ver}${NC}"
elif [[ "$rc" -ne 0 ]]; then
echo -e "${RED}phpvm:${NC} failed to switch to PHP ${ver}" >&2
fi
fi
return "$rc"
}
cmd_local() {
local ver="$1"
if [[ -z "$ver" ]]; then
echo -e "${RED}Usage: phpvm local <version>${NC}" >&2
echo -e "${DIM}Example: phpvm local 8.2${NC}" >&2
exit 1
fi
local norm
norm=$(normalize_version "$ver") || {
echo -e "${RED}Invalid version: ${ver}${NC}" >&2
echo -e "${DIM}Expected format: X.Y (e.g. 8.2)${NC}" >&2
exit 1
}
ver="$norm"
if ! find_version_by_query "$ver" >/dev/null; then
echo -e "${YELLOW}!${NC} PHP ${ver} not installed locally. Writing anyway." >&2
fi
if [[ -f .php-version ]] && [[ -t 0 ]]; then
local existing
existing=$(< .php-version)
existing="${existing//[[:space:]]/}"
if [[ "$existing" != "$ver" ]]; then
read -rp " .php-version already says '${existing}'. Overwrite? [y/N] " ans
[[ "$ans" =~ ^[Yy]$ ]] || { echo -e "${DIM}Cancelled.${NC}"; exit 0; }
fi
fi
echo "$ver" > .php-version
echo -e "${GREEN}✓${NC} Created ${BOLD}.php-version${NC} → ${CYAN}${ver}${NC}"
}
# per-shell switching
# Emit shell code for the wrapper to eval. Default POSIX `export`; fish syntax
# under --fish. On any problem it emits a snippet that prints to stderr and runs
# `false`, so the eval in the caller's shell surfaces the error and returns
# non-zero without setting anything.
#
# Confirmation messages are emitted as `echo ... >&2` inside the eval'd snippet
# rather than printed directly. cmd_sh_shell's own stdout is what the wrapper
# captures via `$(...)` (it cannot reach the user's terminal), so the user only
# sees what we route back through the eval. Stderr from here would be visible,
# but inside the wrapper it loses the "after the eval" ordering and looks like a
# separate message; emitting through eval keeps everything in one logical step.
cmd_sh_shell() {
local fish=false do_unset=false ver=""
while [[ $# -gt 0 ]]; do
case "$1" in
--fish) fish=true ;;
--unset) do_unset=true ;;
-*) ;;
*) ver="$1" ;;
esac
shift
done
if [[ "$do_unset" == "true" ]]; then
if [[ "$fish" == "true" ]]; then
echo "set -e PHPVM_SHELL_VERSION"
else
echo "unset PHPVM_SHELL_VERSION"
fi
echo "echo 'phpvm: shell pin removed for this terminal.' >&2"
return 0
fi
local norm
if [[ -z "$ver" ]] || ! norm=$(normalize_version "$ver"); then
echo "echo 'phpvm: usage: phpvm shell <version> | --unset' >&2; false"
return 0
fi
ver="$norm"
if ! find_version_by_query "$ver" >/dev/null; then
echo "echo 'phpvm: PHP ${ver} is not installed (try: phpvm install ${ver})' >&2; false"
return 0
fi
if [[ "$fish" == "true" ]]; then
echo "set -gx PHPVM_SHELL_VERSION ${ver}"
else
echo "export PHPVM_SHELL_VERSION=${ver}"
fi
echo "echo 'phpvm: pinned this terminal to PHP ${ver}.' >&2"
# Make the pin take effect in THIS terminal even when the shim is not
# currently winning the PATH race.
case "$(shim_status)" in
shadowed)
# shim dir is on PATH but a non-shim php precedes it (a profile
# re-prepended /usr/bin after our hook ran). Repair the caller's PATH
# right here via the hook's own function, so php resolves to the shim
# immediately, with no new terminal needed. The wrapper that routed us
# here is from the same hook file that defines _phpvm_path_fix, so the
# guard normally passes. An older hook silently skips it.
if [[ "$fish" == "true" ]]; then
echo "functions -q _phpvm_path_fix; and _phpvm_path_fix"
else
echo "command -v _phpvm_path_fix >/dev/null 2>&1 && _phpvm_path_fix"
fi
;;
absent)
# shim dir not on PATH at all: the hook is not loaded in this shell,
# so the pin cannot take effect yet. Point the user at it.
local hook_dir
hook_dir=$(detect_hook_dir 2>/dev/null || echo "")
echo "echo 'phpvm: ! shell hook not loaded in this terminal, so the pin has no effect yet.' >&2"
[[ -n "$hook_dir" ]] && echo "echo ' Activate now: source ${hook_dir}/php-auto.bash (zsh: php-auto.zsh, fish: php-auto.fish)' >&2"
echo "echo ' Or just open a new terminal.' >&2"
;;
esac
}
# Direct-invoke fallback. The wrapper intercepts `shell` and routes it through
# `sh-shell` + eval, so reaching the binary here means the wrapper is not loaded
# and we cannot change the caller's shell. Tell them how to enable it.
cmd_shell() {
local v="${1:-}"
echo -e "${YELLOW}!${NC} ${BOLD}phpvm shell${NC} needs the shell wrapper to switch this terminal." >&2
echo -e "${DIM}Enable it once (adds the hook + shim to your shell):${NC}" >&2
echo -e "${DIM} phpvm --enable-hook${NC}" >&2
if [[ -n "$v" ]]; then
echo -e "${DIM}Or for this shell only:${NC}" >&2
echo -e "${DIM} eval \"\$(phpvm sh-shell ${v})\"${NC}" >&2
fi
echo -e "${DIM}For a system-wide switch instead, use: phpvm global ${v:-<version>}${NC}" >&2
exit 1
}
# install
# Configure the upstream PHP repo for $ver if apt can't already see php$ver-cli.
# apt and add-apt-repository run under plain sudo (password-gated). The narrow
# NOPASSWD sudoers rule is for `update-alternatives --set` only and must not grow.
ensure_php_repo() {
local kind="$1" codename="$2" ver="$3"
# empty ver = caller needs the repo configured unconditionally (e.g. to
# resolve `latest`); otherwise skip when apt can already see php$ver-cli.
if [[ -n "$ver" ]] && apt_pkg_available "php${ver}-cli"; then
echo -e " ${DIM}Repo already provides php${ver}, skipping repo setup.${NC}"
return 0
fi
case "$kind" in
ubuntu)
echo -e " ${BLUE}Adding${NC} ${BOLD}ppa:ondrej/php${NC}"
if ! command -v add-apt-repository &>/dev/null; then
_sudo_apt install -y software-properties-common || return 1
fi
sudo add-apt-repository -y ppa:ondrej/php || return 1
;;
debian)
local keyring="/etc/apt/keyrings/sury-php.gpg"
local list="/etc/apt/sources.list.d/sury-php.list"
echo -e " ${BLUE}Adding${NC} ${BOLD}deb.sury.org${NC} repo (${codename})"
_sudo_apt install -y ca-certificates curl || return 1
sudo install -d -m 0755 /etc/apt/keyrings || return 1
curl -fsSL https://packages.sury.org/php/apt.gpg | sudo tee "$keyring" >/dev/null || return 1
echo "deb [signed-by=${keyring}] https://packages.sury.org/php/ ${codename} main" \
| sudo tee "$list" >/dev/null || return 1
;;
*)
return 1
;;
esac
_sudo_apt update
}
cmd_install() {
local target="" with_exts="" minimal=false assume_yes=false auto_use=false print_only=false
while [[ $# -gt 0 ]]; do
case "$1" in
--minimal) minimal=true ;;
--with) shift; with_exts="$1" ;;
--with=*) with_exts="${1#--with=}" ;;
-y|--yes) assume_yes=true ;;
--use) auto_use=true ;;
--print|--dry-run) print_only=true ;;
-*)
echo -e "${RED}Unknown flag: $1${NC}" >&2
echo -e "${DIM}Run: phpvm --help${NC}" >&2
exit 1
;;
*) target="$1" ;;
esac
shift
done
if [[ -z "$target" ]]; then
echo -e "${RED}Usage: phpvm install <version> [--minimal] [--with ext,ext] [--use] [--yes] [--print]${NC}" >&2
echo -e "${DIM}Example: phpvm install 8.3${NC}" >&2
exit 1
fi
# version resolution: explicit X.Y or `latest`. patch-level is rejected.
local ver=""
if [[ "$target" == "latest" ]]; then
ver="latest"
elif [[ "$target" =~ ^[0-9]+\.[0-9]+$ ]]; then
ver="$target"
elif [[ "$target" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo -e "${RED}phpvm installs minor versions (X.Y), not patch levels.${NC}" >&2
echo -e "${DIM}For ${target}, drop the patch: phpvm install ${target%.*}${NC}" >&2
exit 1
else
echo -e "${RED}Invalid version: ${target}${NC}" >&2
echo -e "${DIM}Expected X.Y (e.g. 8.3) or 'latest'.${NC}" >&2
exit 1
fi
# distro / repo detection (needed for both dry-run and real install)
local kind codename
read -r kind codename < <(detect_distro_repo)
if [[ "$kind" == "unsupported" ]]; then
echo -e "${RED}phpvm install supports Debian and Ubuntu (and derivatives) only.${NC}" >&2
echo -e "${DIM}On other distros, install PHP with your package manager, then phpvm will pick it up.${NC}" >&2
exit 1
fi
local repo_desc
case "$kind" in
ubuntu) repo_desc="ppa:ondrej/php" ;;
debian) repo_desc="deb https://packages.sury.org/php/ ${codename} main" ;;
esac
# dry-run: report repo + packages without touching the system. host-agnostic,
# CI-safe, no apt-get required.
if [[ "$print_only" == "true" ]]; then
echo "repo: ${repo_desc}"
if [[ "$ver" == "latest" ]]; then
echo "packages: (resolved to the highest php<X.Y>-cli after the repo is configured)"
else
local plist
plist=$(_assemble_packages "$ver" "$minimal" "$with_exts")
echo "packages: ${plist}"
fi
return 0
fi
if ! command -v apt-get &>/dev/null; then
echo -e "${RED}phpvm install needs apt-get (Debian/Ubuntu).${NC}" >&2
exit 1
fi
local is_latest=false
[[ "$ver" == "latest" ]] && is_latest=true
# idempotency for an explicit version (latest is re-checked once it resolves)
if [[ "$is_latest" != "true" ]] && { [[ -x "/usr/bin/php${ver}" ]] || get_php_versions | grep -qx "/usr/bin/php${ver}"; }; then
echo -e "${GREEN}✓${NC} PHP ${BOLD}${ver}${NC} is already installed."
echo -e "${DIM}Use it: phpvm shell ${ver} (this terminal) | phpvm global ${ver} (system) | phpvm local ${ver} (project)${NC}"
exit 0
fi
# confirm: nothing above this point has touched the system. `latest` can't
# list packages yet (needs the repo), so it confirms on the repo alone.
local packages=""
echo ""
if [[ "$is_latest" == "true" ]]; then
echo -e " ${BOLD}Install the latest PHP${NC}"
echo -e " ${DIM}repo:${NC} ${repo_desc}"
echo -e " ${DIM}version:${NC} highest the repo offers (resolved after repo setup)"
else
packages=$(_assemble_packages "$ver" "$minimal" "$with_exts")
echo -e " ${BOLD}Install PHP ${ver}${NC}"
echo -e " ${DIM}repo:${NC} ${repo_desc}"
echo -e " ${DIM}packages:${NC} ${packages}"
fi
echo ""
if [[ "$assume_yes" != "true" ]]; then
if _tty_interactive; then
local ans
read -rp " Proceed? [y/N] " ans < /dev/tty
[[ "$ans" =~ ^[Yy]$ ]] || { echo -e "${DIM}Cancelled.${NC}"; exit 0; }
else
echo -e "${RED}Refusing to install non-interactively without --yes.${NC}" >&2
exit 1
fi
fi
# configure the repo (empty ver forces config, needed to resolve `latest`)
local repo_ver="$ver"
[[ "$is_latest" == "true" ]] && repo_ver=""
if ! ensure_php_repo "$kind" "$codename" "$repo_ver"; then
echo -e "${RED}✗${NC} Failed to configure the PHP repo." >&2
exit 1
fi
if [[ "$is_latest" == "true" ]]; then
ver=$(apt-cache search --names-only '^php[0-9]+\.[0-9]+-cli$' 2>/dev/null \
| grep -oE 'php[0-9]+\.[0-9]+' | sed 's/^php//' | sort -V | tail -1)
if [[ -z "$ver" ]]; then
echo -e "${RED}Could not resolve 'latest' from the configured repos.${NC}" >&2
exit 1
fi
echo -e " ${DIM}latest resolves to ${ver}${NC}"
if [[ -x "/usr/bin/php${ver}" ]] || get_php_versions | grep -qx "/usr/bin/php${ver}"; then
echo -e "${GREEN}✓${NC} PHP ${BOLD}${ver}${NC} (latest) is already installed."
exit 0
fi
packages=$(_assemble_packages "$ver" "$minimal" "$with_exts")
fi
# shellcheck disable=SC2086
if ! _sudo_apt install -y $packages; then
echo -e "${RED}✗${NC} apt-get install failed." >&2
exit 1
fi
# defensive register: Surý packages self-register the `php` alternative, but
# cover the case where they didn't. priority derived from the version (8.3 gives 83).
local bin="/usr/bin/php${ver}"
if [[ -x "$bin" ]] && ! get_php_versions | grep -qx "$bin"; then
local prio="${ver//./}"
sudo update-alternatives --install /usr/bin/php php "$bin" "$prio" >/dev/null 2>&1 || true
fi
echo -e "${GREEN}✓${NC} Installed PHP ${BOLD}${ver}${NC}"
# offer to switch. install runs as a normal subprocess, so the only switch it
# can make durably is the global one (a per-shell pin can't reach back into
# the parent shell from here); the hint points at the no-sudo alternatives.
if [[ "$auto_use" == "true" ]]; then
do_switch "$bin"
elif _tty_interactive; then
local ans
read -rp " Set PHP ${ver} as the system default now? [y/N] " ans < /dev/tty
[[ "$ans" =~ ^[Yy]$ ]] && do_switch "$bin"
else
echo -e "${DIM}Use it: phpvm shell ${ver} (this terminal) | phpvm global ${ver} (system)${NC}"
fi
}
# build the apt package list for a version, honoring --minimal and --with
_assemble_packages() {
local ver="$1" minimal="$2" with_exts="$3"
local pkgs="php${ver}-cli php${ver}-common"
[[ "$minimal" == "true" ]] || pkgs="${pkgs} php${ver}-fpm"
if [[ -n "$with_exts" ]]; then
local ext
IFS=', ' read -ra _exts <<< "$with_exts"
for ext in "${_exts[@]}"; do
[[ -n "$ext" ]] && pkgs="${pkgs} php${ver}-${ext}"
done
fi
echo "$pkgs"
}
detect_hook_dir() {
local d=""
if [[ -d /etc/phpvm ]]; then
d=/etc/phpvm
elif [[ -d "$HOME/.phpvm" ]]; then
d="$HOME/.phpvm"
else
return 1
fi
# canonicalize: the shell hooks put the symlink-resolved dir on PATH (zsh
# `:A`, bash `cd…pwd`, fish `status -f`), so an unresolved $HOME/.phpvm here
# would not string-match the PATH entry on a symlinked HOME -> false "shim
# inactive" warnings. Resolve to the same canonical form.
( cd "$d" 2>/dev/null && pwd -P ) || echo "$d"
}
# Canonicalize a path (resolve symlinks + ..). Falls back to the input when no
# resolver is available, so callers always get something printable.
_phpvm_realpath() {
local p="$1"
[[ -z "$p" ]] && return 1
if command -v realpath >/dev/null 2>&1; then
realpath -- "$p" 2>/dev/null && return 0
fi
readlink -f -- "$p" 2>/dev/null && return 0
echo "$p"
}
# Single source of truth for "is the shim intercepting php in this terminal?".
# Prints exactly one token:
# active - shim exists, its dir is on PATH, and php resolves to it
# shadowed - shim dir on PATH but php resolves to a non-shim binary ahead of it
# absent - shim exists but its dir is not on PATH (hook not loaded here)
# noshim - shim missing / not executable (broken or no install)
# Used by cmd_sh_shell, cmd_current, and cmd_doctor so the three stay consistent.
shim_status() {
local hook_dir shim shim_dir cur_php
hook_dir=$(detect_hook_dir 2>/dev/null) || { echo "noshim"; return; }
shim="${hook_dir}/shims/php"
shim_dir="${hook_dir}/shims"
[[ -x "$shim" ]] || { echo "noshim"; return; }
cur_php=$(command -v php 2>/dev/null || true)
if [[ -n "$cur_php" ]]; then
if [[ "$cur_php" == "$shim" ]] \
|| [[ "$(_phpvm_realpath "$cur_php")" == "$(_phpvm_realpath "$shim")" ]]; then
echo "active"; return
fi
fi
case ":${PATH}:" in
*":${shim_dir}:"*) echo "shadowed" ;;
*) echo "absent" ;;
esac
}
resolve_shell() {
local shell="$1"
[[ -z "$shell" ]] && shell=$(basename "${SHELL:-bash}")
case "$shell" in
bash|zsh|fish) echo "$shell"; return 0 ;;
*) return 1 ;;
esac
}
shell_rc_path() {
case "$1" in
bash) echo "$HOME/.bashrc" ;;
zsh) echo "$HOME/.zshrc" ;;
fish) echo "$HOME/.config/fish/config.fish" ;;
esac
}
cmd_enable_hook() {
local shell
shell=$(resolve_shell "${1:-}") || {
echo -e "${RED}Unsupported shell: ${1:-unknown}${NC}" >&2
echo -e "${DIM}Use bash, zsh, or fish.${NC}" >&2
exit 1
}
local hook_dir
hook_dir=$(detect_hook_dir) || {
echo -e "${RED}Hook directory not found.${NC}" >&2
echo -e "${DIM}Expected /etc/phpvm or ~/.phpvm; re-run install.sh.${NC}" >&2
exit 1
}
local hook_file="${hook_dir}/php-auto.${shell}"
if [[ ! -f "$hook_file" ]]; then
echo -e "${RED}Hook file missing: ${hook_file}${NC}" >&2
exit 1
fi
local rc
rc=$(shell_rc_path "$shell")
local line="source ${hook_file}"
if [[ -f "$rc" ]] && grep -qF "$line" "$rc"; then
echo -e "${YELLOW}!${NC} Already enabled in ${BOLD}${rc}${NC}"
return 0
fi
mkdir -p "$(dirname "$rc")"
{
echo ""
echo "# phpvm auto-switch"
echo "$line"
} >> "$rc"
echo -e "${GREEN}✓${NC} Hook enabled for ${BOLD}${shell}${NC} → ${rc}"
echo -e " ${DIM}Reload: source ${rc}${NC}"
}
cmd_disable_hook() {
local shell
shell=$(resolve_shell "${1:-}") || {
echo -e "${RED}Unsupported shell: ${1:-unknown}${NC}" >&2
exit 1
}
local rc