Skip to content

Commit

Permalink
claircore: add FromSemver
Browse files Browse the repository at this point in the history
Signed-off-by: RTann <[email protected]>
  • Loading branch information
RTann committed Jan 17, 2024
1 parent 88a4186 commit 1a1957f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
12 changes: 12 additions & 0 deletions version.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"bytes"
"strconv"
"strings"

"github.com/Masterminds/semver"
)

// Version describes a revision of some sort that is ordered correctly within
Expand All @@ -21,6 +23,16 @@ func VersionSort(vs []Version) func(int, int) bool {
return func(i, j int) bool { return vs[i].Compare(&vs[j]) == -1 }
}

// FromSemver is the SemVer to claircore.Version mapping used by this package.
func FromSemver(v *semver.Version) (out Version) {
out.Kind = `semver`
// Leave a leading epoch, for good measure.
out.V[1] = int32(v.Major())
out.V[2] = int32(v.Minor())
out.V[3] = int32(v.Patch())
return out
}

// MarshalText implments encoding.TextMarshaler.
func (v *Version) MarshalText() ([]byte, error) {
if v.Kind == "" {
Expand Down
35 changes: 35 additions & 0 deletions version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package claircore
import (
"testing"

"github.com/Masterminds/semver"
"github.com/google/go-cmp/cmp"
)

Expand Down Expand Up @@ -98,3 +99,37 @@ func TestVersionMarshal(t *testing.T) {
t.Run(tc.Name, tc.MarshalTest)
}
}

func TestFromSemver(t *testing.T) {
testcases := []struct {
name string
semver *semver.Version
want Version
}{
{
name: "0.3.0",
semver: semver.MustParse("0.3.0"),
want: Version{
Kind: `semver`,
V: [...]int32{0, 0, 3, 0, 0, 0, 0, 0, 0, 0},
},
},
{
name: "1.1.6",
semver: semver.MustParse("1.1.6"),
want: Version{
Kind: `semver`,
V: [...]int32{0, 1, 1, 6, 0, 0, 0, 0, 0, 0},
},
},
}

for _, tt := range testcases {
t.Run(tt.name, func(t *testing.T) {
got := FromSemver(tt.semver)
if !cmp.Equal(tt.want, got) {
t.Error(cmp.Diff(tt.want, got))
}
})
}
}

0 comments on commit 1a1957f

Please sign in to comment.