Skip to content

Commit d9327f6

Browse files
committed
improve ParseTorelant to be more tolerant with quirky inputs
1 parent 4487282 commit d9327f6

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

v4/semver.go

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -235,12 +235,22 @@ func Make(s string) (Version, error) {
235235

236236
// ParseTolerant allows for certain version specifications that do not strictly adhere to semver
237237
// specs to be parsed by this library. It does so by normalizing versions before passing them to
238-
// Parse(). It currently trims spaces, removes a "v" prefix, adds a 0 patch number to versions
239-
// with only major and minor components specified, and removes leading 0s.
238+
// Parse(). It currently trims spaces, removes a "v" prefix, adds 0s to missing minor and patch versions,
239+
// and removes leading 0s. PreRelease/Build meta data is preserved.
240240
func ParseTolerant(s string) (Version, error) {
241241
s = strings.TrimSpace(s)
242242
s = strings.TrimPrefix(s, "v")
243243

244+
//Extract PreRelease/Build meta data if any
245+
index := strings.IndexRune(s, '-')
246+
if buildIndex := strings.IndexRune(s, '+'); buildIndex != -1 && (buildIndex < index || index == -1) {
247+
index = buildIndex
248+
}
249+
var meta string
250+
if index != -1 {
251+
meta = s[index:]
252+
s = s[:index]
253+
}
244254
// Split into major.minor.(patch+pr+meta)
245255
parts := strings.SplitN(s, ".", 3)
246256
// Remove leading zeros.
@@ -254,15 +264,11 @@ func ParseTolerant(s string) (Version, error) {
254264
}
255265
}
256266
// Fill up shortened versions.
257-
if len(parts) < 3 {
258-
if strings.ContainsAny(parts[len(parts)-1], "+-") {
259-
return Version{}, errors.New("Short version cannot contain PreRelease/Build meta data")
260-
}
261-
for len(parts) < 3 {
262-
parts = append(parts, "0")
263-
}
267+
for len(parts) < 3 {
268+
parts = append(parts, "0")
264269
}
265-
s = strings.Join(parts, ".")
270+
// Reconstruct the normalized version string
271+
s = strings.Join(parts, ".") + meta
266272

267273
return Parse(s)
268274
}

v4/semver_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ var tolerantFormatTests = []formatTest{
4040
{Version{0, 0, 3, nil, nil}, "000.0.03"},
4141
{Version{1, 2, 0, nil, nil}, "1.2"},
4242
{Version{1, 0, 0, nil, nil}, "1"},
43+
{Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}, "1-alpha"},
44+
{Version{1, 2, 0, []PRVersion{prstr("alpha")}, nil}, "1.2-alpha"},
45+
{Version{1, 0, 0, nil, []string{"build", "123"}}, "1+build.123"},
46+
{Version{1, 2, 0, []PRVersion{prstr("alpha"), prstr("b-eta")}, []string{"123", "b-uild"}}, "1.2-alpha.b-eta+123.b-uild"},
4347
}
4448

4549
func TestStringer(t *testing.T) {

0 commit comments

Comments
 (0)