-
Notifications
You must be signed in to change notification settings - Fork 24
/
srcrepo.go
346 lines (287 loc) · 7.47 KB
/
srcrepo.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
package gvm
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/andrewkroh/gvm/common"
)
type srcCacheInfo struct {
Updated time.Time
}
func (m *Manager) srcCacheDir() string {
return filepath.Join(m.cacheDir, "go")
}
func (m *Manager) hasSrcCache() bool {
localGoSrc := m.srcCacheDir()
exists, err := existsDir(localGoSrc)
return err == nil && exists
}
func (m *Manager) ensureSrcCache() error {
localGoSrc := m.srcCacheDir()
exists, err := existsDir(localGoSrc)
if err != nil {
return err
}
if exists {
return nil
}
return m.updateSrcCache()
}
func (m *Manager) updateSrcCache() error {
localGoSrc := filepath.Join(m.cacheDir, "go")
exists, err := existsDir(localGoSrc)
if err != nil {
return err
}
if !exists {
err = gitClone(m.Logger, localGoSrc, m.GoSourceURL, false)
} else {
err = gitPull(m.Logger, localGoSrc)
}
if err != nil {
return err
}
return writeJSONFile(filepath.Join(m.cacheDir, "go.meta"), srcCacheInfo{
Updated: time.Now(),
})
}
func (m *Manager) installSrc(version *GoVersion) (string, error) {
log := m.Logger
if err := m.ensureSrcCache(); err != nil {
return "", err
}
tag := "master"
to := m.VersionGoROOT(version)
exists, err := existsDir(to)
if err != nil {
return "", err
}
if !version.IsTip() {
tag = fmt.Sprintf("go%v", version)
if err := m.ensureSrcVersionAvail(version); err != nil {
return "", err
}
}
godir := m.versionDir(version)
log.Println("create temp directory")
tmpRoot, err := os.MkdirTemp("", godir)
if err != nil {
return "", err
}
defer os.RemoveAll(tmpRoot)
err = buildGo(log, tmpRoot, m.srcCacheDir(), version, tag)
if err != nil {
return "", err
}
if exists {
log.Println("remove old installation")
if err := os.RemoveAll(to); err != nil {
return "", err
}
}
// move final build result into destination
log.Println("rename")
if err = common.Rename(filepath.Join(tmpRoot, "go"), to); err != nil {
return "", err
}
return to, nil
}
func buildGo(log logrus.FieldLogger, buildDir, repo string, version *GoVersion, tag string) error {
log.Println("copy cache")
tmp := filepath.Join(buildDir, "go")
if err := gitClone(log, tmp, repo, false); err != nil {
return err
}
log.Println("checkout tag:", tag)
if err := gitCheckout(log, tmp, tag); err != nil {
return err
}
bootstrap := os.Getenv("GOROOT_BOOTSTRAP")
if bootstrap == "" {
bootstrap = os.Getenv("GOROOT")
if bootstrap == "" {
return errors.New("GOROOT or GOROOT_BOOTSTRAP must be set")
}
}
if !version.IsTip() {
// write VERSION file
versionFile := filepath.Join(tmp, "VERSION")
err := os.WriteFile(versionFile, []byte(version.String()), 0o644)
if err != nil {
return err
}
}
if err := os.RemoveAll(filepath.Join(tmp, "go", ".git")); err != nil {
return err
}
log.Println("build")
srcDir := filepath.Join(tmp, "src")
var cmd *command
if runtime.GOOS == "windows" {
cmd = makeCommand("cmd", "/C", "make.bat")
} else {
cmd = makeCommand("bash", "make.bash")
}
cmd.Env = []string{
"GOROOT_BOOTSTRAP=" + bootstrap,
}
// Don't look for go.mod when building bootstrapping older pre-module
// versions while using a new module aware Go version.
if _, err := os.Stat(filepath.Join(srcDir, "go.mod")); errors.Is(err, os.ErrNotExist) {
cmd.Env = append(cmd.Env, "GO111MODULE=off")
}
return cmd.WithDir(srcDir).WithLogger(log).Exec()
}
func (m *Manager) hasSrcVersion(version *GoVersion) (bool, error) {
log := m.Logger
localGoSrc := filepath.Join(m.cacheDir, "go")
tag := fmt.Sprintf("go%s", version)
log.Println("check version tag")
hasTag := false
err := gitListTags(log, localGoSrc, func(t string) { hasTag = hasTag || t == tag })
return hasTag, err
}
func (m *Manager) ensureSrcVersionAvail(version *GoVersion) error {
has, err := m.hasSrcVersion(version)
if err != nil {
return err
}
if !has {
if err := m.updateSrcCache(); err != nil {
return err
}
has, err = m.hasSrcVersion(version)
if err != nil {
return err
}
}
if !has {
return fmt.Errorf("unknown version %s", version)
}
return nil
}
func (m *Manager) tryRefreshSrcCache() (bool, error) {
log := m.Logger
localGoSrc := m.srcCacheDir()
exists, err := existsDir(localGoSrc)
if err != nil {
return false, err
}
if !exists {
log.Println("Go cache not found")
err := m.updateSrcCache()
return err == nil, err
}
info := srcCacheInfo{}
if err := readJSONFile(filepath.Join(m.cacheDir, "go.meta"), &info); err != nil {
return false, err
}
updTS := info.Updated
now := time.Now()
if now.Before(updTS) {
return false, nil
}
// don't refresh cache if still same day
if updTS.Day() == now.Day() && updTS.Month() == now.Month() && updTS.Year() == now.Year() {
return false, nil
}
log.Println("Fetch updates")
if err := m.updateSrcCache(); err != nil {
return false, err // update cache failed
}
// check for updates ;)
cTS, err := gitLastCommitTimestamp(log, m.srcCacheDir())
if err != nil {
return false, err
}
log.Printf("last update ts=%v, last commit ts=%v\n", updTS, cTS)
// check new commits have been added since last refresh
updates := updTS.Before(cTS)
if updates {
log.Println("New commits since last build")
} else {
log.Println("No New commits since last build")
}
return updates, nil
}
func (m *Manager) AvailableSource() ([]*GoVersion, error) {
if updates, err := m.tryRefreshSrcCache(); err != nil {
return nil, fmt.Errorf("failed to refresh source cache: %w", err)
} else if updates {
log.Println("Source cache was updated.")
}
localGoSrc := m.srcCacheDir()
var versions []*GoVersion
err := gitListTags(m.Logger, localGoSrc, func(tag string) {
if !strings.HasPrefix(tag, "go") {
return
}
ver, err := ParseVersion(tag[2:])
if err != nil {
return
}
versions = append(versions, ver)
})
if err != nil {
return nil, err
}
tip, _ := ParseVersion("tip")
versions = append(versions, tip)
sortVersions(versions)
return versions, err
}
func gitClone(logger logrus.FieldLogger, to, url string, bare bool) error {
tmpDir := to + ".tmp"
if err := os.Mkdir(tmpDir, 0o755); err != nil {
return err
}
defer os.RemoveAll(tmpDir)
args := []string{"clone"}
if bare {
args = append(args, "--bare")
}
args = append(args, url, tmpDir)
logger.Println("git clone:")
cmd := makeCommand("git", args...).WithLogger(logger)
if err := cmd.Exec(); err != nil {
return err
}
// Move into the final location.
return common.Rename(tmpDir, to)
}
func gitLastCommitTimestamp(logger logrus.FieldLogger, path string) (time.Time, error) {
var tsLine string
logger.Println("git log:")
cmd := makeCommand("git", "log", "-n", "1", "--pretty=format:%ct")
cmd.Stdout = func(l string) { tsLine = l }
err := cmd.WithDir(path).WithLogger(logger).Exec()
if err != nil {
return time.Time{}, err
}
i, err := strconv.ParseInt(tsLine, 10, 64)
if err != nil {
return time.Time{}, err
}
return time.Unix(i, 0), nil
}
func gitPull(logger logrus.FieldLogger, path string) error {
logger.Println("git pull:")
return makeCommand("git", "pull").WithDir(path).WithLogger(logger).Exec()
}
func gitCheckout(logger logrus.FieldLogger, path, tag string) error {
logger.Println("git checkout:")
return makeCommand("git", "checkout", tag).WithDir(path).WithLogger(logger).Exec()
}
func gitListTags(logger logrus.FieldLogger, path string, fn func(string)) error {
logger.Println("git tag:")
cmd := makeCommand("git", "tag").WithDir(path).WithLogger(logger)
cmd.Stdout = fn
return cmd.Exec()
}