-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathgoutil.go
409 lines (367 loc) · 10.6 KB
/
goutil.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package goutil
import (
"bytes"
"debug/buildinfo"
"fmt"
"go/build"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/fatih/color"
"github.com/hashicorp/go-version"
"github.com/nao1215/gorky/file"
"github.com/nao1215/gup/internal/print"
"github.com/pkg/errors"
)
// Internal variables to mock/monkey-patch behaviors in tests.
var (
// goExe is the executable name for the go command.
goExe = "go"
// keyGoBin is the key name of the env variable for "GOBIN".
keyGoBin = "GOBIN"
// keyGoPath is the key name of the env variable for "GOPATH".
keyGoPath = "GOPATH"
// osMkdirTemp is a copy of os.MkdirTemp to ease testing.
osMkdirTemp = os.MkdirTemp
)
// GoPaths has $GOBIN and $GOPATH
type GoPaths struct {
// GOBIN is $GOBIN
GOBIN string
// GOPATH is $GOPATH
GOPATH string
// TmpPath is tmporary path for dry run
TmpPath string
}
// Package is package information
type Package struct {
// Name is package name
Name string
// ImportPath is import path for 'go install'
ImportPath string
// ModulePath is path where go.mod is stored
ModulePath string
// Version store Package version (current and latest).
Version *Version
// GoVersion stores version of Go toolchain
GoVersion *Version
}
// Version is package version information.
type Version struct {
// Current(before update) version
Current string
// Latest(after update) version
Latest string
}
// NewVersion return Version instance.
func NewVersion() *Version {
return &Version{
Current: "",
Latest: "",
}
}
// SetLatestVer set package latest version.
func (p *Package) SetLatestVer() {
p.Version.Latest = GetPackageVersion(p.Name)
}
// CurrentToLatestStr returns string about the current version and the latest version
func (p *Package) CurrentToLatestStr() string {
if p.IsAlreadyUpToDate() {
return "Already up-to-date: " + color.GreenString(p.Version.Latest) + " / " + color.GreenString(p.GoVersion.Current)
}
var ret string
if p.Version.Current != p.Version.Latest {
ret += color.GreenString(p.Version.Current) + " to " + color.YellowString(p.Version.Latest)
}
if p.GoVersion.Current != p.GoVersion.Latest {
if len(ret) != 0 {
ret += ", "
}
ret += color.GreenString(p.GoVersion.Current) + " to " + color.YellowString(p.GoVersion.Latest)
}
return ret
}
// VersionCheckResultStr returns string about command version check.
func (p *Package) VersionCheckResultStr() string {
if p.IsAlreadyUpToDate() {
return "Already up-to-date: " + color.GreenString(p.Version.Latest) + " / " + color.GreenString(p.GoVersion.Current)
}
var ret string
// TODO: yellow only if latest > current
if p.Version.Current == p.Version.Latest {
ret += color.GreenString(p.Version.Current)
} else {
ret += "current: " + color.GreenString(p.Version.Current) + ", latest: "
if versionUpToDate(p.Version.Current, p.Version.Latest) {
ret += color.GreenString(p.Version.Latest)
} else {
ret += color.YellowString(p.Version.Latest)
}
}
ret += " / "
if p.GoVersion.Current == p.GoVersion.Latest {
ret += color.GreenString(p.GoVersion.Current)
} else {
ret += "current: " + color.GreenString(p.GoVersion.Current) + ", installed: "
if versionUpToDate(p.GoVersion.Current, p.GoVersion.Latest) {
ret += color.GreenString(p.GoVersion.Latest)
} else {
ret += color.YellowString(p.GoVersion.Latest)
}
}
return ret
}
// IsAlreadyUpToDate return whether binary is already up to date or not.
func (p *Package) IsAlreadyUpToDate() bool {
if p.Version.Current == p.Version.Latest && p.GoVersion.Current == p.GoVersion.Latest {
return true
}
return versionUpToDate(
strings.TrimLeft(p.Version.Current, "v"),
strings.TrimLeft(p.Version.Latest, "v"),
) && versionUpToDate(
strings.TrimLeft(p.GoVersion.Current, "go"),
strings.TrimLeft(p.GoVersion.Latest, "go"),
)
}
// versionUpToDate return whether current version is up to date or not.
func versionUpToDate(current, available string) bool {
if current == "unknown" || available == "unknown" {
return false // unknown version is not up to date
}
currentVer, err := version.NewVersion(current)
if err != nil {
return false // invalid version is not up to date
}
availableVer, err := version.NewVersion(available)
if err != nil {
return false // invalid version is not up to date
}
if currentVer.GreaterThanOrEqual(availableVer) {
return true
}
return false
}
// NewGoPaths return GoPaths instance.
func NewGoPaths() *GoPaths {
return &GoPaths{
GOBIN: goBin(),
GOPATH: goPath(),
}
}
// StartDryRunMode change the GOBIN or GOPATH settings to install the binaries in the temporary directory.
func (gp *GoPaths) StartDryRunMode() error {
tmpDir, err := osMkdirTemp("", "")
if err != nil {
return err
}
if gp.GOBIN != "" {
if err := os.Setenv(keyGoBin, tmpDir); err != nil {
// Wrap error to avoid OS dependent error message during testing.
return errors.Wrapf(
err,
"failed to set GOBIN to env variable. key: %v, value: %v",
keyGoBin, tmpDir,
)
}
} else if gp.GOPATH != "" {
if err := os.Setenv(keyGoPath, tmpDir); err != nil {
return errors.Wrapf(
err,
"failed to set GOPATH to env variable. key: %v, value: %v",
keyGoPath, tmpDir,
)
}
} else {
return errors.New("$GOPATH and $GOBIN is not set")
}
return nil
}
// EndDryRunMode restore the GOBIN or GOPATH settings.
func (gp *GoPaths) EndDryRunMode() error {
if gp.GOBIN != "" {
if err := os.Setenv(keyGoBin, gp.GOBIN); err != nil {
// Wrap error to avoid OS dependent error message during testing.
return errors.Wrapf(
err,
"failed to set GOBIN to env variable. key: %v, value: %v",
keyGoBin, gp.GOBIN,
)
}
} else if gp.GOPATH != "" {
if err := os.Setenv(keyGoPath, gp.GOPATH); err != nil {
return errors.Wrapf(
err,
"failed to set GOPATH to env variable. key: %v, value: %v",
keyGoPath, gp.GOPATH,
)
}
} else {
return errors.New("$GOPATH and $GOBIN is not set")
}
if err := gp.removeTmpDir(); err != nil {
return errors.Wrap(err, "temporary directory for dry run remains")
}
return nil
}
// removeTmpDir remove tmporary directory for dry run
func (gp *GoPaths) removeTmpDir() error {
if gp.TmpPath != "" {
return os.RemoveAll(gp.TmpPath)
}
return nil
}
// CanUseGoCmd check whether go command install in the system.
func CanUseGoCmd() error {
_, err := exec.LookPath(goExe)
return err
}
// InstallLatest execute "$ go install <importPath>@latest"
func InstallLatest(importPath string) error {
return install(importPath, "latest")
}
// InstallMainOrMaster execute "$ go install <importPath>@main" or "$ go install <importPath>@master"
func InstallMainOrMaster(importPath string) error {
mainErr := install(importPath, "main")
if mainErr != nil {
// Previous error is "invalid version: unknown revision main". Not return this error.
masterErr := install(importPath, "master")
if masterErr == nil {
return nil
}
const errMsg = "cannot update with @master or @main using the 'gup'. please update manually."
if strings.Contains(mainErr.Error(), "unknown revision main") {
return fmt.Errorf("%s\n%w", errMsg, masterErr)
} else if strings.Contains(masterErr.Error(), "unknown revision master") {
return fmt.Errorf("%s\n%w", errMsg, mainErr)
}
return fmt.Errorf("%s\n%s\n%w", errMsg, mainErr.Error(), masterErr)
}
return nil
}
// install execute "$ go install <importPath>@<version>"
func install(importPath, version string) error {
if importPath == "command-line-arguments" {
return errors.New("is devel-binary copied from local environment")
}
var stderr bytes.Buffer
cmd := exec.Command(goExe, "install", fmt.Sprintf("%s@%s", importPath, version)) //#nosec
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return fmt.Errorf("can't install %s:\n%s", importPath, stderr.String())
}
return nil
}
// GetLatestVer execute "$ go list -m -f {{.Version}} <importPath>@latest"
func GetLatestVer(modulePath string) (string, error) {
out, err := exec.Command(goExe, "list", "-m", "-f", "{{.Version}}", modulePath+"@latest").Output() //#nosec
if err != nil {
return "", errors.New("can't check " + modulePath)
}
return strings.TrimRight(string(out), "\n"), nil
}
// goPath return GOPATH environment variable.
func goPath() string {
gopath := os.Getenv(keyGoPath)
if gopath != "" {
return gopath
}
out, err := exec.Command(goExe, "env", keyGoPath).Output()
if err == nil {
return strings.TrimSpace(string(out))
}
return build.Default.GOPATH
}
// goBin return GOBIN environment variable.
func goBin() string {
return os.Getenv(keyGoBin)
}
// GoBin return $GOPATH/bin directory path.
func GoBin() (string, error) {
goBin := goBin()
if goBin != "" {
return goBin, nil
}
goPath := goPath()
if goPath == "" {
return "", errors.New("$GOPATH is not set")
}
return filepath.Join(goPath, "bin"), nil
}
// BinaryPathList return list of binary paths.
func BinaryPathList(path string) ([]string, error) {
entries, err := os.ReadDir(path)
if err != nil {
return nil, err
}
list := []string{}
for _, e := range entries {
if e.IsDir() {
continue
}
path := filepath.Join(path, e.Name())
if file.IsHiddenFile(path) {
continue
}
list = append(list, path)
}
return list, nil
}
// GetPackageInformation return golang package information.
func GetPackageInformation(binList []string) []Package {
pkgs := []Package{}
goVer, err := GetInstalledGoVersion()
if err != nil {
goVer = "unknown"
}
for _, v := range binList {
info, err := buildinfo.ReadFile(v)
if err != nil {
print.Warn(err)
continue
}
pkg := Package{
Name: filepath.Base(v),
ImportPath: info.Path,
ModulePath: info.Main.Path,
Version: NewVersion(),
GoVersion: NewVersion(),
}
pkg.Version.Current = info.Main.Version
pkg.GoVersion.Current = info.GoVersion
pkg.GoVersion.Latest = goVer
pkgs = append(pkgs, pkg)
}
return pkgs
}
// GetPackageVersion return golang package version
func GetPackageVersion(cmdName string) string {
goBin, err := GoBin()
if err != nil {
return "unknown"
}
info, err := buildinfo.ReadFile(filepath.Join(goBin, cmdName))
if err != nil {
return "unknown"
}
return info.Main.Version
}
var goVersionRegex = regexp.MustCompile(`(^|\s)(go[1-9]\S+)`)
// GetInstalledGoVersion return installed go version.
func GetInstalledGoVersion() (string, error) {
var stdout, stderr bytes.Buffer
cmd := exec.Command(goExe, "version")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return "", fmt.Errorf("can't check go version:\n%s", stderr.String())
}
if m := goVersionRegex.FindStringSubmatch(stdout.String()); m != nil {
return m[2], nil
}
return "", fmt.Errorf("can't find go version string in %q", strings.TrimSpace(stdout.String()))
}