Skip to content

Commit 59cb29e

Browse files
committed
goenv: ParseGoVersion helper
1 parent 9ee8ecf commit 59cb29e

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

goenv/version.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,12 @@ func GetGorootVersion() (major, minor int, err error) {
3434
if err != nil {
3535
return 0, 0, err
3636
}
37+
return ParseGoVersion(s)
38+
}
3739

40+
// ParseGoVersion returns the major and minor version for a given Go version.
41+
// The input must be in the form of "go$MAJOR.$MINOR$TRAILING", e.g. "go1.23" or "go1.24.0-rc2".
42+
func ParseGoVersion(s string) (major, minor int, err error) {
3843
if s == "" || s[:2] != "go" {
3944
return 0, 0, errors.New("could not parse Go version: version does not start with 'go' prefix")
4045
}
@@ -54,7 +59,18 @@ func GetGorootVersion() (major, minor int, err error) {
5459
if err != nil {
5560
return 0, 0, fmt.Errorf("failed to parse version: %s", err)
5661
}
57-
return
62+
63+
return major, minor, nil
64+
}
65+
66+
// WantGoVersion returns true if Go version s is >= major and minor.
67+
// Returns false if s is not a valid Go version string. See [ParseGoVersion] for more information.
68+
func WantGoVersion(s string, major, minor int) bool {
69+
ma, mi, err := ParseGoVersion(s)
70+
if err != nil {
71+
return false
72+
}
73+
return ma >= major && mi >= minor
5874
}
5975

6076
// GorootVersionString returns the version string as reported by the Go

goenv/version_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package goenv
2+
3+
import "testing"
4+
5+
func TestParseGoVersion(t *testing.T) {
6+
tests := []struct {
7+
v string
8+
major int
9+
minor int
10+
wantErr bool
11+
}{
12+
{"", 0, 0, true},
13+
{"go", 0, 0, true},
14+
{"go1", 0, 0, true},
15+
{"go.0", 0, 0, true},
16+
{"go1.0", 1, 0, false},
17+
{"go1.1", 1, 1, false},
18+
{"go1.23", 1, 23, false},
19+
{"go1.23.5", 1, 23, false},
20+
{"go1.23.5-rc6", 1, 23, false},
21+
{"go2.0", 2, 0, false},
22+
}
23+
for _, tt := range tests {
24+
t.Run(tt.v, func(t *testing.T) {
25+
major, minor, err := ParseGoVersion(tt.v)
26+
if err == nil && tt.wantErr {
27+
t.Errorf("ParseGoVersion(%q): expected err != nil", tt.v)
28+
}
29+
if err != nil && !tt.wantErr {
30+
t.Errorf("ParseGoVersion(%q): expected err == nil", tt.v)
31+
}
32+
if major != tt.major || minor != tt.minor {
33+
t.Errorf("ParseGoVersion(%q): expected %d, %d, nil; got %d, %d, %v",
34+
tt.v, tt.major, tt.minor, major, minor, err)
35+
}
36+
})
37+
}
38+
}

0 commit comments

Comments
 (0)