forked from paketo-buildpacks/node-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nvmrc_parser.go
101 lines (81 loc) · 1.99 KB
/
nvmrc_parser.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
package nodeengine
import (
"fmt"
"os"
"strings"
"github.com/Masterminds/semver/v3"
)
var (
lts = map[string]int{
"argon": 4,
"boron": 6,
"carbon": 8,
"dubnium": 10,
"erbium": 12,
"fermium": 14,
"gallium": 16,
"hydrogen": 18,
"iron": 20,
}
)
type NvmrcParser struct{}
func NewNvmrcParser() NvmrcParser {
return NvmrcParser{}
}
func (p NvmrcParser) ParseVersion(path string) (string, error) {
nvmrcContents, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return "", nil
}
return "", err
}
nvmrcVersion, err := p.validateNvmrc(string(nvmrcContents))
if err != nil {
return "", err
}
// TODO
// if nvmrcVersion == Node {
// logger.Info(".nvmrc specified latest node version, this will be selected from versions available in buildpack.toml")
// }
//
// if strings.HasPrefix(nvmrcVersion, "lts") {
// logger.Info(".nvmrc specified an lts version, this will be selected from versions available in buildpack.toml")
// }
return p.formatNvmrcContent(nvmrcVersion), nil
}
func (p NvmrcParser) validateNvmrc(content string) (string, error) {
content = strings.TrimSpace(strings.ToLower(content))
if content == "lts/*" || content == Node {
return content, nil
}
for key := range lts {
if content == strings.ToLower("lts/"+key) {
return content, nil
}
}
content = strings.TrimPrefix(content, "v")
if _, err := semver.NewConstraint(content); err != nil {
return "", fmt.Errorf("invalid version constraint specified in .nvmrc: %q", content)
}
return content, nil
}
func (p NvmrcParser) formatNvmrcContent(version string) string {
if version == Node {
return "*"
}
if strings.HasPrefix(version, "lts") {
ltsName := strings.SplitN(version, "/", 2)[1]
if ltsName == "*" {
var maxVersion int
for _, versionValue := range lts {
if maxVersion < versionValue {
maxVersion = versionValue
}
}
return fmt.Sprintf("%d.*", maxVersion)
}
return fmt.Sprintf("%d.*", lts[ltsName])
}
return version
}