-
Notifications
You must be signed in to change notification settings - Fork 0
/
switch.go
80 lines (66 loc) · 1.44 KB
/
switch.go
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
package main
import (
"os"
"path"
"strings"
"github.com/manifoldco/promptui"
"github.com/urfave/cli/v2"
)
func switchVersion(ctx *cli.Context) error {
home, err := os.UserHomeDir()
if err != nil {
return err
}
if err := createGovsDir(home); err != nil {
return err
}
sdkDir := getSDKDirPath(home)
installedVers, err := listInstalledVersions(sdkDir)
if err != nil {
return err
}
prompt := promptui.Select{
Label: "Choose a version",
Items: installedVers,
Templates: &promptui.SelectTemplates{
Help: "Golang Version Switcher",
},
}
_, result, err := prompt.Run()
if err != nil {
return err
}
goroot := path.Join(sdkDir, "go"+result)
if err := setGOROOT(home, goroot); err != nil {
return err
}
if err := setPATH(home, goroot); err != nil {
return err
}
return nil
}
func setGOROOT(home, goroot string) error {
if err := os.WriteFile(path.Join(home, ".govs", "goroot"), []byte(goroot), 0644); err != nil {
return err
}
return nil
}
func setPATH(home, goroot string) error {
gorootBin := path.Join(goroot, "bin")
pathEnv := os.Getenv("PATH")
pathMap := map[string]bool{}
for _, p := range strings.Split(pathEnv, ":") {
if p == gorootBin {
continue
}
pathMap[p] = true
}
keys := []string{}
for k := range pathMap {
keys = append(keys, k)
}
if err := os.WriteFile(path.Join(home, ".govs", "path"), []byte(gorootBin+":"+strings.Join(keys, ":")), 0644); err != nil {
return err
}
return nil
}