Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
executable file
·308 lines (270 loc) · 11.5 KB
/
Copy pathsetup.py
File metadata and controls
executable file
·308 lines (270 loc) · 11.5 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
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["yaspin"]
# ///
# generated by ai
import argparse
import os
import plistlib
import subprocess
import time
from contextlib import contextmanager
from pathlib import Path
from yaspin import yaspin
DOTFILES = Path(__file__).parent.resolve()
HOME = Path.home()
# same spelling the Brewfile loader uses to pick Brewfile.<host>
HOST = subprocess.run(["hostname", "-s"], capture_output=True, text=True).stdout.strip()
# brew's tap-trust store lives under XDG_CONFIG_HOME (~/.config/homebrew/trust.json);
# without it (ssh, launchd, bootstrap) brew reads an empty ~/.homebrew/trust.json
XDG_CONFIG_HOME = os.environ.setdefault("XDG_CONFIG_HOME", str(HOME / ".config"))
# ssh/launchd shells lack these; dotnet-sdk's cask doesn't always link its binary into brew's bin
os.environ["PATH"] = ":".join([
"/opt/homebrew/bin", "/usr/local/bin", "/usr/local/share/dotnet",
str(HOME / ".volta/bin"), str(HOME / ".local/bin"), os.environ["PATH"],
])
parser = argparse.ArgumentParser()
parser.add_argument("--upgrade", action="store_true", help="also run `brew upgrade` (slow)")
ARGS = parser.parse_args()
BLUE = "\033[34m"
GREEN = "\033[32m"
RED = "\033[31m"
RESET = "\033[0m"
errors = []
@contextmanager
def section(title):
print(f"{BLUE}* {title}{RESET}")
yield
print()
def ok(msg):
print(f"{GREEN} - {msg}{RESET}")
def fail(label, detail):
errors.append((label, detail))
print(f"{RED} - {label} ✗{RESET}")
def run(label, *cmd, stream=False):
try:
if stream:
with yaspin(text=label) as sp:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
assert proc.stdout
proc.stdout.read()
proc.wait()
rc = proc.returncode
else:
result = subprocess.run(cmd, capture_output=True)
rc = result.returncode
except FileNotFoundError:
fail(label, f"command not found: {cmd[0]}")
return
if rc == 0:
ok(label)
else:
fail(label, f"run manually to debug: {' '.join(cmd)}")
def symlink(src, target):
src, target = Path(src), Path(target)
if target.is_symlink():
if Path(os.readlink(target)) == src:
ok(str(target))
return
target.unlink()
elif target.exists():
fail(str(target), f"exists and is not a symlink — remove it to fix: rm -rf {target}")
return
target.parent.mkdir(parents=True, exist_ok=True)
target.symlink_to(src)
ok(str(target))
# output passes through: brew prompts (cask sudo) and errors must be visible
def run_visible(label, *cmd):
rc = subprocess.run(cmd).returncode
if rc == 0:
ok(label)
else:
fail(label, f"exited {rc}: {' '.join(cmd)}")
# homebrew (install only; upgrading 100+ formulae is slow, so it's opt-in)
with section("homebrew"):
run_visible("brew bundle install", "brew", "bundle", "install", f"--file={DOTFILES}/Brewfile", "--no-upgrade")
if ARGS.upgrade:
run_visible("brew upgrade", "brew", "upgrade")
# symlinks
def remove_stale_config_symlinks():
config_dir = HOME / ".config"
if not config_dir.exists():
return
for entry in config_dir.iterdir():
if not entry.is_symlink():
continue
target = Path(os.readlink(entry))
if not target.is_absolute():
target = entry.parent / target
try:
target.relative_to(DOTFILES)
except ValueError:
continue
if not target.exists():
entry.unlink()
ok(f"removed stale symlink: {entry}")
with section("symlinks"):
(HOME / ".config").mkdir(exist_ok=True)
remove_stale_config_symlinks()
for name in os.listdir(DOTFILES / "config"):
symlink(DOTFILES / "config" / name, HOME / ".config" / name)
for src, target in {
DOTFILES / "zshrc": HOME / ".zshrc",
DOTFILES / "hushlogin": HOME / ".hushlogin",
DOTFILES / "claude/CLAUDE.md": HOME / ".claude/CLAUDE.md",
}.items():
symlink(src, target)
# nvim providers
with section("nvim providers"):
venv_base = HOME / ".local/share/venv"
venv_base.mkdir(parents=True, exist_ok=True)
venv_python = venv_base / "neovim-python"
if (venv_python / "bin/python").exists():
ok("python (pynvim)")
else:
r1 = subprocess.run(["uv", "venv", "--clear", str(venv_python)], capture_output=True)
r2 = subprocess.run(["uv", "pip", "install", "--python", str(venv_python / "bin/python"), "pynvim"], capture_output=True)
if r1.returncode == 0 and r2.returncode == 0:
ok("python (pynvim)")
else:
fail("python provider", "uv venv or pynvim install failed")
r = subprocess.run(["rv", "ruby", "find"], capture_output=True, text=True)
if r.returncode == 0:
ruby_bin = Path(r.stdout.strip()).parent
run("ruby (neovim gem)", str(ruby_bin / "gem"), "install", "neovim")
else:
fail("ruby provider", "rv ruby find failed (is a ruby installed via rv?)")
# nvim lsp
with section("nvim lsp"):
run("rubocop", "rv", "tool", "install", "rubocop")
run("ruby-lsp", "rv", "tool", "install", "ruby-lsp")
# uv tools (ruff etc.) come from the Brewfile's `uv` entries
# julia: @name resolves to <depot>/environments/<name> (depot set by
# JULIA_DEPOT_PATH in zshrc). nvim-lspconfig's julials looks for
# LanguageServer.jl in @nvim-lspconfig; Runic.jl (formatter) is run from
# @runic by conform.
run("julia LanguageServer", "julia", "--project=@nvim-lspconfig",
"-e", 'using Pkg; Pkg.add("LanguageServer")')
run("julia Runic", "julia", "--project=@runic", "-e", 'using Pkg; Pkg.add("Runic")')
# C# LSP for roslyn.nvim (the official MS Roslyn server; csharp-ls can't
# locate MSBuild on recent .NET SDKs). Azure feed is more current than nuget.org.
run("roslyn-language-server", "dotnet", "tool", "update", "--global",
"roslyn-language-server", "--prerelease", "--source",
"https://pkgs.dev.azure.com/azure-public/vside/_packaging/vs-impl/nuget/v3/index.json")
run("node", "volta", "install", "node")
for pkg in [
"bash-language-server",
"vscode-langservers-extracted",
"prettier",
"sql-formatter",
"svelte-language-server",
"@tailwindcss/language-server",
"@vtsls/language-server",
"yaml-language-server",
"@olrtg/emmet-language-server",
]:
run(pkg, "volta", "install", pkg)
# monogame (machine-global; run once, not per-project. the per-project content
# builder `dotnet-mgcb` comes from each project's tool manifest via `dotnet tool
# restore`. `mgcb-editor --register` is skipped: it's broken/unneeded on macOS.)
with section("monogame"):
run("monogame templates", "dotnet", "new", "install", "MonoGame.Templates.CSharp")
run("mgcb-editor", "dotnet", "tool", "update", "--global", "dotnet-mgcb-editor")
run("mgcb-editor-mac", "dotnet", "tool", "update", "--global", "dotnet-mgcb-editor-mac")
# launch agents (written, not symlinked: launchd wants a real file with absolute
# paths. rewritten and reloaded only when the plist content changes.)
LAUNCHD = f"gui/{os.getuid()}"
def agent_loaded(label):
return subprocess.run(["launchctl", "print", f"{LAUNCHD}/{label}"], capture_output=True).returncode == 0
def agent_bootout(label):
subprocess.run(["launchctl", "bootout", f"{LAUNCHD}/{label}"], capture_output=True)
# bootout returns before teardown finishes; bootstrapping too soon fails with EIO
for _ in range(50):
if not agent_loaded(label):
break
time.sleep(0.1)
def launch_agent(label, program, keep_alive=False, calendar=None, log=None, extra=None, enabled=True):
target = HOME / "Library/LaunchAgents" / f"{label}.plist"
if not enabled:
if agent_loaded(label):
agent_bootout(label)
target.unlink(missing_ok=True)
ok(f"{label} (disabled)")
return
log = log or HOME / "Library/Logs" / f"{label}.log"
plist = {
"Label": label,
"ProgramArguments": [str(a) for a in program],
"RunAtLoad": True,
"StandardOutPath": str(log),
"StandardErrorPath": str(log),
# launchd gives agents a bare environment; brew needs both of these
"EnvironmentVariables": {
"PATH": "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
"XDG_CONFIG_HOME": XDG_CONFIG_HOME,
},
}
if keep_alive:
plist["KeepAlive"] = True
plist["ThrottleInterval"] = 30
if calendar:
plist["StartCalendarInterval"] = calendar
plist.update(extra or {})
content = plistlib.dumps(plist)
changed = not target.exists() or target.read_bytes() != content
loaded = agent_loaded(label)
if not changed and loaded:
ok(label)
return
if loaded:
agent_bootout(label)
target.parent.mkdir(parents=True, exist_ok=True)
# unlink first so a symlinked plist is replaced, not written through
target.unlink(missing_ok=True)
target.write_bytes(content)
run(label, "launchctl", "bootstrap", LAUNCHD, str(target))
# hand-made agents superseded by the declarations below
def remove_legacy_agent(label):
# the original maxwell agent's label already ended in ".plist", matching its filename
target = HOME / "Library/LaunchAgents" / (label if label.endswith(".plist") else f"{label}.plist")
if not target.exists() and not agent_loaded(label):
return
if agent_loaded(label):
agent_bootout(label)
target.unlink(missing_ok=True)
ok(f"removed legacy agent {label}")
with section("launch agents"):
remove_legacy_agent("com.user.maxwell.plist") # original maxwell fix on patches; its label included ".plist"
launch_agent("ca.carper.maxwell-fix", [DOTFILES / "config/maxwell/keepalive.sh"], keep_alive=True)
launch_agent("ca.carper.llama-server", [DOTFILES / "config/llama.cpp/server.sh"], keep_alive=True)
if HOST == "patches":
launch_agent("ca.carper.allowance-backup", ["/bin/bash", HOME / "Backups/allowance-pull.sh"],
calendar=[{"Hour": 20, "Minute": 0}], log=HOME / "Backups/allowance-pull.log")
# hourly. StartInterval left launchd's spawn permanently "pended" (Sep 2026); calendar triggers are reliable
launch_agent("ca.carper.mc-backup", ["/bin/bash", HOME / "mc-backups/pull.sh"],
calendar=[{"Hour": h, "Minute": 17} for h in range(24)], log=HOME / "mc-backups/pull.log",
extra={"LowPriorityIO": True, "Nice": 5}, enabled=False)
# drift check
with section("homebrew drift"):
r = subprocess.run(
["brew", "bundle", "cleanup", f"--file={DOTFILES}/Brewfile"],
capture_output=True, text=True,
)
# the "Would `brew cleanup`" block is cache/old-version housekeeping, not drift
unlisted = r.stdout.split("Would `brew cleanup`")[0].strip()
if not unlisted:
ok("no unlisted packages")
else:
indented = "\n".join(f" {line}" for line in unlisted.splitlines())
fail("homebrew drift", f"packages not in Brewfile (run 'brew bundle cleanup --file={DOTFILES}/Brewfile --force' to remove):\n{indented}")
# report
if not errors:
print(f"{BLUE}* done{RESET}")
else:
print(f"{BLUE}* {len(errors)} issue(s):{RESET}")
for label, detail in errors:
print(f"\n{BLUE}{label}:{RESET}")
for line in detail.splitlines():
print(f"{RED} {line}{RESET}")
raise SystemExit(1)