-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathmain.go
More file actions
659 lines (574 loc) · 17.8 KB
/
Copy pathmain.go
File metadata and controls
659 lines (574 loc) · 17.8 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
package main
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"github.com/go-nv/goenv/internal/migration"
"github.com/go-nv/goenv/internal/platform"
"github.com/go-nv/goenv/internal/utils"
)
// Colors
const (
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[1;33m"
blue = "\033[0;34m"
nc = "\033[0m"
)
var (
scriptDir string
goBinary string
backupDir string
goenvPath string
useColor = true
dryRun bool
updateAll bool
interactive = true
)
func init() {
// Disable colors if not a TTY
if !isatty() {
useColor = false
}
// For `go run`, use the source file location
// For built binary, use the executable location
_, sourceFile, _, _ := runtime.Caller(0)
scriptDir = filepath.Dir(sourceFile) // This gives us scripts/swap directory
// Find repo root (go up from scripts/swap to repo root)
repoRoot := filepath.Dir(filepath.Dir(scriptDir)) // Go up 2 levels
goBinary = filepath.Join(repoRoot, "goenv")
if platform.IsWindows() {
goBinary += ".exe"
}
homeDir, _ := os.UserHomeDir()
backupDir = filepath.Join(homeDir, ".goenv_backup")
}
func isatty() bool {
fileInfo, _ := os.Stdout.Stat()
return (fileInfo.Mode() & os.ModeCharDevice) != 0
}
func log(msg string) {
if useColor {
fmt.Printf("%s→%s %s\n", blue, nc, msg)
} else {
fmt.Printf("→ %s\n", msg)
}
}
func success(msg string) {
if useColor {
fmt.Printf("%s✓%s %s\n", green, nc, msg)
} else {
fmt.Printf("✓ %s\n", msg)
}
}
func warn(msg string) {
if useColor {
fmt.Printf("%s⚠%s %s\n", yellow, nc, msg)
} else {
fmt.Printf("⚠ %s\n", msg)
}
}
func errorExit(msg string) {
if useColor {
fmt.Printf("%s✗%s %s\n", red, nc, msg)
} else {
fmt.Printf("✗ %s\n", msg)
}
os.Exit(1)
}
func detectGoenv() (string, error) {
installations := detectAllGoenv()
if len(installations) == 0 {
return "", fmt.Errorf("goenv not found")
}
return installations[0], nil
}
func detectAllGoenv() []string {
var found []string
seen := make(map[string]bool)
// Method 1: Check PATH
if path, err := exec.LookPath("goenv"); err == nil {
// Resolve symlinks to get actual file
resolved := path
if r, err := filepath.EvalSymlinks(path); err == nil {
resolved = r
}
if !seen[resolved] {
found = append(found, resolved)
seen[resolved] = true
}
}
// Build list of common locations to check
homeDir, _ := os.UserHomeDir()
locations := []string{}
// Method 2: Homebrew locations
if platform.IsMacOS() || platform.IsLinux() {
locations = append(locations,
"/opt/homebrew/bin/goenv", // ARM Mac
"/usr/local/bin/goenv", // Intel Mac / Linux Homebrew
"/home/linuxbrew/.linuxbrew/bin/goenv", // Linux Homebrew
)
}
// Method 3: Manual installation
locations = append(locations, filepath.Join(homeDir, ".goenv", "bin", "goenv"))
// Method 4: System locations (Unix)
if !platform.IsWindows() {
locations = append(locations,
"/usr/bin/goenv",
"/usr/local/bin/goenv",
"/opt/goenv/bin/goenv",
)
}
// Method 5: Windows locations
if platform.IsWindows() {
locations = append(locations,
filepath.Join(homeDir, "bin", "goenv.exe"),
filepath.Join(homeDir, ".goenv", "bin", "goenv.exe"),
"C:\\Program Files\\goenv\\goenv.exe",
"C:\\goenv\\bin\\goenv.exe",
)
// Check scoop
if scoopPath := os.Getenv("SCOOP"); scoopPath != "" {
locations = append(locations, filepath.Join(scoopPath, "shims", "goenv.exe"))
}
// Check chocolatey
if programData := os.Getenv("ProgramData"); programData != "" {
locations = append(locations, filepath.Join(programData, "chocolatey", "bin", "goenv.exe"))
}
}
// Check all locations
for _, loc := range locations {
if utils.FileExists(loc) {
// Resolve symlinks
resolved := loc
if r, err := filepath.EvalSymlinks(loc); err == nil {
resolved = r
}
if !seen[resolved] {
found = append(found, resolved)
seen[resolved] = true
}
}
}
return found
}
func detectShellOverrides() []string {
var warnings []string
// Check for shell function/alias (bash)
shells := []string{"bash", "zsh"}
for _, shell := range shells {
if _, err := exec.LookPath(shell); err == nil {
if output, err := utils.RunCommandOutput(shell, "-c", "type -t goenv 2>/dev/null"); err == nil {
if output == "function\n" {
warnings = append(warnings, fmt.Sprintf("Shell function 'goenv' detected in %s", shell))
} else if output == "alias\n" {
warnings = append(warnings, fmt.Sprintf("Shell alias 'goenv' detected in %s", shell))
}
}
}
}
return warnings
}
func checkGoenv() {
var err error
goenvPath, err = detectGoenv()
if err != nil {
errorExit(`goenv not found. Please install goenv first.
Options:
- Homebrew: brew install goenv
- Manual: git clone https://github.com/go-nv/goenv ~/.goenv
- Package mgr: apt/yum/pkg install goenv`)
}
log(fmt.Sprintf("Found goenv: %s", goenvPath))
}
func cmdBuild() {
log("Building Go version...")
// Check if Go is installed
if _, err := exec.LookPath("go"); err != nil {
errorExit(`Go compiler not found. Please install Go first:
- macOS: brew install go
- Linux: apt install golang / yum install golang
- Manual: https://golang.org/dl/`)
}
// Find repo root (where Makefile is located)
repoRoot := scriptDir
for i := 0; i < 3; i++ { // Go up max 3 levels
makefilePath := filepath.Join(repoRoot, "Makefile")
if utils.PathExists(makefilePath) {
break
}
repoRoot = filepath.Dir(repoRoot)
}
log(fmt.Sprintf("Running: make build (in %s)", repoRoot))
if err := utils.RunCommandWithIOInDir(repoRoot, "make", []string{"build"}, os.Stdout, os.Stderr); err != nil {
errorExit("Build failed")
}
if utils.FileNotExists(goBinary) {
errorExit(fmt.Sprintf("Build completed but binary not found: %s", goBinary))
}
success(fmt.Sprintf("Built: %s", goBinary))
// Show version
_ = utils.RunCommandWithIO(goBinary, []string{"--version"}, os.Stdout, nil)
}
func cmdStatus() {
fmt.Println("═══════════════════════════════════════")
fmt.Println(" goenv Status")
fmt.Println("═══════════════════════════════════════")
log(fmt.Sprintf("System: %s %s", platform.OS(), platform.Arch()))
fmt.Println()
installations := detectAllGoenv()
if len(installations) == 0 {
warn("goenv not found in PATH or common locations")
} else if len(installations) == 1 {
log(fmt.Sprintf("goenv location: %s", installations[0]))
showGoenvInfo(installations[0])
} else {
warn(fmt.Sprintf("Found %d goenv installations:", len(installations)))
for i, path := range installations {
fmt.Printf("\n %d. %s\n", i+1, path)
showGoenvInfo(path)
}
fmt.Println()
warn("Multiple installations may cause conflicts!")
warn("Use 'goenv doctor' to check for issues")
}
// Check for shell overrides
if overrides := detectShellOverrides(); len(overrides) > 0 {
fmt.Println()
for _, override := range overrides {
warn(override)
}
}
fmt.Println()
log(fmt.Sprintf("Go binary: %s", goBinary))
if utils.PathExists(goBinary) {
size := utils.GetFileSize(goBinary)
success(fmt.Sprintf("Exists (size: %d bytes)", size))
} else {
warn("Not built yet (run: swap build)")
}
fmt.Println()
log(fmt.Sprintf("Backup: %s", backupDir))
backupFile := filepath.Join(backupDir, "goenv.bash")
if utils.PathExists(backupFile) {
success("Exists")
} else {
warn("No backup (will create on first swap)")
}
fmt.Println("═══════════════════════════════════════")
}
func showGoenvInfo(path string) {
if utils.PathExists(path) {
// Check if it's a binary or script
if utils.IsExecutableFile(path) {
// Read first bytes to determine type
f, err := os.Open(path)
if err == nil {
buf := make([]byte, 4)
f.Read(buf)
f.Close()
// Check for ELF (Linux) or Mach-O (macOS) magic numbers
if buf[0] == 0x7f && buf[1] == 0x45 && buf[2] == 0x4c && buf[3] == 0x46 {
fmt.Printf(" Type: Go version (ELF binary)\n")
} else if buf[0] == 0xcf && buf[1] == 0xfa {
fmt.Printf(" Type: Go version (Mach-O binary)\n")
} else if buf[0] == 0x4d && buf[1] == 0x5a {
fmt.Printf(" Type: Go version (PE binary)\n")
} else if buf[0] == '#' && buf[1] == '!' {
fmt.Printf(" Type: Bash version (script)\n")
} else {
fmt.Printf(" Type: Unknown\n")
}
}
}
// Show version
if output, err := utils.RunCommandOutput(path, "--version"); err == nil {
fmt.Printf(" Version: %s", output)
}
}
}
func cmdGo() {
log("Switching to Go version...")
installations := detectAllGoenv()
if len(installations) == 0 {
errorExit(`goenv not found. Please install goenv first.
Options:
- Homebrew: brew install goenv
- Manual: git clone https://github.com/go-nv/goenv ~/.goenv
- Package mgr: apt/yum/pkg install goenv`)
}
// Check if Go binary exists
if utils.FileNotExists(goBinary) {
warn("Go binary not built. Building now...")
cmdBuild()
}
// Determine which installations to update
var targets []string
if updateAll {
targets = installations
log(fmt.Sprintf("Updating all %d installations...", len(installations)))
} else if len(installations) > 1 && interactive && !dryRun {
// Interactive selection
fmt.Println()
warn(fmt.Sprintf("Found %d goenv installations:", len(installations)))
for i, path := range installations {
fmt.Printf(" %d. %s\n", i+1, path)
}
fmt.Println()
fmt.Print("Which installation do you want to update? [1, or 'all']: ")
var choice string
fmt.Scanln(&choice)
if choice == "all" || choice == "a" {
targets = installations
} else if choice == "" || choice == "1" {
targets = []string{installations[0]}
} else {
// Parse number
var num int
fmt.Sscanf(choice, "%d", &num)
if num > 0 && num <= len(installations) {
targets = []string{installations[num-1]}
} else {
errorExit("Invalid selection")
}
}
} else {
targets = []string{installations[0]}
}
// Update each target
for _, target := range targets {
fmt.Println()
log(fmt.Sprintf("Updating: %s", target))
if dryRun {
success(fmt.Sprintf("[DRY RUN] Would update: %s", target))
continue
}
swapGoenvBinary(target)
}
// Remove stale goenv shim from v2 that may shadow the new binary.
// Uses helper function to handle both forward and backslash paths.
goenvRoot := os.Getenv("GOENV_ROOT")
if goenvRoot == "" {
homeDir, _ := os.UserHomeDir()
goenvRoot = filepath.Join(homeDir, ".goenv")
}
shimsDir := filepath.Join(goenvRoot, "shims")
if removed, err := migration.RemoveStaleV2Shim(shimsDir); err != nil {
warn(err.Error())
} else if removed {
success("Removed stale v2 goenv shim from " + filepath.Join(shimsDir, "goenv"))
}
fmt.Println()
success("Switch successful!")
warn("IMPORTANT: Reload your shell before testing:")
if runtime.GOOS != "windows" {
fmt.Println(" hash -r")
fmt.Println(" # OR restart your terminal")
} else {
fmt.Println(" Restart your terminal or PowerShell session")
}
fmt.Println()
warn("To test: goenv --version")
warn("If it hangs, swap back with: ./swap bash")
}
func swapGoenvBinary(target string) {
// Create backup if it doesn't exist
backupFile := filepath.Join(backupDir, filepath.Base(target)+".bash")
if utils.FileNotExists(backupFile) {
log("Creating backup...")
utils.EnsureDir(backupDir)
src, err := os.Open(target)
if err != nil {
errorExit(fmt.Sprintf("Cannot read goenv: %v", err))
}
defer src.Close()
dst, err := os.Create(backupFile)
if err != nil {
errorExit(fmt.Sprintf("Cannot create backup: %v", err))
}
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
errorExit(fmt.Sprintf("Backup failed: %v", err))
}
success(fmt.Sprintf("Backed up: %s", backupFile))
}
// Copy Go binary to goenv location
log("Replacing with Go version...")
src, err := os.Open(goBinary)
if err != nil {
errorExit(fmt.Sprintf("Cannot read Go binary: %v", err))
}
defer src.Close()
dst, err := os.Create(target)
if err != nil {
// Try with sudo if regular copy fails (Unix only)
if !platform.IsWindows() {
log("Regular copy failed, trying with sudo...")
if err := utils.RunCommand("sudo", "cp", goBinary, target); err == nil {
success(fmt.Sprintf("Copied: %s → %s (with sudo)", goBinary, target))
} else {
errorExit(fmt.Sprintf("Cannot copy to %s\n\nTry manually:\n sudo cp %s %s", target, goBinary, target))
}
} else {
errorExit(fmt.Sprintf("Cannot write to %s: %v", target, err))
}
} else {
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
errorExit(fmt.Sprintf("Copy failed: %v", err))
}
dst.Chmod(utils.PermFileExecutable)
success(fmt.Sprintf("Copied: %s → %s", goBinary, target))
// Make executable (Unix only - Windows uses file extension)
if !platform.IsWindows() {
if err := os.Chmod(target, utils.PermFileExecutable); err != nil {
warn(fmt.Sprintf("Could not set executable permission: %v", err))
}
}
}
// Verify file was copied
if utils.PathExists(target) {
size := utils.GetFileSize(target)
success(fmt.Sprintf("Binary installed (%d bytes)", size))
} else {
errorExit("Verification failed: file not found")
}
}
func cmdBash() {
log("Switching back to bash version...")
checkGoenv()
backupFile := filepath.Join(backupDir, "goenv.bash")
// Check if backup exists
if utils.FileNotExists(backupFile) {
warn("No backup found.")
// Try reinstalling from package manager
if platform.IsMacOS() {
if _, err := exec.LookPath("brew"); err == nil {
log("Reinstalling from Homebrew...")
if err := utils.RunCommandWithIO("brew", []string{"reinstall", "goenv"}, os.Stdout, os.Stderr); err == nil {
success("Reinstalled from Homebrew")
return
}
}
}
errorExit("Cannot restore: No backup found")
}
// Restore from backup
log("Restoring from backup...")
src, err := os.Open(backupFile)
if err != nil {
errorExit(fmt.Sprintf("Cannot read backup: %v", err))
}
defer src.Close()
dst, err := os.Create(goenvPath)
if err != nil {
// Try with sudo
if !platform.IsWindows() {
log("Regular copy failed, trying with sudo...")
if err := utils.RunCommand("sudo", "cp", backupFile, goenvPath); err == nil {
success(fmt.Sprintf("Restored: %s → %s (with sudo)", backupFile, goenvPath))
} else {
errorExit(fmt.Sprintf("Cannot restore to %s", goenvPath))
}
} else {
errorExit(fmt.Sprintf("Cannot write to %s: %v", goenvPath, err))
}
} else {
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
errorExit(fmt.Sprintf("Restore failed: %v", err))
}
dst.Chmod(utils.PermFileExecutable)
success(fmt.Sprintf("Restored: %s → %s", backupFile, goenvPath))
}
success("Switch successful!")
if runtime.GOOS != "windows" {
warn("Reload your shell: hash -r (or restart terminal)")
} else {
warn("Reload your shell: restart terminal or PowerShell session")
}
}
func printUsage() {
fmt.Println("Usage: swap {build|go|bash|status} [flags]")
fmt.Println()
fmt.Println("Commands:")
fmt.Println(" build - Build the Go version")
fmt.Println(" go - Switch to Go version")
fmt.Println(" bash - Switch back to bash version")
fmt.Println(" status - Show current version and status")
fmt.Println()
fmt.Println("Flags:")
fmt.Println(" --all Update all goenv installations (use with 'go')")
fmt.Println(" --dry-run Show what would be done without actually doing it")
fmt.Println(" --yes Non-interactive mode, use default selection")
fmt.Println()
fmt.Println("Cross-platform: Works on macOS, Linux, BSD, WSL, Windows")
fmt.Println()
fmt.Println("Examples:")
fmt.Println(" swap build # Build Go version first")
fmt.Println(" swap status # Check current version")
fmt.Println(" swap go # Switch to Go version (interactive)")
fmt.Println(" swap go --all # Update all installations")
fmt.Println(" swap go --dry-run # Preview changes without applying")
fmt.Println(" swap go --yes # Non-interactive, update first found")
fmt.Println(" swap bash # Switch back to bash version")
}
func main() {
if len(os.Args) < 2 {
printUsage()
os.Exit(1)
}
// Parse flags
cmd := os.Args[1]
for i := 2; i < len(os.Args); i++ {
switch os.Args[i] {
case "--all", "-a":
updateAll = true
case "--dry-run", "-n":
dryRun = true
case "--yes", "-y":
interactive = false
case "--help", "-h":
printUsage()
os.Exit(0)
default:
errorExit(fmt.Sprintf("Unknown flag: %s", os.Args[i]))
}
}
switch cmd {
case "build":
cmdBuild()
case "go":
if useColor {
fmt.Printf("%s╔═══════════════════════════════════════════╗%s\n", green, nc)
fmt.Printf("%s║ Switching to Go version of goenv ║%s\n", green, nc)
fmt.Printf("%s╚═══════════════════════════════════════════╝%s\n", green, nc)
} else {
fmt.Println("Switching to Go version of goenv")
}
fmt.Println()
if dryRun {
log("[DRY RUN MODE] - No changes will be made")
fmt.Println()
}
cmdGo()
case "bash":
if useColor {
fmt.Printf("%s╔═══════════════════════════════════════════╗%s\n", yellow, nc)
fmt.Printf("%s║ Switching to Bash version of goenv ║%s\n", yellow, nc)
fmt.Printf("%s╚═══════════════════════════════════════════╝%s\n", yellow, nc)
} else {
fmt.Println("Switching to Bash version of goenv")
}
fmt.Println()
cmdBash()
case "status":
cmdStatus()
default:
printUsage()
os.Exit(1)
}
}