Skip to content

Commit

Permalink
Add GetOsAndSemverFromImage function. (#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gerrit91 authored Jul 23, 2024
1 parent 74e4064 commit 9ba8b42
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
35 changes: 35 additions & 0 deletions pkg/metal/images.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package metal

import (
"fmt"
"strings"

"github.com/Masterminds/semver/v3"
)

// GetOsAndSemverFromImage parses a metal-api image ID to OS and Semver or returns an error
//
// The last part must be the semantic version, valid ids are:
//
// ubuntu-19.04 => os: ubuntu version: 19.04
// ubuntu-19.04.20200408 => os: ubuntu version: 19.04.20200408
// ubuntu-small-19.04.20200408 => os: ubuntu-small version: 19.04.20200408
func GetOsAndSemverFromImage(id string) (string, *semver.Version, error) {
imageParts := strings.Split(id, "-")
if len(imageParts) < 2 {
return "", nil, fmt.Errorf("invalid format for os image, expected <os>-<major>.<minor>[.<patch>]: %s", id)
}

var (
parts = len(imageParts) - 1
os = strings.Join(imageParts[:parts], "-")
version = strings.Join(imageParts[parts:], "")
)

v, err := semver.NewVersion(version)
if err != nil {
return "", nil, err
}

return os, v, nil
}
63 changes: 63 additions & 0 deletions pkg/metal/images_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package metal

import (
"fmt"
"testing"

"github.com/Masterminds/semver/v3"
"github.com/google/go-cmp/cmp"
"github.com/metal-stack/metal-lib/pkg/testcommon"
)

func TestGetOsAndSemverFromImage(t *testing.T) {
tests := []struct {
name string
id string
want string
wantSemver *semver.Version
wantErr error
}{
{
name: "shorthand syntax",
id: "ubuntu-19.04",
want: "ubuntu",
wantSemver: semver.MustParse("19.04"),
},
{
name: "fqn syntax",
id: "ubuntu-19.04.20200408",
want: "ubuntu",
wantSemver: semver.MustParse("19.04.20200408"),
},
{
name: "dashes in os variant",
id: "ubuntu-slim-19.04.20200408",
want: "ubuntu-slim",
wantSemver: semver.MustParse("19.04.20200408"),
},
{
name: "no version contained",
id: "ubuntu",
wantErr: fmt.Errorf("invalid format for os image, expected <os>-<major>.<minor>[.<patch>]: ubuntu"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
v, sem, err := GetOsAndSemverFromImage(tt.id)

if diff := cmp.Diff(err, tt.wantErr, testcommon.ErrorStringComparer()); diff != "" {
t.Errorf("error diff (+got -want):\n %s", diff)
}
if err != nil {
return
}

if diff := cmp.Diff(v, tt.want); diff != "" {
t.Errorf("diff (+got -want):\n %s", diff)
}
if diff := cmp.Diff(sem, tt.wantSemver); diff != "" {
t.Errorf("diff (+got -want):\n %s", diff)
}
})
}
}

0 comments on commit 9ba8b42

Please sign in to comment.