-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·1915 lines (1753 loc) · 67.2 KB
/
Copy pathsetup.sh
File metadata and controls
executable file
·1915 lines (1753 loc) · 67.2 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
# version: 2.2.2
# Bootstrap this home directory as a checkout of yusing/agentic-dotfiles and
# install the packages and tools the shell configuration expects.
#
# Safe to re-run after a mid-flight failure. Unrelated files already in $HOME
# are left in place. Files that would be overwritten by the checkout are copied
# to ~/.local/share/dotfiles-setup/ first.
set -euo pipefail
REPO_URL="https://github.com/yusing/agentic-dotfiles.git"
REPO_SLUG="yusing/agentic-dotfiles"
PRIVATE_REPO_SLUG="yusing/dotfiles"
GIT_NAME="yusing"
GIT_EMAIL="yusing.wys@gmail.com"
LOCAL_BIN="${HOME}/.local/bin"
BACKUP_ROOT="${HOME}/.local/share/dotfiles-setup"
MISE_BIN="${LOCAL_BIN}/mise"
MISE_SHIMS="${HOME}/.local/share/mise/shims"
MISE_CONFIG="${MISE_CONFIG:-${HOME}/.config/mise/config.toml}"
MISE_LOCK_PLATFORMS="linux-arm64,linux-x64,macos-arm64"
LLVM_BREW_FORMULA_API="https://formulae.brew.sh/api/formula/llvm.json"
UPGRADE=0
SETUP_CONFIG_EXPLICIT="${SETUP_CONFIG:+1}"
SETUP_CONFIG="${SETUP_CONFIG:-$(cd "$(dirname "${BASH_SOURCE[0]:-$HOME/setup.sh}")" && pwd)/setup.json}"
STEP="starting"
trap 'printf "setup.sh failed during: %s\n" "$STEP" >&2' ERR
log() { printf '%s\n' "$*"; }
info() { printf '==> %s\n' "$*"; }
warn() { printf 'warning: %s\n' "$*" >&2; }
die() { printf 'error: %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }
# in_list NEEDLE [ITEM...]
# Empty arrays must be expanded as ${arr[@]+"${arr[@]}"} so bash 3.2 `set -u`
# does not treat "${arr[@]}" as unbound.
in_list() {
local needle="$1" item
shift
for item in "$@"; do
[ "$item" != "$needle" ] || return 0
done
return 1
}
run_root() {
if [ "$(id -u)" -eq 0 ]; then
"$@"
else
sudo "$@"
fi
}
# ---------------------------------------------------------------------------
# PATH and OS
# ---------------------------------------------------------------------------
export PATH="${MISE_SHIMS}:${LOCAL_BIN}:${HOME}/.grok/bin:${HOME}/.bun/bin:${PATH}"
export DEBIAN_FRONTEND=noninteractive
export NONINTERACTIVE=1
export GIT_TERMINAL_PROMPT=0
OS="$(uname -s)"
ARCH="$(uname -m)"
case "$ARCH" in
x86_64) GOARCH=amd64 ;;
aarch64|arm64) GOARCH=arm64 ;;
*) die "unsupported architecture: $ARCH" ;;
esac
PM=""
detect_pm() {
case "$OS" in
Darwin)
PM=brew
;;
Linux)
[ -r /etc/os-release ] || die "cannot detect distro: /etc/os-release is missing"
# shellcheck disable=SC1091
. /etc/os-release
case "${ID:-}" in
ubuntu|debian)
PM=apt
;;
arch|cachyos)
PM=pacman
;;
*)
case " ${ID_LIKE:-} " in
*" arch "*)
PM=pacman
;;
*" debian "*|*" ubuntu "*)
PM=apt
;;
*)
die "unsupported linux distro: ${ID:-unknown}"
;;
esac
;;
esac
;;
*)
die "unsupported OS: $OS"
;;
esac
}
load_brew_env() {
if [ -x /opt/homebrew/bin/brew ]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -x /usr/local/bin/brew ]; then
eval "$(/usr/local/bin/brew shellenv)"
elif have brew; then
eval "$(brew shellenv)"
fi
}
load_brew_llvm_env() {
local prefix
[ "$PM" = brew ] || return 0
have brew || return 0
prefix="$(brew --prefix llvm 2>/dev/null || true)"
[ -n "$prefix" ] && [ -d "$prefix/bin" ] || return 0
export PATH="${prefix}/bin:${PATH}"
}
ensure_brew() {
[ "$PM" = brew ] || return 0
load_brew_env
if have brew; then
return 0
fi
info "installing Homebrew"
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
load_brew_env
have brew || die "Homebrew installed but brew is not on PATH"
}
# yay-bin is used for the AUR bootstrap because it does not need a Go toolchain
# (this script installs the latest Go later).
ensure_yay() {
local tmp
[ "$PM" = pacman ] || return 0
if have yay; then
return 0
fi
info "installing yay"
if run_root pacman -S --needed --noconfirm yay && have yay; then
return 0
fi
run_root pacman -S --needed --noconfirm git base-devel \
|| die "git and base-devel are required to build yay"
have git || die "git is required to build yay"
if [ "$(id -u)" -eq 0 ]; then
die "yay is not in the pacman repos and cannot be built as root; install yay and re-run"
fi
tmp="$(mktemp -d "${TMPDIR:-/tmp}/setup-yay.XXXXXX")"
git clone --depth 1 https://aur.archlinux.org/yay-bin.git "$tmp/yay-bin"
(cd "$tmp/yay-bin" && makepkg -si --noconfirm)
rm -rf "$tmp"
hash -r 2>/dev/null || true
have yay || die "yay is required on Arch"
}
ensure_sudo() {
[ "$PM" = brew ] && return 0
if [ "$(id -u)" -eq 0 ]; then
return 0
fi
have sudo || die "sudo is required to install packages"
sudo -v
(
while true; do
sudo -n true
sleep 60
kill -0 "$$" || exit
done
) 2>/dev/null &
}
# ---------------------------------------------------------------------------
# Package mapping: logical name -> distro/brew package
# ---------------------------------------------------------------------------
# Prints one or more package-manager names for a logical package, or an empty
# line if this manager has nothing to install for it.
mapped_pkgs() { setup_config native-packages "$1"; }
pkg_cmd() { setup_config native-command "$1"; }
have_logical() {
local name="$1" cmd prefix commands
setup_config native-enabled "$name" || return 1
prefix="$(setup_config native-prefix "$name")" || return 1
if [ "$PM" = brew ] && [ -n "$prefix" ]; then
prefix="$(brew --prefix "$prefix" 2>/dev/null || true)"
cmd="$(pkg_cmd "$name")"
[ -n "$prefix" ] && [ -x "$prefix/bin/$cmd" ]
return
fi
commands="$(setup_config native-commands "$name")" || return 1
if [ -z "$commands" ]; then
# No executable probe: ask the package manager rather than assuming success.
commands="$(mapped_pkgs "$name")" || return 1
while IFS= read -r cmd; do
case "$PM" in
apt) if dpkg-query -W -f='${Status}\n' "$cmd" 2>/dev/null | grep -q 'install ok installed'; then return 0; fi ;;
brew) if [ -n "$(brew list --versions "$cmd" 2>/dev/null)" ]; then return 0; fi ;;
pacman) if pacman -Q "$cmd" >/dev/null 2>&1; then return 0; fi ;;
esac
done <<<"$commands"
return 1
fi
while IFS= read -r cmd; do
have "$cmd" && return 0
done <<<"$commands"
return 1
}
py() {
if [ -n "${SETUP_PYTHON:-}" ]; then
"$SETUP_PYTHON" "$@"
elif have python3; then
python3 "$@"
elif have python; then
python "$@"
else
die "python3 is required"
fi
}
ensure_toml_parser() {
local check=$'try:\n import tomllib\nexcept ImportError:\n import tomli'
py -c "$check" >/dev/null 2>&1 && return 0
info "installing Python TOML support"
case "$PM" in
apt) refresh_pm; pm_install_batch python3-tomli ;;
pacman) pm_install_batch python-tomli ;;
brew)
pm_install_batch python
SETUP_PYTHON="$(brew --prefix python)/bin/python3"
;;
esac
py -c "$check" >/dev/null 2>&1 \
|| die "Python TOML support is unavailable; use Python 3.11+ or install tomli for the active Python"
}
# JSON values travel as data, never as shell source. Validate before emitting any
# records so malformed config cannot turn into a partial install plan.
setup_config() {
SETUP_PM="$PM" SETUP_OS="$OS" \
py - "$SETUP_CONFIG" "$@" <<'PY'
import json
import math
import os
import re
import sys
from pathlib import Path
def require(ok, message):
if not ok:
raise ValueError(message)
def obj(value, allowed, where):
require(isinstance(value, dict), f"{where} must be an object")
require(not (set(value) - set(allowed)), f"unknown field in {where}: {set(value) - set(allowed)}")
def string(value):
require(isinstance(value, str) and value and not any(c in value for c in "\n\r\0|"), "expected a nonempty, single-line string without |")
def strings(value):
require(isinstance(value, list), "expected an array")
for item in value:
string(item)
def relative(value):
string(value)
require(not value.startswith(("/", "-")) and all(p not in {"", ".", ".."} for p in value.split("/")), "paths must be relative to HOME without . or .. components")
def packages(value):
obj(value, ("apt", "brew", "pacman"), "packages")
for items in value.values():
strings(items)
require(all(not x.startswith("-") and not any(c.isspace() for c in x) for x in items), "invalid package name")
def unique_object(pairs):
result = {}
for key, value in pairs:
require(key not in result, f"duplicate JSON key: {key}")
result[key] = value
return result
try:
config = json.loads(Path(sys.argv[1]).read_text(), object_pairs_hook=unique_object)
obj(config, ("version", "native", "mise", "mise_commands", "vendors", "legacy"), "setup")
require(type(config.get("version")) is int and config["version"] == 2, "unsupported setup config version")
for section in ("native", "mise_commands", "vendors", "legacy"):
require(isinstance(config.get(section), dict), f"{section} must be an object")
for name in config[section]:
string(name)
require(not name.startswith("-"), "names must not start with -")
for entry in config["native"].values():
obj(entry, ("packages", "commands", "optional", "brew_prefix"), "native package")
packages(entry.get("packages"))
strings(entry.get("commands", []))
require(type(entry.get("optional", False)) is bool, "optional must be boolean")
if "brew_prefix" in entry:
string(entry["brew_prefix"])
for command in config["mise_commands"].values():
string(command)
obj(config.get("mise"), ("settings", "tools"), "mise")
require(isinstance(config["mise"].get("settings", {}), dict), "mise.settings must be an object")
require(isinstance(config["mise"].get("tools"), dict), "mise.tools must be an object")
for tool, declaration in config["mise"]["tools"].items():
string(tool)
require(not tool.startswith("-"), "invalid mise tool name")
require(isinstance(declaration, (str, dict)), "mise tool must be a version string or options object")
string(declaration if isinstance(declaration, str) else declaration.get("version"))
def toml(value):
if isinstance(value, str):
return json.dumps(value, ensure_ascii=False)
if type(value) is bool:
return "true" if value else "false"
if type(value) is int:
return str(value)
if type(value) is float:
require(math.isfinite(value), "non-finite TOML number")
return str(value)
if isinstance(value, list):
return "[" + ", ".join(toml(item) for item in value) + "]"
if isinstance(value, dict):
return "{ " + ", ".join(json.dumps(key) + " = " + toml(item) for key, item in value.items()) + " }"
raise ValueError("mise values must be TOML-compatible: null is not supported")
def render_mise(data):
result = "# Generated by setup.sh from setup.json. Edit setup.json, not this file.\n"
for section in ("settings", "tools"):
result += f"\n[{section}]\n"
for key, value in data.get(section, {}).items():
result += json.dumps(key) + " = " + toml(value) + "\n"
return result
rendered = render_mise(config["mise"])
def lock_matches(tool, declaration, entry):
selector = declaration["version"] if isinstance(declaration, dict) else declaration
if selector not in entry.get("specifiers", []):
return False
# Qualified identifiers declare their backend. Bare aliases deliberately
# leave backend selection to mise's registry and the lock itself.
if ":" in tool and entry.get("backend") not in (None, tool):
return False
# npm preserves complete semver pins exactly. Other providers may
# normalize or expand numeric selectors, so mise owns their exactness.
if tool.startswith("npm:") and re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?", selector):
if entry.get("version") != selector:
return False
return True
for entry in config["vendors"].values():
obj(entry, ("label", "path", "url", "shell", "update", "env", "legacy_mise"), "vendor")
for field in ("label", "url", "shell"):
string(entry.get(field))
relative(entry.get("path"))
require(entry["url"].startswith("https://"), "vendor URL must use HTTPS")
require(entry["shell"] in ("sh", "bash"), "vendor shell must be sh or bash")
strings(entry.get("update", []))
strings(entry.get("legacy_mise", []))
require(all(not x.startswith("-") for x in entry.get("legacy_mise", [])), "invalid legacy mise tool")
require(isinstance(entry.get("env", {}), dict), "vendor env must be an object")
for key, value in entry.get("env", {}).items():
require(re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key), "invalid environment variable name")
string(value)
for entry in config["legacy"].values():
obj(entry, ("packages", "bun", "files", "directories"), "legacy entry")
packages(entry.get("packages", {}))
if "bun" in entry:
string(entry["bun"])
require(not entry["bun"].startswith("-"), "invalid legacy bun package")
for field in ("files", "directories"):
require(isinstance(entry.get(field, []), list), f"{field} must be an array")
for item in entry.get("files", []):
obj(item, ("path", "command"), "legacy file")
relative(item.get("path"))
string(item.get("command"))
for item in entry.get("directories", []):
obj(item, ("path", "executable", "origin_contains"), "legacy directory")
relative(item.get("path"))
require(item["path"] not in {".local", ".local/bin", ".local/share", ".local/opt", ".config", "go", "go/bin", ".bun", ".bun/bin"}, "legacy directory is too broad")
require(("executable" in item) != ("origin_contains" in item), "legacy directory needs exactly one ownership probe")
if "executable" in item:
relative(item["executable"])
else:
string(item["origin_contains"])
action = sys.argv[2]
name = sys.argv[3] if len(sys.argv) > 3 else ""
pm = os.environ["SETUP_PM"]
platform = {"Darwin": "macos", "Linux": "linux"}.get(os.environ["SETUP_OS"])
output = []
if action == "validate":
pass
elif action.startswith("native-"):
if action in ("native-required", "native-optional"):
output = [key for key, entry in config["native"].items()
if entry["packages"].get(pm, []) and entry.get("optional", False) == (action == "native-optional")]
elif action == "native-enabled":
sys.exit(0 if config["native"].get(name, {}).get("packages", {}).get(pm) else 1)
else:
entry = config["native"][name]
if action == "native-packages":
output = entry["packages"].get(pm, [])
elif action == "native-command":
output = entry.get("commands", [])[:1]
elif action == "native-commands":
output = entry.get("commands", [])
elif action == "native-prefix":
output = [entry.get("brew_prefix", "")]
else:
raise ValueError(f"unknown action: {action}")
elif action == "mise-render":
sys.stdout.write(rendered)
sys.exit(0)
elif action in ("mise-plan", "mise-verify-lock"):
try:
import tomllib
except ImportError:
import tomli as tomllib
root = Path(name)
def read_toml(path):
return tomllib.loads(path.read_text()) if path.exists() else {}
previous = read_toml(root / "previous.toml")
old_lock = read_toml(root / "previous.lock")
old_tools = old_lock.get("tools", {})
if action == "mise-verify-lock":
retained = json.loads((root / "retained.json").read_text())
updated = read_toml(root / ".config/mise/mise.lock").get("tools", {})
desired = read_toml(root / "desired.toml").get("tools", {})
for tool, declaration in desired.items():
entries = updated.get(tool, [])
require(len(entries) == 1 and lock_matches(tool, declaration, entries[0]),
f"lock entry does not match declaration: {tool}")
for tool in retained:
require(updated.get(tool) == old_tools[tool], f"lock refresh unexpectedly changed retained tool: {tool}")
else:
desired = read_toml(root / "desired.toml")
tools = desired.get("tools", {})
changed = {
tool for tool, value in tools.items()
if sys.argv[4] == "1" or previous.get("tools", {}).get(tool) != value
or len(old_tools.get(tool, [])) != 1
or not lock_matches(tool, value, old_tools[tool][0])
}
retained = set(tools) - changed
(root / "retained.json").write_text(json.dumps(sorted(retained)))
# Preserve retained records verbatim; remove an entire tool record,
# including its platform subtables, for deletions and option changes.
old_text = (root / "previous.lock").read_text() if (root / "previous.lock").exists() else "lockfile_version = 1\n"
headers = list(re.finditer(r"^\[\[tools\.(.+)\]\][ \t]*$", old_text, re.MULTILINE))
pruned = old_text[:headers[0].start()] if headers else old_text
for index, match in enumerate(headers):
tool = next(iter(tomllib.loads(match[0])["tools"]))
if tool in retained:
end = headers[index + 1].start() if index + 1 < len(headers) else len(old_text)
pruned += old_text[match.start():end]
(root / ".config/mise/mise.lock").write_text(pruned)
# Mise resolves its whole input before filtering tool arguments.
# Pin unchanged declarations so their latest selectors do not advance.
resolution = dict(desired)
resolution["tools"] = dict(tools)
for tool in retained:
value = tools[tool]
version = old_tools[tool][0]["version"]
resolution["tools"][tool] = dict(value, version=version) if isinstance(value, dict) else version
(root / ".config/mise/config.toml").write_text(render_mise(resolution))
for os_name in ("linux", "macos"):
selected = []
for tool, value in tools.items():
platforms = value.get("os", ["linux", "macos"]) if isinstance(value, dict) else ["linux", "macos"]
if tool in changed and os_name in platforms:
selected.append(tool)
(root / (os_name + "-tools")).write_text("".join(tool + "\n" for tool in selected))
(root / "changed-tools").write_text("".join(tool + "\n" for tool in tools if tool in changed))
bootstrap = []
for runtime, backend in (("go", "go:"), ("bun", "npm:")):
if runtime in tools and any(tool.startswith(backend) for tool in changed):
mode = "locked" if runtime in old_tools and runtime in previous.get("tools", {}) else "unlocked"
bootstrap.append(f"{runtime}|{mode}\n")
(root / "bootstrap-tools").write_text("".join(bootstrap))
print(f"mise lock: {len(changed)} added/changed, {len(set(old_tools) - set(tools))} removed, {len(retained)} retained")
elif action.startswith("mise-"):
tools = config["mise"]["tools"]
def platforms(value):
return value.get("os", ["linux", "macos"]) if isinstance(value, dict) else ["linux", "macos"]
if action == "mise-records":
for tool in tools:
command = config["mise_commands"].get(tool, tool.rsplit(":", 1)[-1].rsplit("/", 1)[-1])
string(tool)
string(command)
output.append(f"{tool}|{command}")
elif action == "mise-applies":
sys.exit(0 if name in tools and platform in platforms(tools[name]) else 1)
elif action == "mise-has":
sys.exit(0 if name in tools else 1)
else:
raise ValueError(f"unknown action: {action}")
elif action == "vendors":
output = [f"{key}|{entry['label']}" for key, entry in config["vendors"].items()]
elif action == "vendor-field":
value = config["vendors"][name].get(sys.argv[4], [])
output = value if isinstance(value, list) else [value]
elif action == "vendor-env":
output = [f"{key}={value}" for key, value in config["vendors"][name].get("env", {}).items()]
elif action.startswith("legacy-"):
entry = config["legacy"].get(name, {})
if action == "legacy-packages":
output = entry.get("packages", {}).get(pm, [])
elif action == "legacy-bun":
output = [entry.get("bun", "")]
elif action == "legacy-files":
output = [f"{item['path']}|{item['command']}" for item in entry.get("files", [])]
elif action == "legacy-directories":
output = [f"{item['path']}|{item.get('executable', '')}|{item.get('origin_contains', '')}" for item in entry.get("directories", [])]
else:
raise ValueError(f"unknown action: {action}")
else:
raise ValueError(f"unknown action: {action}")
for value in output:
print(value)
except (ValueError, KeyError, TypeError, OSError, ImportError) as error:
print(f"setup config: {error}", file=sys.stderr)
sys.exit(1)
PY
}
install_configured_packages() {
local name records
local names=()
records="$(setup_config native-required)" || return 1
while IFS= read -r name; do [ -z "$name" ] || names+=("$name"); done <<<"$records"
names+=(--optional)
records="$(setup_config native-optional)" || return 1
while IFS= read -r name; do [ -z "$name" ] || names+=("$name"); done <<<"$records"
install_packages "${names[@]}"
}
# Upgrade declared installed alternatives; Arch requires a full system upgrade.
upgrade_configured_packages() {
[ "$UPGRADE" -eq 1 ] || return 0
if [ "$PM" = pacman ]; then
info "upgrading the full Arch system"
refresh_pm || return 1
return 0
fi
local records optional_records name candidates pkg installed
local packages=()
records="$(setup_config native-required)" || return 1
optional_records="$(setup_config native-optional)" || return 1
records="${records}"$'\n'"${optional_records}"
while IFS= read -r name; do
[ -n "$name" ] || continue
candidates="$(mapped_pkgs "$name")" || return 1
while IFS= read -r pkg; do
[ -n "$pkg" ] || continue
installed="$(installed_pm_package "$pkg")" || continue
[ -n "$installed" ] || continue
if ! in_list "$pkg" ${packages[@]+"${packages[@]}"}; then packages+=("$pkg"); fi
# Mappings are alternatives, not additional packages to manage.
break
done <<<"$candidates"
done <<<"$records"
[ "${#packages[@]}" -gt 0 ] || return 0
info "upgrading setup-owned native packages: ${packages[*]}"
case "$PM" in
apt)
run_root apt-get update -y || return 1
run_root apt-get install --only-upgrade --no-remove -y "${packages[@]}" || return 1
;;
brew)
brew update || return 1
HOMEBREW_NO_AUTO_UPDATE=1 brew upgrade --formula "${packages[@]}" || return 1
;;
*) die "unknown package manager: $PM" ;;
esac
}
refresh_pm() {
case "$PM" in
apt)
run_root apt-get update -y
;;
pacman)
yay -Syu --noconfirm --answerclean None --answerdiff None
;;
brew)
# brew install refreshes as needed; a full update is slow on reruns
true
;;
esac
}
apt_pkg_available() {
local cand
# apt-cache show can succeed for a package with no installable version.
# "Candidate: (none)" is what later becomes "has no installation candidate"
# and would abort a whole apt-get batch.
cand="$(apt-cache policy "$1" 2>/dev/null | awk '$1 == "Candidate:" { print $2; exit }')"
[ -n "$cand" ] && [ "$cand" != "(none)" ]
}
# Prints the first mapped package that this machine can actually install.
# Exit 0 with empty output if this package manager has nothing to install.
# Exit 1 if every mapped name lacks an install candidate.
select_mapped_pkg() {
local name="$1" pkg any=0
while IFS= read -r pkg; do
[ -n "$pkg" ] || continue
any=1
if [ "$PM" != apt ]; then
printf '%s\n' "$pkg"
return 0
fi
if apt_pkg_available "$pkg"; then
printf '%s\n' "$pkg"
return 0
fi
done <<EOF
$(mapped_pkgs "$name")
EOF
[ "$any" -eq 0 ]
}
pm_install_batch() {
[ "$#" -gt 0 ] || return 0
case "$PM" in
apt)
run_root apt-get install -y "$@"
;;
pacman)
if have yay && [ "$(id -u)" -ne 0 ]; then
yay -S --needed --noconfirm --answerclean None --answerdiff None "$@"
else
run_root pacman -S --needed --noconfirm "$@"
fi
;;
brew)
brew install --no-ask "$@"
;;
*)
die "unknown package manager: $PM"
;;
esac
}
# install_packages NAME... [--optional NAME...]
# One package-manager transaction for the whole list. Optional names that are
# missing from the apt index are skipped so a single unknown package cannot
# split the install back into a per-package loop (and re-trigger initramfs).
install_packages() {
local name pkg cmd mode=required apt_refreshed=0
local required_names=()
local pkgs=()
for name in "$@"; do
if [ "$name" = --optional ]; then
mode=optional
continue
fi
if [ "$mode" = required ]; then
required_names+=("$name")
fi
if have_logical "$name"; then
continue
fi
if [ "$PM" = apt ] && [ "$apt_refreshed" -eq 0 ]; then
refresh_pm
apt_refreshed=1
fi
if ! pkg="$(select_mapped_pkg "$name")"; then
if [ "$mode" = required ]; then
die "required package $name has no install candidate"
fi
warn "$name has no package candidate; will try another install path if one exists"
continue
fi
[ -n "$pkg" ] || continue
pkgs+=("$pkg")
done
if [ "${#pkgs[@]}" -eq 0 ]; then
return 0
fi
info "installing ${pkgs[*]}"
if ! pm_install_batch "${pkgs[@]}"; then
retry_batch_without_unavailable || true
if [ "${#required_names[@]}" -gt 0 ]; then
for name in "${required_names[@]}"; do
if ! have_logical "$name"; then
die "failed to install required package: $name"
fi
done
fi
warn "batch install reported failure; optional packages may be missing"
fi
hash -r 2>/dev/null || true
}
# After a failed apt transaction, drop packages that are already installed or
# still have no candidate and retry the remainder once as a batch. Never
# falls back to installing packages one by one. Pacman/brew have no equivalent
# candidate filter here, so they do not retry.
retry_batch_without_unavailable() {
local pkg retry=() i=0
[ "$PM" = apt ] || return 1
while [ "$i" -lt "${#pkgs[@]}" ]; do
pkg="${pkgs[$i]}"
i=$((i + 1))
if dpkg-query -W -f='${Status}\n' "$pkg" 2>/dev/null | grep -q 'install ok installed'; then
continue
fi
apt_pkg_available "$pkg" || continue
retry+=("$pkg")
done
if [ "${#retry[@]}" -eq 0 ]; then
return 1
fi
if [ "${#retry[@]}" -eq "${#pkgs[@]}" ]; then
return 1
fi
info "retrying batch without unavailable packages: ${retry[*]}"
pm_install_batch "${retry[@]}"
}
# ---------------------------------------------------------------------------
# Git identity and $HOME checkout
# ---------------------------------------------------------------------------
configure_git_identity() {
local current
current="$(git config --global --get user.name 2>/dev/null || true)"
if [ "$current" != "$GIT_NAME" ]; then
git config --global user.name "$GIT_NAME"
fi
current="$(git config --global --get user.email 2>/dev/null || true)"
if [ "$current" != "$GIT_EMAIL" ]; then
git config --global user.email "$GIT_EMAIL"
fi
current="$(git config --global --get init.defaultBranch 2>/dev/null || true)"
if [ "$current" != main ]; then
git config --global init.defaultBranch main
fi
}
ensure_origin() {
local url=""
if url="$(git remote get-url origin 2>/dev/null)"; then
case "$url" in
*github.com[:/]"$REPO_SLUG"*) return 0 ;;
*[:/]"$PRIVATE_REPO_SLUG"|*[:/]"$PRIVATE_REPO_SLUG".git) return 1 ;;
esac
die "origin is $url; refusing to replace a different repository in $HOME"
fi
git remote add origin "$REPO_URL"
}
# Copy overlapping paths out of the way so a dirty $HOME can still take the
# tracked files from origin/main. Identical untracked files still have to move;
# git will not overwrite them in place.
backup_checkout_collisions() {
local ref="$1"
local path local_path tracked origin_hash local_hash
local backed=0
BACKUP_DIR="${BACKUP_ROOT}/backup-$(date +%Y%m%d%H%M%S)"
while IFS= read -r -d '' path; do
local_path="${HOME}/${path}"
if [ ! -e "$local_path" ] && [ ! -L "$local_path" ]; then
continue
fi
tracked=0
if git rev-parse --verify --quiet HEAD >/dev/null \
&& git ls-files --error-unmatch -- "$path" >/dev/null 2>&1; then
tracked=1
fi
if [ "$tracked" -eq 1 ]; then
# Tracked files are stashed or updated by pull; do not move them here.
continue
fi
# Untracked (or type-conflicting) path that origin also has.
if [ -f "$local_path" ] && [ ! -L "$local_path" ]; then
origin_hash="$(git rev-parse "${ref}:${path}")"
local_hash="$(git hash-object "$local_path")"
if [ "$origin_hash" = "$local_hash" ]; then
rm -f "$local_path"
continue
fi
fi
mkdir -p "$(dirname "${BACKUP_DIR}/${path}")"
cp -a "$local_path" "${BACKUP_DIR}/${path}"
rm -rf "$local_path"
backed=1
done < <(git ls-tree -z -r --name-only "$ref")
if [ "$backed" -eq 1 ]; then
info "backed up overlapping home files to ${BACKUP_DIR}"
else
rmdir "$BACKUP_DIR" 2>/dev/null || true
fi
}
drop_bootstrap_empty_commit() {
local ahead
git rev-parse --verify --quiet HEAD >/dev/null || return 0
git show-ref --verify --quiet refs/remotes/origin/main || return 0
ahead="$(git rev-list --count origin/main..HEAD)"
# Mixed reset keeps dirty tracked files. checkout -f would throw them away.
if [ "$ahead" -eq 1 ] \
&& [ "$(git log -1 --format=%s)" = rebase ] \
&& [ -z "$(git diff --stat origin/main HEAD)" ]; then
info "dropping leftover bootstrap commit"
git reset origin/main
fi
}
setup_home_repo() {
local update_checkout
cd "$HOME"
if [ ! -d .git ]; then
info "initializing git repository in $HOME"
if git init -b main >/dev/null 2>&1; then
true
else
git init
git checkout -B main >/dev/null 2>&1 || true
fi
fi
# A recognized private source checkout is already authoritative. Keep its
# origin, history, and identity, but still activate the tracked hooks.
if ensure_origin; then
update_checkout=1
else
update_checkout=0
fi
git config --local core.hooksPath .githooks
if [ "$update_checkout" -eq 0 ]; then
info "preserving private repository checkout at $HOME"
return 0
fi
configure_git_identity
info "fetching origin"
git fetch origin
git show-ref --verify --quiet refs/remotes/origin/main \
|| die "origin/main does not exist on $REPO_URL"
backup_checkout_collisions origin/main
if ! git rev-parse --verify --quiet HEAD >/dev/null; then
info "checking out origin/main"
git checkout -f -B main origin/main
return 0
fi
drop_bootstrap_empty_commit
if [ "$(git symbolic-ref --short HEAD 2>/dev/null || true)" != main ]; then
git branch -M main 2>/dev/null || git checkout -B main
fi
if ! git diff --quiet || ! git diff --cached --quiet; then
info "stashing local tracked changes"
git stash push -m "setup.sh: local tracked changes"
STASHED=1
else
STASHED=0
fi
info "rebasing onto origin/main"
if ! git pull --rebase origin main; then
git rebase --abort >/dev/null 2>&1 || true
if [ "${STASHED:-0}" -eq 1 ]; then
git stash pop || true
fi
die "git pull --rebase origin main failed; resolve the repo in $HOME and re-run"
fi
if [ "${STASHED:-0}" -eq 1 ]; then
git stash pop || warn "stash pop had conflicts; resolve them in $HOME"
fi
}
rewrite_home_paths() {
local changed
changed="$(CONFIG_SOURCE_HOME="/home/${GIT_NAME}" py - <<'PY'
import os
import subprocess
from pathlib import Path
home = Path(os.environ["HOME"])
source_home = os.environ["CONFIG_SOURCE_HOME"]
tracked = subprocess.run(
["git", "ls-files", "-z"],
check=True,
stdout=subprocess.PIPE,
).stdout.decode().split("\0")
def is_runtime_config(path: Path) -> bool:
name = path.as_posix()
if name in {
".claude/settings.json",
".codex/config.toml",
".codex/hooks.json",
".config/fish/config.fish",
".gitconfig",
".grok/config.toml",
".bashrc",
".zsh/fish-mirror.zsh",
".zshrc",
}:
return True
if name.startswith(".claude/agents/"):
return path.suffix == ".md"
if name.startswith(".codex/agents/"):
return path.suffix == ".toml"
if name.startswith(".grok/hooks/"):
return path.suffix in {".json", ".toml", ".yaml", ".yml"}
return name.startswith(".config/") and path.suffix in {
".json",
".toml",
".yaml",
".yml",
}
changed = 0
for name in tracked:
relative = Path(name)
if not name or not is_runtime_config(relative):
continue
path = home / relative
if not path.is_file() or path.is_symlink():
continue
text = path.read_text(encoding="utf-8")
resolved = text.replace(source_home, str(home))
if relative.parts[0] in {".claude", ".codex", ".grok"}:
resolved = resolved.replace("$HOME", str(home))
if resolved == text:
continue
path.write_text(resolved, encoding="utf-8")
changed += 1
print(changed)
PY
)"
if [ "$changed" -gt 0 ]; then
info "resolved home paths in $changed configuration files"
fi
}
# ---------------------------------------------------------------------------
# Cross-platform tools managed by mise
# ---------------------------------------------------------------------------
mise_cmd() {
"$MISE_BIN" "$@"
}
install_mise() {
local installed=0 staged
mkdir -p "$LOCAL_BIN"
if [ -L "$MISE_BIN" ] || [ ! -x "$MISE_BIN" ]; then
[ ! -L "$MISE_BIN" ] || info "replacing legacy mise link $MISE_BIN"
info "installing mise"
(
staged="$(mktemp "${MISE_BIN}.setup.XXXXXX")"
trap 'rm -f "$staged"' EXIT HUP INT TERM
if ! curl -fsSL https://mise.run | MISE_INSTALL_PATH="$staged" sh; then
die "mise installer failed; existing $MISE_BIN was preserved"
fi
"$staged" --version >/dev/null 2>&1 \
|| die "downloaded mise failed validation; existing $MISE_BIN was preserved"
mv -f "$staged" "$MISE_BIN"
trap - EXIT HUP INT TERM
) || return $?