-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathgobrew.go
393 lines (343 loc) · 10.6 KB
/
gobrew.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
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
package gobrew
import (
"fmt"
"io"
"io/fs"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/Masterminds/semver"
"github.com/gookit/color"
"github.com/kevincobain2000/gobrew/utils"
)
const (
goBrewDir string = ".gobrew"
DefaultRegistryPath string = "https://go.dev/dl/"
DownloadURL string = "https://github.com/kevincobain2000/gobrew/releases/latest/download/"
TagsAPI = "https://raw.githubusercontent.com/kevincobain2000/gobrew/json/golang-tags.json"
VersionsURL string = "https://api.github.com/repos/kevincobain2000/gobrew/releases/latest"
)
const (
NoneVersion = "None"
ProgramName = "gobrew"
)
// check GoBrew implement is Command interface
var _ Command = (*GoBrew)(nil)
// Command ...
type Command interface {
ListVersions()
ListRemoteVersions(bool) map[string][]string
CurrentVersion() string
Uninstall(version string)
Install(version string) string
Use(version string)
Prune()
Version(currentVersion string)
Upgrade(currentVersion string)
Interactive(ask bool)
}
// GoBrew struct
type GoBrew struct {
installDir string
versionsDir string
currentDir string
currentBinDir string
currentGoDir string
downloadsDir string
cacheFile string
Config
}
type Config struct {
RootDir string
RegistryPathURL string
GobrewDownloadURL string
GobrewTags string
GobrewVersionsURL string
// cache settings
TTL time.Duration
DisableCache bool
ClearCache bool
}
// NewGoBrew instance
func NewGoBrew(config Config) GoBrew {
installDir := filepath.Join(config.RootDir, goBrewDir)
cacheFile := filepath.Join(installDir, "cache.json")
gb := GoBrew{
Config: config,
installDir: installDir,
versionsDir: filepath.Join(installDir, "versions"),
currentDir: filepath.Join(installDir, "current"),
currentBinDir: filepath.Join(installDir, "current", "bin"),
currentGoDir: filepath.Join(installDir, "current", "go"),
downloadsDir: filepath.Join(installDir, "downloads"),
cacheFile: cacheFile,
}
if gb.ClearCache {
_ = os.RemoveAll(gb.cacheFile)
}
return gb
}
// Interactive used by default
func (gb *GoBrew) Interactive(ask bool) {
currentVersion := gb.CurrentVersion()
currentMajorVersion := extractMajorVersion(currentVersion)
latestVersion := gb.getLatestVersion()
latestMajorVersion := extractMajorVersion(latestVersion)
modVersion := NoneVersion
if gb.hasModFile() {
modVersion = gb.getModVersion()
modVersion = extractMajorVersion(modVersion)
}
fmt.Println()
if currentVersion == NoneVersion {
color.Warnln("🚨 Installed Version", ".......", currentVersion, "⚠️")
} else {
var labels []string
if modVersion != NoneVersion && currentMajorVersion != modVersion {
labels = append(labels, "🔄 not same as go.mod")
}
if currentVersion != latestVersion {
labels = append(labels, "⬆️ not latest")
}
label := ""
if len(labels) > 0 {
label = " " + color.FgRed.Render(label)
}
if currentVersion != latestVersion {
color.Successln("✅ Installed Version", ".......", currentVersion+label, "\t🌟", latestVersion, "available")
} else {
color.Successln("✅ Installed Version", ".......", currentVersion+label, "\t🎉", "on latest")
}
}
if modVersion != NoneVersion && latestMajorVersion != modVersion {
label := " " + color.FgYellow.Render("\t⚠️ not latest")
color.Successln("📄 go.mod Version", " .......", modVersion+label)
} else {
color.Successln("📄 go.mod Version", " .......", modVersion)
}
fmt.Println()
if currentVersion == NoneVersion {
color.Warnln("GO is not installed.")
c := true
if ask {
c = askForConfirmation("Do you want to use latest GO version (" + latestVersion + ")?")
}
if c {
gb.Use(latestVersion)
}
return
}
if modVersion != NoneVersion && currentMajorVersion != modVersion {
color.Warnf("⚠️ GO Installed Version (%s) and go.mod Version (%s) are different.\n", currentMajorVersion, modVersion)
fmt.Println(" Please consider updating your go.mod file")
c := true
if ask {
c = askForConfirmation("🤔 Do you want to use GO version same as go.mod version (" + modVersion + "@latest)?")
}
if c {
gb.Use(modVersion + "@latest")
}
return
}
if currentVersion != latestVersion {
color.Warnf("⚠️ GO Installed Version (%s) and GO Latest Version (%s) are different.\n", currentVersion, latestVersion)
c := true
if ask {
c = askForConfirmation("🤔 Do you want to update GO to latest version (" + latestVersion + ")?")
}
if c {
gb.Use(latestVersion)
}
return
}
}
// Prune removes all installed versions of go except current version
func (gb *GoBrew) Prune() {
currentVersion := gb.CurrentVersion()
color.Infoln("==> [Info] Current version:", currentVersion)
entries, err := os.ReadDir(gb.versionsDir)
utils.CheckError(err, "[Error]: List versions failed")
files := make([]fs.FileInfo, 0, len(entries))
for _, entry := range entries {
info, err := entry.Info()
utils.CheckError(err, "[Error]: List versions failed")
files = append(files, info)
}
for _, f := range files {
if f.Name() != currentVersion {
version := f.Name()
color.Infoln("==> [Info] Uninstalling version:", version)
gb.Uninstall(version)
}
}
}
// ListVersions that are installed by dir ls
// highlight the version that is currently symbolic linked
func (gb *GoBrew) ListVersions() {
entries, err := os.ReadDir(gb.versionsDir)
if err != nil && os.IsNotExist(err) {
color.Infoln("==> [Info] Nothing installed yet. Run `gobrew use latest` to install a latest version of Go.")
return
}
files := make([]fs.FileInfo, 0, len(entries))
for _, entry := range entries {
info, err := entry.Info()
utils.CheckError(err, "[Error]: List versions failed")
files = append(files, info)
}
cv := gb.CurrentVersion()
versionsSemantic := make([]*semver.Version, 0)
for _, f := range files {
if v, err := semver.NewVersion(f.Name()); err == nil {
versionsSemantic = append(versionsSemantic, v)
}
}
// sort semantic versions
sort.Sort(semver.Collection(versionsSemantic))
for _, versionSemantic := range versionsSemantic {
version := versionSemantic.String()
// 1.8.0 -> 1.8, if version < 1.21.0
reMajorVersion := regexp.MustCompile("([0-9]+).([0-9]+).0")
if len(reMajorVersion.FindStringSubmatch(version)) > 1 {
vv, _ := strconv.Atoi(reMajorVersion.FindStringSubmatch(version)[2])
if vv < 21 {
if reMajorVersion.MatchString(version) {
version = strings.Split(version, ".")[0] + "." + strings.Split(version, ".")[1]
}
}
}
if version == cv {
version = cv + "*"
color.Successln(version)
} else {
color.Infoln(version)
}
}
// print rc and beta versions in the end
for _, f := range files {
rcVersion := f.Name()
r := regexp.MustCompile("beta.*|rc.*")
matches := r.FindAllString(rcVersion, -1)
if len(matches) == 1 {
if rcVersion == cv {
rcVersion = cv + "*"
color.Successln(rcVersion)
} else {
color.Infoln(rcVersion)
}
}
}
if cv != "" {
color.Infoln()
color.Infoln("current:", cv)
}
}
// ListRemoteVersions that are installed by dir ls
func (gb *GoBrew) ListRemoteVersions(shouldPrint bool) map[string][]string {
if shouldPrint {
color.Infoln("==> [Info] Fetching remote versions")
}
tags := gb.getGolangVersions()
var versions []string
versions = append(versions, tags...)
return gb.getGroupedVersion(versions, shouldPrint)
}
// CurrentVersion get current version from symb link
func (gb *GoBrew) CurrentVersion() string {
fp, err := evalSymlinks(gb.currentBinDir)
if err != nil {
return NoneVersion
}
version := strings.TrimSuffix(fp, filepath.Join("go", "bin"))
version = filepath.Base(version)
if version == "." {
return NoneVersion
}
return version
}
// Uninstall the given version of go
func (gb *GoBrew) Uninstall(version string) {
if version == "" {
color.Errorln("[Error] No version provided")
os.Exit(1)
}
if gb.CurrentVersion() == version {
color.Errorf("[Error] Version: %s you are trying to remove is your current version. Please use a different version first before uninstalling the current version\n", version)
os.Exit(1)
}
gb.cleanVersionDir(version)
color.Successf("==> [Success] Version: %s uninstalled\n", version)
}
// Install the given version of go
func (gb *GoBrew) Install(version string) string {
if version == "" || version == NoneVersion {
color.Errorln("[Error] No version provided")
os.Exit(1)
}
version = gb.judgeVersion(version)
if version == NoneVersion {
color.Errorln("[Error] Version non exists")
os.Exit(1)
}
if gb.existsVersion(version) {
color.Infof("==> [Info] Version: %s exists\n", version)
return version
}
gb.mkDirs(version)
color.Infof("==> [Info] Downloading version: %s\n", version)
gb.downloadAndExtract(version)
gb.cleanDownloadsDir()
color.Successf("==> [Success] Downloaded version: %s\n", version)
return version
}
// Use a version
func (gb *GoBrew) Use(version string) {
version = gb.Install(version)
if gb.CurrentVersion() == version {
color.Infof("==> [Info] Version: %s is already your current version \n", version)
return
}
color.Infof("==> [Info] Changing go version to: %s \n", version)
gb.changeSymblinkGoBin(version)
gb.changeSymblinkGo(version)
color.Successf("==> [Success] Changed go version to: %s\n", version)
}
// Version of GoBrew
func (gb *GoBrew) Version(currentVersion string) {
color.Infoln("[INFO] gobrew version is", currentVersion)
}
// Upgrade of GoBrew
func (gb *GoBrew) Upgrade(currentVersion string) {
if "v"+currentVersion == gb.getGobrewVersion() {
color.Infoln("[INFO] your version is already newest")
return
}
mkdirTemp, _ := os.MkdirTemp("", ProgramName)
tmpFile := filepath.Join(mkdirTemp, ProgramName+fileExt)
downloadURL, _ := url.JoinPath(gb.GobrewDownloadURL, "gobrew-"+gb.getArch()+fileExt)
utils.CheckError(
utils.DownloadWithProgress(downloadURL, ProgramName+fileExt, mkdirTemp),
"[Error] Download GoBrew failed")
source, err := os.Open(tmpFile)
utils.CheckError(err, "[Error] Cannot open file")
defer func(source *os.File) {
_ = source.Close()
utils.CheckError(os.Remove(source.Name()), "==> [Error] Cannot remove tmp file:")
}(source)
goBrewFile := filepath.Join(gb.installDir, "bin", ProgramName+fileExt)
removeFile(goBrewFile)
destination, err := os.Create(goBrewFile)
utils.CheckError(err, "==> [Error] Cannot open file")
defer func(destination *os.File) {
_ = destination.Close()
}(destination)
_, err = io.Copy(destination, source)
utils.CheckError(err, "==> [Error] Cannot copy file")
utils.CheckError(os.Chmod(goBrewFile, 0755), "==> [Error] Cannot set file as executable")
color.Infoln("Upgrade successful")
}