-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
304 lines (254 loc) · 6.36 KB
/
main.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
//go:build unix
package main
import (
"debug/buildinfo"
"errors"
"fmt"
"io/fs"
"log/slog"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
)
const (
goBinEnv = "GOBIN"
goPathEnv = "GOPATH"
goProxyEnv = "GOPROXY"
goMinVersionEnv = "GOMINVERSION"
homeEnv = "HOME"
ignorePath = ".goupdateignore"
logErrorKey = "error"
)
var (
client = http.DefaultClient
logLevel = &slog.LevelVar{}
// minGoVersion sets the minimum go version that the binaries have to be
// built with. From go1.18 on the full build info is included, however, some
// of it has been present with go1.17, and it might work with go1.17
// binaries as well.
minGoVersion = "go1.18"
// goProxies contains the parsed list of the GOPROXY environment variable.
// It honors the definition at
// https://go.dev/ref/mod#environment-variables.
goProxies = []string{"https://proxy.golang.org", "direct"}
goBin string
goCli string
excludePatterns []string
includePatterns []string
)
type usageError error
func init() {
var err error
defer func() {
if err != nil {
fmt.Printf("error: init: %s\n", err.Error())
os.Exit(1) // exit code 1: error during init
} else {
slog.Debug("init done",
goBinEnv, goBin,
goMinVersionEnv, minGoVersion,
"GOCLI", goCli,
goProxyEnv, goProxies,
)
}
}()
logLevelEnv, ok := os.LookupEnv("LOG")
if ok {
err = logLevel.UnmarshalText([]byte(logLevelEnv))
if err != nil {
return
}
} else {
logLevel.Set(slog.LevelError)
}
slog.SetDefault(slog.New(newConsoleHandler(os.Stderr, logLevel)))
customMinGoVersion, ok := os.LookupEnv(goMinVersionEnv)
if ok {
minGoVersion = customMinGoVersion
}
goBin = os.Getenv(goBinEnv)
if goBin == "" && os.Getenv(goPathEnv) != "" {
goBin = filepath.Join(os.Getenv(goPathEnv), "bin")
} else if goBin == "" && os.Getenv(homeEnv) != "" {
goBin = filepath.Join(os.Getenv(homeEnv), "go", "bin")
} else if goBin == "" {
err = fmt.Errorf("unable to determine GOBIN: $GOBIN, $GOPATH and $HOME are not set")
return
}
fileInfo, err := os.Stat(goBin)
if err != nil {
err = fmt.Errorf("stat $GOBIN (%s): %s", goBin, err.Error())
return
}
if !fileInfo.IsDir() {
err = fmt.Errorf("$GOBIN (%s) is not a directory", goBin)
return
}
proxy, ok := os.LookupEnv(goProxyEnv)
if ok {
goProxies = strings.Split(proxy, ",")
}
goCli, err = exec.LookPath("go")
if err != nil {
err = fmt.Errorf("looking up go cli path: %w", err)
return
}
excludePatterns, includePatterns, err = ignoreFile(filepath.Join(goBin, ignorePath))
if err != nil {
err = fmt.Errorf("load ignore file: %w", err)
}
}
func main() {
err := Main()
if err != nil {
var usageErr usageError
if errors.As(err, &usageErr) {
fmt.Printf("Usage: %s [ update (default) | list ]\n", os.Args[0])
}
fmt.Printf("error: main: %s\n", err.Error())
os.Exit(2) // exit code 2: generic error during execution
}
}
func Main() error {
var list bool
if len(os.Args) > 2 {
return usageError(fmt.Errorf("only one argument can be provided"))
} else if len(os.Args) > 1 {
switch os.Args[1] {
case "update": // default, no-op
case "list":
list = true
default:
return usageError(fmt.Errorf("unknown command '%s'", os.Args[1]))
}
}
entries, err := fs.ReadDir(os.DirFS(goBin), ".")
if err != nil {
return err
}
var artefacts []Artefact
for _, entry := range entries {
executablePath := filepath.Join(goBin, entry.Name())
log := slog.With("path", executablePath)
if ignore(excludePatterns, includePatterns, entry.Name()) {
log.Debug("ignoring file")
continue
}
if entry.IsDir() {
log.Info("skipping directory", "name", entry.Name())
continue
}
fileInfo, err := entry.Info()
if err != nil {
log.Error("reading file info failed", logErrorKey, err)
continue
}
if !executable(fileInfo.Mode()) {
log.Info("skipping non-executable file")
continue
}
if !fileInfo.Mode().Type().IsRegular() {
log.Info("skipping non-regular file")
continue
}
info, err := buildinfo.ReadFile(executablePath)
if err != nil {
log.Error("reading build info failed", logErrorKey, err)
continue
}
if info.GoVersion < minGoVersion {
log.Error("go version too old to update", "go-version", info.GoVersion)
continue
}
a, err := NewArtefact(info)
if err != nil {
log.Error("loading artefact failed", logErrorKey, err)
continue
}
artefacts = append(artefacts, a)
log.Info("loaded artefact", "installed-version", a.InstalledVersion(),
"target-version", a.TargetVersion())
if list || !a.NeedsUpdate() {
continue
}
err = a.Update()
if err != nil {
log.Error("installing target version failed", logErrorKey, err)
continue
}
log.Info("updated artefact")
}
if list {
printArtefacts(artefacts)
}
return nil
}
func install(pkg string, version string) error {
args := []string{"go", "install"}
if logLevel.Level() <= slog.LevelInfo {
args = append(args, "-v")
}
if logLevel.Level() <= slog.LevelDebug {
args = append(args, "-x")
}
args = append(args, fmt.Sprintf("%s@%s", pkg, version))
cmd := exec.Cmd{
Path: goCli,
Args: args,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
slog.Debug("executing command", "cmd", cmd.String())
return cmd.Run()
}
func executable(mode os.FileMode) bool {
return mode&0111 != 0
}
func printArtefacts(artefacts []Artefact) {
var table [][]string
table = append(table, []string{"Program", "Installed Version", "Latest Version"})
for _, a := range artefacts {
table = append(table, []string{
a.InstallPath(),
a.InstalledVersion(),
a.TargetVersion(),
})
}
tablePrint(table)
}
func tablePrint(table [][]string) {
var columnWidth []int
for _, row := range table {
for ci, column := range row {
if ci >= len(columnWidth) {
// new column
// TODO: this is not the correct way to get the width of a string
columnWidth = append(columnWidth, len(column))
} else if len(column) > columnWidth[ci] {
// new biggest value for column
columnWidth[ci] = len(column)
}
}
}
spaces := func(n int) string {
b := strings.Builder{}
for i := 0; i < n; i++ {
b.WriteRune(' ')
}
return b.String()
}
b := strings.Builder{}
for _, row := range table {
for ci, column := range row {
b.WriteString(column)
if ci == len(row)-1 {
continue
}
b.WriteString(spaces(columnWidth[ci] - len(column) + 1))
}
b.WriteRune('\n')
}
fmt.Print(b.String())
}