Skip to content

Commit

Permalink
Merge d9327f6 into 4487282
Browse files Browse the repository at this point in the history
  • Loading branch information
trung committed Jun 9, 2020
2 parents 4487282 + d9327f6 commit faf4d07
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
26 changes: 16 additions & 10 deletions v4/semver.go
Expand Up @@ -235,12 +235,22 @@ func Make(s string) (Version, error) {

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

//Extract PreRelease/Build meta data if any
index := strings.IndexRune(s, '-')
if buildIndex := strings.IndexRune(s, '+'); buildIndex != -1 && (buildIndex < index || index == -1) {
index = buildIndex
}
var meta string
if index != -1 {
meta = s[index:]
s = s[:index]
}
// Split into major.minor.(patch+pr+meta)
parts := strings.SplitN(s, ".", 3)
// Remove leading zeros.
Expand All @@ -254,15 +264,11 @@ func ParseTolerant(s string) (Version, error) {
}
}
// Fill up shortened versions.
if len(parts) < 3 {
if strings.ContainsAny(parts[len(parts)-1], "+-") {
return Version{}, errors.New("Short version cannot contain PreRelease/Build meta data")
}
for len(parts) < 3 {
parts = append(parts, "0")
}
for len(parts) < 3 {
parts = append(parts, "0")
}
s = strings.Join(parts, ".")
// Reconstruct the normalized version string
s = strings.Join(parts, ".") + meta

return Parse(s)
}
Expand Down
4 changes: 4 additions & 0 deletions v4/semver_test.go
Expand Up @@ -40,6 +40,10 @@ var tolerantFormatTests = []formatTest{
{Version{0, 0, 3, nil, nil}, "000.0.03"},
{Version{1, 2, 0, nil, nil}, "1.2"},
{Version{1, 0, 0, nil, nil}, "1"},
{Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}, "1-alpha"},
{Version{1, 2, 0, []PRVersion{prstr("alpha")}, nil}, "1.2-alpha"},
{Version{1, 0, 0, nil, []string{"build", "123"}}, "1+build.123"},
{Version{1, 2, 0, []PRVersion{prstr("alpha"), prstr("b-eta")}, []string{"123", "b-uild"}}, "1.2-alpha.b-eta+123.b-uild"},
}

func TestStringer(t *testing.T) {
Expand Down

0 comments on commit faf4d07

Please sign in to comment.