Proposal: add Coerce method to Version type which takes a string into SemVer if possible
andriisoldatenko opened this issue · comments
something like:
// Coerce a string into SemVer if possible
func Coerce(version string) *semver.Version {
v, err := semver.NewVersion(version)
if err != nil {
fmt.Println(err)
}
coerceVer, err := semver.NewVersion(fmt.Sprintf("%d.%d.%d", v.Major(), v.Minor(), v.Patch()))
if err != nil {
fmt.Println(err)
}
return coerceVer
}
func Test_coerce(t *testing.T) {
assert.Equal(t, "1.10.5", coerce("1.10.5-11-alpine3.10-onbuild").String())
assert.Equal(t, "1.10.5", coerce("1.10.5").String())
assert.Equal(t, "1.10.12", coerce("1.10.12-buster").String())
}
inspired by node.js version https://www.npmjs.com/package/semver
Let me know if i can fire PR.
What's the use case for Coerce? semver already has a NewVersion
and StrictNewVersion
. The first performs a minimal coerce and the second does not. For an example, see https://play.golang.org/p/zqjlWuyO0JT.
If you look at examples the coerce JS function works on... you'll see that NewVersion
will throw an error. Like 42.6.7.9.3-alpha
. This is where it gets interesting. In the Test_coerce
function all 3 examples that go through coerce
are valid SemVer. The two with pre-releases should not match the versions that don't have a pre-release.
What are you looking for a coerce function to do? Just perform the same duty the JS one does? I'm curious of the problem to be solved.
What's the use case for Coerce? semver already has a
NewVersion
andStrictNewVersion
. The first performs a minimal coerce and the second does not. For an example, see https://play.golang.org/p/zqjlWuyO0JT.If you look at examples the coerce JS function works on... you'll see that
NewVersion
will throw an error. Like42.6.7.9.3-alpha
. This is where it gets interesting. In theTest_coerce
function all 3 examples that go throughcoerce
are valid SemVer. The two with pre-releases should not match the versions that don't have a pre-release.What are you looking for a coerce function to do? Just perform the same duty the JS one does? I'm curious of the problem to be solved.
@mattfarina thanks for quick reply!
Use case is pretty simple: you have list of strings versions ["1.10.5-11-alpine3.10-onbuild", "1.10.5", "1.10.12-buster"]
and valid min SemVer: e.g. 1.10.12
and goal is to filter list by that version and return:
["1.10.12-buster"]
yeah looks like it was my fault:
package main
import (
"fmt"
"github.com/Masterminds/semver/v3"
)
func main() {
versions := []string{"1.10.5-11-alpine3.10-onbuild", "1.10.5", "1.10.12-buster", "1.10.12"}
_ = versions
targetVer, _ := semver.NewVersion("1.10.12-alpine")
for _, version := range versions {
v, _ := semver.NewVersion(version)
if i := v.Compare(targetVer); i >= 0 {
fmt.Println(v.String())
}
}
}
1.10.12-buster
1.10.12
so it works as expected. https://play.golang.org/p/If5d3Rmgozr