forked from tofuutils/tenv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager.go
565 lines (444 loc) · 16.2 KB
/
manager.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/*
*
* Copyright 2024 tofuutils authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package versionmanager
import (
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-version"
"github.com/tofuutils/tenv/v3/config"
"github.com/tofuutils/tenv/v3/pkg/lockfile"
"github.com/tofuutils/tenv/v3/pkg/loghelper"
"github.com/tofuutils/tenv/v3/pkg/reversecmp"
"github.com/tofuutils/tenv/v3/versionmanager/lastuse"
"github.com/tofuutils/tenv/v3/versionmanager/semantic"
flatparser "github.com/tofuutils/tenv/v3/versionmanager/semantic/parser/flat"
iacparser "github.com/tofuutils/tenv/v3/versionmanager/semantic/parser/iac"
"github.com/tofuutils/tenv/v3/versionmanager/semantic/types"
)
var (
errEmptyVersion = errors.New("empty version")
errNoCompatible = errors.New("no compatible version found")
ErrNoCompatibleLocally = errors.New("no compatible version found locally")
)
type ReleaseInfoRetriever interface {
InstallRelease(ctx context.Context, version string, targetPath string) error
ListReleases(ctx context.Context) ([]string, error)
}
type DatedVersion struct {
UseDate time.Time
Version string
}
type VersionManager struct {
conf *config.Config
constraintEnvName string
FolderName string
iacExts []iacparser.ExtDescription
retriever ReleaseInfoRetriever
VersionEnvName string
defaultVersionEnvName string
VersionFiles []types.VersionFile
}
func Make(conf *config.Config, constraintEnvName string, folderName string, iacExts []iacparser.ExtDescription, retriever ReleaseInfoRetriever, versionEnvName string, defaultVersionEnvName string, versionFiles []types.VersionFile) VersionManager {
return VersionManager{conf: conf, constraintEnvName: constraintEnvName, FolderName: folderName, iacExts: iacExts, retriever: retriever, VersionEnvName: versionEnvName, defaultVersionEnvName: defaultVersionEnvName, VersionFiles: versionFiles}
}
// Detect version (resolve and evaluate, can install depending on auto install env var).
func (m VersionManager) Detect(ctx context.Context, proxyCall bool) (string, error) {
configVersion, err := m.Resolve(semantic.LatestAllowedKey)
if err != nil {
m.conf.Displayer.Flush(proxyCall)
return "", err
}
return m.Evaluate(ctx, configVersion, proxyCall)
}
// Evaluate version resolution strategy or version constraint (can install depending on auto install env var).
func (m VersionManager) Evaluate(ctx context.Context, requestedVersion string, proxyCall bool) (string, error) {
parsedVersion, err := version.NewVersion(requestedVersion)
if err == nil {
cleanedVersion := parsedVersion.String() // use a parsable version
if m.conf.SkipInstall {
_, installed, err := m.checkVersionInstallation("", cleanedVersion)
if err != nil {
return "", err
}
if !installed {
return cleanedVersion, m.autoInstallDisabledMsg(cleanedVersion)
}
m.conf.Displayer.Flush(proxyCall)
return cleanedVersion, nil
}
return cleanedVersion, m.installSpecificVersion(ctx, cleanedVersion, proxyCall)
}
predicateInfo, err := semantic.ParsePredicate(requestedVersion, m.FolderName, m, m.iacExts, m.conf)
if err != nil {
m.conf.Displayer.Flush(proxyCall)
return "", err
}
installPath, err := m.InstallPath()
if err != nil {
m.conf.Displayer.Flush(proxyCall)
return "", err
}
if !m.conf.ForceRemote {
versions, err := m.innerListLocal(installPath, predicateInfo.ReverseOrder)
if err != nil {
m.conf.Displayer.Flush(proxyCall)
return "", err
}
for _, version := range versions {
if predicateInfo.Predicate(version) {
m.conf.Displayer.Display("Found compatible version installed locally : " + version)
m.conf.Displayer.Flush(proxyCall)
return version, nil
}
}
m.conf.Displayer.Display("No compatible version found locally, search a remote one...")
}
return m.searchInstallRemote(ctx, predicateInfo, m.conf.SkipInstall, proxyCall)
}
func (m VersionManager) Install(ctx context.Context, requestedVersion string) error {
parsedVersion, err := version.NewVersion(requestedVersion)
if err == nil {
return m.installSpecificVersion(ctx, parsedVersion.String(), false) // use a parsable version
}
predicateInfo, err := semantic.ParsePredicate(requestedVersion, m.FolderName, m, m.iacExts, m.conf)
if err != nil {
return err
}
// noInstall is set to false to force install regardless of conf
_, err = m.searchInstallRemote(ctx, predicateInfo, false, false)
return err
}
func (m VersionManager) InstallMultiple(ctx context.Context, versions []string) error {
installPath, err := m.InstallPath()
if err != nil {
return err
}
deleteLock := lockfile.Write(installPath, m.conf.Displayer)
disableExit := lockfile.CleanAndExitOnInterrupt(deleteLock)
defer disableExit()
defer deleteLock()
for _, version := range versions {
if err = m.installSpecificVersionWithoutLock(ctx, installPath, version, false); err != nil {
return err
}
}
return nil
}
// try to ensure the directory exists with a MkdirAll call.
// (made lazy method : not always useful and allows flag override for root path).
func (m VersionManager) InstallPath() (string, error) {
dirPath := filepath.Join(m.conf.RootPath, m.FolderName)
return dirPath, os.MkdirAll(dirPath, 0o755)
}
func (m VersionManager) ListLocal(reverseOrder bool) ([]DatedVersion, error) {
installPath, err := m.InstallPath()
if err != nil {
return nil, err
}
versions, err := m.innerListLocal(installPath, reverseOrder)
if err != nil {
return nil, err
}
datedVersions := make([]DatedVersion, 0, len(versions))
for _, version := range versions {
datedVersions = append(datedVersions, DatedVersion{
UseDate: lastuse.Read(filepath.Join(installPath, version), m.conf.Displayer),
Version: version,
})
}
return datedVersions, nil
}
func (m VersionManager) ListRemote(ctx context.Context, reverseOrder bool) ([]string, error) {
versions, err := m.retriever.ListReleases(ctx)
if err != nil {
return nil, err
}
cmpFunc := reversecmp.Reverser[string](semantic.CmpVersion, reverseOrder)
slices.SortFunc(versions, cmpFunc)
return versions, nil
}
func (m VersionManager) LocalSet() map[string]struct{} {
installPath, err := m.InstallPath()
if err != nil {
m.conf.Displayer.Log(hclog.Warn, "Can not create installation directory", loghelper.Error, err)
return nil
}
entries, err := os.ReadDir(installPath)
if err != nil {
m.conf.Displayer.Log(loghelper.LevelWarnOrDebug(errors.Is(err, fs.ErrNotExist)), "Can not read installed versions", loghelper.Error, err)
return nil
}
versionSet := make(map[string]struct{}, len(entries))
for _, entry := range entries {
if entry.IsDir() {
versionSet[entry.Name()] = struct{}{}
}
}
return versionSet
}
func (m VersionManager) ReadDefaultConstraint() string {
if constraint := os.Getenv(m.constraintEnvName); constraint != "" {
return constraint
}
constraint, _ := flatparser.Retrieve(m.RootConstraintFilePath(), m.conf, flatparser.NoMsg)
return constraint
}
func (m VersionManager) ResetConstraint() error {
return removeFile(m.RootConstraintFilePath(), m.conf)
}
func (m VersionManager) ResetVersion() error {
return removeFile(m.RootVersionFilePath(), m.conf)
}
// Search the requested version in version files (with fallbacks and env var overloading).
func (m VersionManager) Resolve(defaultStrategy string) (string, error) {
version := os.Getenv(m.VersionEnvName)
if version != "" {
return types.DisplayDetectionInfo(m.conf.Displayer, version, m.VersionEnvName), nil
}
version, err := m.ResolveWithVersionFiles()
if err != nil || version != "" {
return version, err
}
if version = os.Getenv(m.defaultVersionEnvName); version != "" {
return types.DisplayDetectionInfo(m.conf.Displayer, version, m.defaultVersionEnvName), nil
}
if version, err = flatparser.RetrieveVersion(m.RootVersionFilePath(), m.conf); err != nil || version != "" {
return version, err
}
m.conf.Displayer.Display(loghelper.Concat("No version files found for ", m.FolderName, ", fallback to ", defaultStrategy, " strategy"))
return defaultStrategy, nil
}
// Search the requested version in version files.
func (m VersionManager) ResolveWithVersionFiles() (string, error) {
return semantic.RetrieveVersion(m.VersionFiles, m.conf)
}
// (made lazy method : not always useful and allows flag override for root path).
func (m VersionManager) RootConstraintFilePath() string {
return filepath.Join(m.conf.RootPath, m.FolderName, "constraint")
}
// (made lazy method : not always useful and allows flag override for root path).
func (m VersionManager) RootVersionFilePath() string {
return filepath.Join(m.conf.RootPath, m.FolderName, "version")
}
func (m VersionManager) SetConstraint(constraint string) error {
_, err := version.NewConstraint(constraint) // check the use of a parsable constraint
if err != nil {
return err
}
return writeFile(m.RootConstraintFilePath(), constraint, m.conf)
}
func (m VersionManager) Uninstall(requestedVersion string) error {
installPath, err := m.InstallPath()
if err != nil {
return err
}
deleteLock := lockfile.Write(installPath, m.conf.Displayer)
disableExit := lockfile.CleanAndExitOnInterrupt(deleteLock)
defer disableExit()
defer deleteLock()
parsedVersion, err := version.NewVersion(requestedVersion) // check the use of a parsable version
if err == nil {
m.uninstallSpecificVersion(installPath, parsedVersion.String())
return nil
}
versions, err := m.innerListLocal(installPath, true)
if err != nil {
return err
}
selected, err := semantic.SelectVersionsToUninstall(requestedVersion, installPath, versions, m.conf.Displayer)
if err != nil {
return err
}
if len(selected) == 0 {
m.conf.Displayer.Display(loghelper.Concat("No matching ", m.FolderName, " versions"))
return nil
}
m.conf.Displayer.Display(loghelper.Concat("Selected ", m.FolderName, " versions for uninstallation :"))
m.conf.Displayer.Display(strings.Join(selected, ", "))
m.conf.Displayer.Display("Uninstall ? [y/N]")
buffer := make([]byte, 1)
os.Stdin.Read(buffer)
read := buffer[0]
if doUninstall := read == 'y' || read == 'Y'; !doUninstall {
return nil
}
for _, version := range selected {
m.uninstallSpecificVersion(installPath, version)
}
return nil
}
func (m VersionManager) UninstallMultiple(versions []string) error {
installPath, err := m.InstallPath()
if err != nil {
return err
}
deleteLock := lockfile.Write(installPath, m.conf.Displayer)
disableExit := lockfile.CleanAndExitOnInterrupt(deleteLock)
defer disableExit()
defer deleteLock()
for _, version := range versions {
m.uninstallSpecificVersion(installPath, version)
}
return nil
}
func (m VersionManager) Use(ctx context.Context, requestedVersion string, workingDir bool) error {
detectedVersion, err := m.Evaluate(ctx, requestedVersion, false)
if err != nil {
if err != ErrNoCompatibleLocally {
return err
}
m.conf.Displayer.Display(err.Error())
}
targetFilePath := m.VersionFiles[0].Name
if !workingDir {
targetFilePath = m.RootVersionFilePath()
}
return writeFile(targetFilePath, detectedVersion, m.conf)
}
func (m VersionManager) alreadyInstalledMsg(version string, proxyCall bool) {
m.conf.Displayer.Display(loghelper.Concat(m.FolderName, " ", version, " already installed"))
m.conf.Displayer.Flush(proxyCall)
}
func (m VersionManager) autoInstallDisabledMsg(version string) error {
cmdName := strings.ToLower(m.FolderName)
m.conf.Displayer.Flush(false) // Always normal display when installation is missing
m.conf.Displayer.Display(loghelper.Concat("Auto-install is disabled. To install ", m.FolderName, " version ", version, ", you can set environment variable TENV_AUTO_INSTALL=true, or install it via any of the following command: 'tenv ", cmdName, " install', 'tenv ", cmdName, " install ", version, "'"))
return ErrNoCompatibleLocally
}
func (m VersionManager) checkVersionInstallation(installPath string, version string) (string, bool, error) {
var err error
if installPath == "" {
installPath, err = m.InstallPath()
if err != nil {
return "", false, err
}
}
if _, err = os.Stat(filepath.Join(installPath, version)); err != nil {
if errors.Is(err, os.ErrNotExist) {
return installPath, false, nil
}
return "", false, err
}
return installPath, true, nil
}
func (m VersionManager) innerListLocal(installPath string, reverseOrder bool) ([]string, error) {
entries, err := os.ReadDir(installPath)
if err != nil {
return nil, err
}
versions := make([]string, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() {
versions = append(versions, entry.Name())
}
}
cmpFunc := reversecmp.Reverser[string](semantic.CmpVersion, reverseOrder)
slices.SortFunc(versions, cmpFunc)
return versions, nil
}
func (m VersionManager) installSpecificVersion(ctx context.Context, version string, proxyCall bool) error {
if version == "" {
m.conf.Displayer.Flush(proxyCall)
return errEmptyVersion
}
// first check without lock
installPath, installed, err := m.checkVersionInstallation("", version)
if err != nil {
return err
}
if installed {
m.alreadyInstalledMsg(version, proxyCall)
return nil
}
deleteLock := lockfile.Write(installPath, m.conf.Displayer)
disableExit := lockfile.CleanAndExitOnInterrupt(deleteLock)
defer disableExit()
defer deleteLock()
return m.installSpecificVersionWithoutLock(ctx, installPath, version, proxyCall)
}
func (m VersionManager) installSpecificVersionWithoutLock(ctx context.Context, installPath string, version string, proxyCall bool) error {
// second check with lock to ensure there is no ongoing install
_, installed, err := m.checkVersionInstallation(installPath, version)
if err != nil {
return err
}
if installed {
m.alreadyInstalledMsg(version, proxyCall)
return nil
}
// Always normal display when installation is needed
m.conf.Displayer.Flush(false)
m.conf.Displayer.Display(loghelper.Concat("Installing ", m.FolderName, " ", version))
err = m.retriever.InstallRelease(ctx, version, filepath.Join(installPath, version))
if err == nil {
m.conf.Displayer.Display(loghelper.Concat("Installation of ", m.FolderName, " ", version, " successful"))
}
return err
}
func (m VersionManager) searchInstallRemote(ctx context.Context, predicateInfo types.PredicateInfo, noInstall bool, proxyCall bool) (string, error) {
versions, err := m.ListRemote(ctx, predicateInfo.ReverseOrder)
if err != nil {
m.conf.Displayer.Flush(proxyCall)
return "", err
}
for _, version := range versions {
if predicateInfo.Predicate(version) {
m.conf.Displayer.Display("Found compatible version remotely : " + version)
if noInstall {
return version, m.autoInstallDisabledMsg(version)
}
return version, m.installSpecificVersion(ctx, version, proxyCall)
}
}
m.conf.Displayer.Flush(proxyCall)
return "", errNoCompatible
}
func (m VersionManager) uninstallSpecificVersion(installPath string, version string) {
if version == "" {
m.conf.Displayer.Display(errEmptyVersion.Error())
return
}
targetPath := filepath.Join(installPath, version)
err := os.RemoveAll(targetPath)
if err == nil {
m.conf.Displayer.Display(loghelper.Concat("Uninstallation of ", m.FolderName, " ", version, " successful (directory ", targetPath, " removed)"))
} else {
m.conf.Displayer.Display(loghelper.Concat("Uninstallation of ", m.FolderName, " ", version, " failed with error : ", err.Error()))
}
}
func removeFile(filePath string, conf *config.Config) error {
err := os.RemoveAll(filePath)
if err == nil {
conf.Displayer.Display("Removed " + filePath)
}
return err
}
func writeFile(filePath string, content string, conf *config.Config) error {
err := os.WriteFile(filePath, []byte(content), 0o644)
if err == nil {
conf.Displayer.Display(loghelper.Concat("Written ", content, " in ", filePath))
}
return err
}