-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpost.go
More file actions
610 lines (558 loc) · 18.6 KB
/
Copy pathpost.go
File metadata and controls
610 lines (558 loc) · 18.6 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
package main
import (
"fmt"
"io"
"os"
"os/user"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// ── pyenv / Python ──────────────────────────────────────────────────────
func installPyenv() {
taskPrintln(" Installing pyenv via curl ...")
if !runShell("curl https://pyenv.run | bash", CmdOpts{Out: taskOut()}).OK() {
errLog("pyenv installation failed")
return
}
taskPrintln(" pyenv installed to ~/.pyenv")
}
func python3DecimalOK() bool {
if !hasCmd("python3") {
return false
}
r, ok := probe([]string{"python3", "-c", "from decimal import Decimal"}, 10*time.Second)
return ok && r.ExitCode == 0
}
func fixPython3Decimal() bool {
switch pkgMgr {
case "apt-get":
runCmd([]string{"apt-get", "install", "-y", "python3-full"}, CmdOpts{AsSudo: true})
case "dnf":
runCmd([]string{"dnf", "install", "-y", "python3-libs"}, CmdOpts{AsSudo: true})
case "pacman":
runCmd([]string{"pacman", "-S", "--noconfirm", "--needed", "python"}, CmdOpts{AsSudo: true})
}
return python3DecimalOK()
}
func installPip() {
out := taskOut()
if !hasCmd("python3") {
errLog("python3 is not installed — cannot install pip")
return
}
if !python3DecimalOK() {
warn("Python 3 _decimal C extension failed to import — attempting fix ...")
if fixPython3Decimal() {
taskPrintln(" Python 3 _decimal extension restored.")
} else {
errLog("Python 3 _decimal C extension could not be fixed. " +
"Run: sudo apt-get install python3-full (Debian/Ubuntu), " +
"sudo dnf install python3-libs (Fedora/RHEL), or " +
"sudo pacman -S python (Arch)")
return
}
}
taskPrintln(" Bootstrapping pip via 'python3 -m ensurepip --upgrade' ...")
bootstrap := runCmd([]string{"python3", "-m", "ensurepip", "--upgrade"}, CmdOpts{AsSudo: true, Out: out})
if !bootstrap.OK() {
switch pkgMgr {
case "apt-get":
warn("ensurepip unavailable in system Python — installing python3-pip via apt-get")
if !runCmd([]string{"apt-get", "install", "-y", "python3-pip"}, CmdOpts{AsSudo: true, Out: out}).OK() {
errLog("python3-pip failed to install via apt-get — skipping pip bootstrap")
return
}
case "pacman":
warn("ensurepip unavailable in system Python — installing python-pip via pacman")
if !runCmd([]string{"pacman", "-S", "--noconfirm", "--needed", "python-pip"}, CmdOpts{AsSudo: true, Out: out}).OK() {
errLog("python-pip failed to install via pacman — skipping pip bootstrap")
return
}
default:
errLog("python3 -m ensurepip failed (system Python may need a distro 'python3-pip' package)")
return
}
}
taskPrintln(" Upgrading pip to the latest version ...")
upgrade := runCmd([]string{"python3", "-m", "pip", "install", "--upgrade", "pip"}, CmdOpts{AsSudo: true, Out: out})
if !upgrade.OK() {
warn("pip self-upgrade failed (likely PEP 668 externally-managed); ensurepip-provided pip remains")
}
}
func latestStablePython(pyenvBin string) string {
r, ok := probe([]string{pyenvBin, "install", "--list"}, 2*time.Minute)
if !ok {
errLog("pyenv install --list failed")
return ""
}
if r.ExitCode != 0 {
errLog("pyenv install --list failed")
return ""
}
stableRe := regexp.MustCompile(`^\s*(\d+)\.(\d+)\.(\d+)\s*$`)
type ver struct{ a, b, c int }
var versions []ver
for _, line := range strings.Split(string(r.Stdout), "\n") {
m := stableRe.FindStringSubmatch(line)
if m == nil {
continue
}
a, _ := strconv.Atoi(m[1])
b, _ := strconv.Atoi(m[2])
c, _ := strconv.Atoi(m[3])
if a >= 3 {
versions = append(versions, ver{a, b, c})
}
}
if len(versions) == 0 {
return ""
}
sort.Slice(versions, func(i, j int) bool {
if versions[i].a != versions[j].a {
return versions[i].a < versions[j].a
}
if versions[i].b != versions[j].b {
return versions[i].b < versions[j].b
}
return versions[i].c < versions[j].c
})
v := versions[len(versions)-1]
return fmt.Sprintf("%d.%d.%d", v.a, v.b, v.c)
}
// ensurePythonLatest installs the latest stable Python via pyenv if not
// present, then sets it as global. Returns a wait group if an install was
// kicked off in the background; the caller must call .Wait() before exiting.
func ensurePythonLatest() *sync.WaitGroup {
home, _ := os.UserHomeDir()
pyenvDir := filepath.Join(home, ".pyenv")
if _, err := osStat(pyenvDir); err != nil {
return nil
}
pyenvBin := filepath.Join(pyenvDir, "bin", "pyenv")
if _, err := osStat(pyenvBin); err != nil {
warn(fmt.Sprintf("pyenv binary not found at %s", pyenvBin))
return nil
}
latest := latestStablePython(pyenvBin)
if latest == "" {
errLog("Could not determine latest stable Python from pyenv")
return nil
}
r, ok := probe([]string{pyenvBin, "versions", "--bare"}, 30*time.Second)
if !ok {
return nil
}
installed := strings.Fields(string(r.Stdout))
for _, v := range installed {
if v == latest {
fmt.Printf("\n[pyenv] Python %s already installed.\n", latest)
fmt.Printf("[pyenv] Setting Python %s as global default ...\n", latest)
if !runCmd([]string{pyenvBin, "global", latest}, CmdOpts{}).OK() {
errLog(fmt.Sprintf("pyenv global %s failed", latest))
}
return nil
}
}
fmt.Printf("\n[pyenv] Backgrounding install of Python %s (compile may take several minutes) ...\n", latest)
start := time.Now()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
r := runCmd([]string{pyenvBin, "install", "--skip-existing", latest},
CmdOpts{Timeout: 60 * time.Minute, Capture: true})
elapsed := int(time.Since(start).Seconds())
if !r.OK() {
errLog(fmt.Sprintf("pyenv install %s failed after %ds", latest, elapsed))
if len(r.Stderr) > 0 {
lines := strings.Split(string(r.Stderr), "\n")
if len(lines) > 20 {
lines = lines[len(lines)-20:]
}
fmt.Printf("\n[pyenv stderr tail]\n%s\n", strings.Join(lines, "\n"))
}
return
}
if !runCmd([]string{pyenvBin, "global", latest},
CmdOpts{Timeout: time.Minute}).OK() {
errLog(fmt.Sprintf("pyenv global %s failed", latest))
return
}
fmt.Printf("\n[pyenv] Python %s installed and set as global default (%ds).\n", latest, elapsed)
}()
return &wg
}
// ── nvm / Node ──────────────────────────────────────────────────────────
func installNVM() {
var rel ghRelease
if !fetchJSON("https://api.github.com/repos/nvm-sh/nvm/releases/latest", &rel) {
return
}
version := rel.TagName
if version == "" {
errLog("NVM tag_name missing")
return
}
installURL := fmt.Sprintf("https://raw.githubusercontent.com/nvm-sh/nvm/%s/install.sh", version)
taskPrintf(" Installing NVM %s via curl ...\n", version)
if !runShell(fmt.Sprintf("curl -o- %s | bash", installURL), CmdOpts{Out: taskOut()}).OK() {
errLog("NVM installation failed")
return
}
taskPrintf(" NVM %s installed to ~/.nvm\n", version)
}
func ensureNodeLTS() {
home, _ := os.UserHomeDir()
if _, err := osStat(filepath.Join(home, ".nvm")); err != nil {
return
}
check := runShell(`bash -c "source ~/.nvm/nvm.sh 2>/dev/null && nvm version lts/* 2>/dev/null"`,
CmdOpts{Capture: true})
installed := strings.TrimSpace(string(check.Stdout))
if installed != "" && installed != "N/A" {
fmt.Printf("\n[NVM] Node LTS (%s) already installed.\n", installed)
} else {
fmt.Println("\n[NVM] Installing Node.js LTS ...")
if !runShell(`bash -c "source ~/.nvm/nvm.sh && nvm install --lts"`, CmdOpts{}).OK() {
errLog("Node.js LTS install via nvm failed")
return
}
fmt.Println(" Node.js LTS installed.")
}
fmt.Println("[NVM] Setting Node LTS as default ...")
if !runShell(`bash -c "source ~/.nvm/nvm.sh && nvm alias default 'lts/*' && nvm use --lts"`, CmdOpts{}).OK() {
errLog("Setting nvm default to LTS failed")
}
fmt.Println("[NVM] Enabling corepack and installing latest pnpm ...")
if !runShell(`bash -c 'source ~/.nvm/nvm.sh && corepack enable && corepack prepare pnpm@latest --activate'`, CmdOpts{}).OK() {
errLog("Failed to enable corepack and prepare pnpm")
return
}
fmt.Println("[pnpm] Running pnpm setup to configure PATH ...")
if !runShell(`bash -c 'export SHELL=/bin/bash && source ~/.nvm/nvm.sh && pnpm setup'`, CmdOpts{}).OK() {
errLog("pnpm setup failed")
}
}
// ── oh-my-zsh ───────────────────────────────────────────────────────────
func installOhMyZsh() {
if !hasCmd("zsh") {
errLog("zsh is not installed — required by oh-my-zsh")
return
}
if !hasCmd("git") {
errLog("git is not installed — required by oh-my-zsh")
return
}
home, _ := os.UserHomeDir()
target := filepath.Join(home, ".oh-my-zsh")
if _, err := osStat(target); err == nil {
taskPrintf(" oh-my-zsh already present at %s; updating theme only\n", target)
} else {
taskPrintln(" Installing oh-my-zsh via the official installer ...")
installer := `sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended`
if !runShell(installer, CmdOpts{Out: taskOut()}).OK() {
errLog("oh-my-zsh installer failed")
return
}
}
zshrc := filepath.Join(home, ".zshrc")
data, err := osReadFile(zshrc)
if err != nil {
warn("~/.zshrc not present after oh-my-zsh install; cannot set theme")
return
}
text := string(data)
re := regexp.MustCompile(`(?m)^\s*ZSH_THEME=.*$`)
var newText string
if re.MatchString(text) {
newText = re.ReplaceAllString(text, `ZSH_THEME="gnzh"`)
} else {
newText = strings.TrimRight(text, "\n") + "\nZSH_THEME=\"gnzh\"\n"
}
if newText != text {
if err := osWriteFile(zshrc, []byte(newText), 0o644); err != nil {
errLog(fmt.Sprintf("could not write ~/.zshrc: %v", err))
return
}
taskPrintln(` Set ZSH_THEME="gnzh" in ~/.zshrc`)
} else {
taskPrintln(` ~/.zshrc already has ZSH_THEME="gnzh"`)
}
}
// ── default-shell + neovim config + gh auth ─────────────────────────────
func invokingUser() string {
if u := os.Getenv("SUDO_USER"); u != "" {
return u
}
if u, err := user.Current(); err == nil {
return u.Username
}
return ""
}
func ensureZshDefault() {
if !hasCmd("zsh") {
warn("zsh not installed — skipping default-shell change")
return
}
zshPath := "/bin/zsh"
if r, ok := probe([]string{"which", "zsh"}, 5*time.Second); ok && r.ExitCode == 0 {
if p := strings.TrimSpace(string(r.Stdout)); p != "" {
zshPath = p
}
}
username := invokingUser()
if username == "" {
warn("could not determine invoking user; skipping default-shell change")
return
}
u, err := user.Lookup(username)
if err != nil {
warn(fmt.Sprintf("user %s not found in passwd; skipping default-shell change", username))
return
}
current := userLoginShell(u.Uid)
if current == zshPath {
fmt.Printf("\n[zsh] %s's default shell is already %s.\n", username, zshPath)
return
}
family := "Debian-family"
if isRHELFamily {
family = "RHEL-family"
} else if isArchFamily {
family = "Arch-family"
} else if isMacOS {
family = "macOS"
}
fmt.Printf("\n[zsh] Setting default shell for %s to %s (%s) ...\n", username, zshPath, family)
var cmd []string
if isRHELFamily {
cmd = []string{"usermod", "-s", zshPath, username}
} else {
cmd = []string{"chsh", "-s", zshPath, username}
}
if !runCmd(cmd, CmdOpts{AsSudo: true}).OK() {
errLog(fmt.Sprintf("Failed to set default shell to zsh for %s", username))
} else {
fmt.Println("[zsh] Default shell updated. Log out and back in for it to take effect.")
}
}
// userLoginShell returns the login shell for uid by parsing /etc/passwd. On
// macOS the shell may be set by dscl; getent isn't available either, so we
// just read passwd directly which works on every supported platform.
func userLoginShell(uid string) string {
data, err := osReadFile(passwdPath)
if err != nil {
return ""
}
for _, line := range strings.Split(string(data), "\n") {
parts := strings.Split(line, ":")
if len(parts) < 7 {
continue
}
if parts[2] == uid {
return parts[6]
}
}
return ""
}
func isZshDefault() bool {
if !hasCmd("zsh") {
return false
}
zshPath := "/bin/zsh"
if r, ok := probe([]string{"which", "zsh"}, 5*time.Second); ok && r.ExitCode == 0 {
if p := strings.TrimSpace(string(r.Stdout)); p != "" {
zshPath = p
}
}
username := invokingUser()
if username == "" {
return false
}
u, err := user.Lookup(username)
if err != nil {
return false
}
current := userLoginShell(u.Uid)
return current == zshPath
}
func cloneNvimConfig() {
home, _ := os.UserHomeDir()
configDir := filepath.Join(home, ".config", "nvim")
const sshURL = "git@github.com:JMR-dev/nvim-config.git"
const httpsURL = "https://github.com/JMR-dev/nvim-config.git"
fmt.Printf("\n[Neovim] Setting up configuration from %s ...\n", sshURL)
if _, err := osStat(configDir); err == nil {
n := 1
var backup string
for {
backup = filepath.Join(filepath.Dir(configDir), fmt.Sprintf("nvim-%d", n))
if _, err := osStat(backup); os.IsNotExist(err) {
break
}
n++
}
fmt.Printf(" Renaming existing %s → %s ...\n", configDir, backup)
if err := osRename(configDir, backup); err != nil {
errLog(fmt.Sprintf("could not back up existing nvim config: %v", err))
return
}
notice(fmt.Sprintf("Previous Neovim config preserved at %s", backup))
}
osMkdirAll(filepath.Dir(configDir), 0o755)
repoName := strings.TrimSuffix(filepath.Base(sshURL), ".git")
tempClone := filepath.Join(filepath.Dir(configDir), repoName)
osRemoveAll(tempClone)
fmt.Printf(" Cloning to %s ...\n", configDir)
if !runCmd([]string{"git", "clone", sshURL, tempClone}, CmdOpts{}).OK() {
fmt.Printf(" SSH clone failed; falling back to HTTPS (%s) ...\n", httpsURL)
osRemoveAll(tempClone)
if !runCmd([]string{"git", "clone", httpsURL, tempClone}, CmdOpts{}).OK() {
errLog("Neovim configuration clone failed")
return
}
}
if tempClone != configDir {
fmt.Printf(" Renaming %s to %s ...\n", filepath.Base(tempClone), filepath.Base(configDir))
osRename(tempClone, configDir)
}
fmt.Printf(" Neovim configuration ready at %s\n", configDir)
}
func ghLoggedIn() bool {
r, ok := probe([]string{"gh", "auth", "status"}, 30*time.Second)
return ok && r.ExitCode == 0
}
func checkAndSetupSSH() {
if !hasCmd("gh") {
fmt.Println("\n[GitHub CLI] gh not installed — skipping authentication.")
return
}
if ghLoggedIn() {
fmt.Println("\n[GitHub CLI] Already authenticated.")
return
}
if !askYN("\n[GitHub CLI] Would you like to authenticate the GitHub CLI? [y/N] ") {
return
}
res := runCmd([]string{"gh", "auth", "login"}, CmdOpts{Timeout: 15 * time.Minute})
if !res.OK() {
errLog("gh auth login failed — skipping key upload.")
return
}
}
// askYN prompts on stdin. Returns true only for an exact "y" (case-insensitive).
func askYN(prompt string) bool {
fmt.Print(prompt)
var buf [256]byte
n, err := stdin.Read(buf[:])
if err != nil && err != io.EOF {
fmt.Println()
return false
}
answer := strings.ToLower(strings.TrimSpace(string(buf[:n])))
return answer == "y"
}
func installAgy() {
taskPrintln(" Installing agy via curl ...")
if !runShell("curl -fsSL https://antigravity.google/cli/install.sh | bash", CmdOpts{Out: taskOut()}).OK() {
errLog("agy installation failed")
}
}
func pnpmEnvPrefix() string {
if isMacOS {
return `export PNPM_HOME="$HOME/Library/pnpm"; export PATH="$PNPM_HOME/bin:$PNPM_HOME:$PATH"; `
}
return `export PNPM_HOME="${XDG_DATA_HOME:-$HOME/.local/share}/pnpm"; export PATH="$PNPM_HOME/bin:$PNPM_HOME:$PATH"; `
}
func installNpmPackage(pkgName string) {
home, _ := os.UserHomeDir()
if _, err := osStat(filepath.Join(home, ".nvm")); err != nil {
errLog("NVM is not installed — cannot install " + pkgName)
return
}
ensureNodeLTS()
taskPrintf(" Installing %s via pnpm ...\n", pkgName)
cmd := fmt.Sprintf(`bash -c '%ssource ~/.nvm/nvm.sh && pnpm add -g %s'`, pnpmEnvPrefix(), pkgName)
if !runShell(cmd, CmdOpts{Out: taskOut()}).OK() {
errLog(fmt.Sprintf("%s installation failed", pkgName))
}
}
// installPlaywrightBrowsers runs `pnpx playwright install` (with --with-deps
// on apt-get). Separated from the npm-side install so that installNpmToolsBatch
// can do all `pnpm add -g` work in one call and then just provision browsers
// once if playwright was in the batch.
func installPlaywrightBrowsers() {
installCmd := "pnpx playwright install"
if pkgMgr == "apt-get" {
fmt.Println(" Installing Playwright browsers with dependencies ...")
installCmd += " --with-deps"
} else {
fmt.Println(" Installing Playwright browsers ...")
}
if !runShell(fmt.Sprintf(`bash -c '%ssource ~/.nvm/nvm.sh && %s'`, pnpmEnvPrefix(), installCmd), CmdOpts{}).OK() {
errLog("playwright browser installation failed")
}
}
func installPlaywright() {
home, _ := os.UserHomeDir()
if _, err := osStat(filepath.Join(home, ".nvm")); err != nil {
errLog("NVM is not installed — cannot install playwright")
return
}
ensureNodeLTS()
taskPrintln(" Installing playwright via pnpm ...")
addCmd := fmt.Sprintf(`bash -c '%ssource ~/.nvm/nvm.sh && pnpm add -g playwright'`, pnpmEnvPrefix())
if !runShell(addCmd, CmdOpts{Out: taskOut()}).OK() {
errLog("playwright installation failed")
return
}
installPlaywrightBrowsers()
}
func installGHExtension(repo string) {
if !hasCmd("gh") {
errLog("gh CLI is not installed — cannot install extension " + repo)
return
}
taskPrintf(" Installing gh extension %s ...\n", repo)
if !runCmd([]string{"gh", "extension", "install", repo}, CmdOpts{Out: taskOut()}).OK() {
errLog(fmt.Sprintf("gh extension install %s failed", repo))
}
}
// ── LibreOffice AutoSave Extension ──────────────────────────────────────
func ensureLibreOfficeAutoSave() {
var unopkgPath string
if isMacOS {
unopkgPath = "/Applications/LibreOffice.app/Contents/MacOS/unopkg"
if _, err := osStat(unopkgPath); err != nil {
return
}
} else {
if !hasCmd("unopkg") {
return
}
unopkgPath = "unopkg"
}
fmt.Println("\n[LibreOffice] LibreOffice detected. Installing AutoSave extension ...")
tmp, err := os.MkdirTemp("", "libreoffice-autosave-")
if err != nil {
errLog(fmt.Sprintf("LibreOffice AutoSave temp dir failed: %v", err))
return
}
defer osRemoveAll(tmp)
url := "https://github.com/JMR-dev/LibreOfficeAutoSave/releases/latest/download/AutoSave.oxt"
dest := filepath.Join(tmp, "AutoSave.oxt")
if !download(url, dest) {
errLog("Failed to download LibreOffice AutoSave extension")
return
}
if !runCmd([]string{unopkgPath, "add", "-f", dest}, CmdOpts{}).OK() {
errLog("Failed to install LibreOffice AutoSave extension")
return
}
fmt.Println(" LibreOffice AutoSave extension installed successfully.")
}