diff --git a/CLAUDE.md b/CLAUDE.md index 1f66eb71..ea8bb1b7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,7 +80,7 @@ The CLI operates as a wrapper around a legacy PHP CLI: **Commands**: `commands/` - `root.go`: Root command that sets up the Cobra CLI and delegates to legacy CLI when needed - Native Go commands: init, list, version, config:install, project:convert, completion, lint, and with Go auth (below): auth:browser-login (login), auth:api-token-login, auth:logout (logout), auth:token -- `lint.go`: Native config linter, `lint` (also `validate`; registered under the namespaced name `app:config-validate`). Validates Flex (`.upsun`) and Fixed (`.platform`) config in `pkg/lint`, reporting all errors at once. It looks for those names only, so it is not registered in CLIs configured with other names. `pkg/lint` and `pkg/registry` are public because other Upsun projects import them; their API is not covered by semantic versioning. The Flex JSON schema and the image registry come from meta.upsun.com (`make update-schema`, `make update-registry`): schema changes are made in the upsun/meta repository first. Fixed config is checked with the same schema, patched by `internal/schema/fixed-overlay.json` (a JSON Merge Patch adding Fixed-only keys such as `disk`) +- `lint.go`: Native config linter, `lint` (also `validate`; registered under the namespaced name `app:config-validate`). Validates Flex (`.upsun`) and Fixed (`.platform`) config in `pkg/lint`, reporting all errors at once. It looks for those names only, so it is not registered in CLIs configured with other names. `pkg/lint` and `pkg/registry` are public because other Upsun projects import them; their API is not covered by semantic versioning. The Flex JSON schema and the image registry (including composable image channels) come from meta.upsun.com (`make update-schema`, `make update-registry`): schema changes are made in the upsun/meta repository first. A version newer than the registry's (e.g. a new composable channel) is a warning, not an error, so that older CLIs accept it. Fixed config is checked with the same schema, patched by `internal/schema/fixed-overlay.json` (a JSON Merge Patch adding Fixed-only keys such as `disk`) - Unrecognized commands are passed to the legacy PHP CLI **Configuration**: `internal/config/` diff --git a/pkg/lint/fixed_test.go b/pkg/lint/fixed_test.go index b3fe95db..c6ff833a 100644 --- a/pkg/lint/fixed_test.go +++ b/pkg/lint/fixed_test.go @@ -102,7 +102,7 @@ web: name: "container features", files: map[string]string{ ".platform.app.yaml": `name: myapp -type: "composable:25.11" +type: "composable:26.05" container_profile: HIGH_CPU stack: runtimes: ["php@8.4"] @@ -194,7 +194,7 @@ authorizations: name: "composable image with type and stack", files: map[string]string{ ".platform.app.yaml": `name: myapp -type: "composable:25.11" +type: "composable:26.05" stack: {runtimes: ["php@8.3"]}`, }, wantNoErr: true, @@ -203,7 +203,7 @@ stack: {runtimes: ["php@8.3"]}`, name: "composable image with an empty stack", files: map[string]string{ ".platform.app.yaml": `name: myapp -type: "composable:25.11" +type: "composable:26.05" stack: []`, }, wantNoErr: true, @@ -212,7 +212,7 @@ stack: []`, name: "composable image with a stack list", files: map[string]string{ ".platform.app.yaml": `name: myapp -type: "composable:25.11" +type: "composable:26.05" stack: ["php@8.3"]`, }, wantErrors: []string{"applications.myapp.stack: Array must have at most 0 items"}, diff --git a/pkg/lint/linter_test.go b/pkg/lint/linter_test.go index 23cea30f..80465cd6 100644 --- a/pkg/lint/linter_test.go +++ b/pkg/lint/linter_test.go @@ -173,7 +173,7 @@ tasks: - type: env action: view composed: - type: composable:25.11 + type: composable:26.05 stack: {runtimes: ["python@3.14"]} run: command: python run.py @@ -313,12 +313,12 @@ tasks: content: ` applications: listed: - type: composable:25.11 + type: composable:26.05 stack: runtimes: ["php@8.4", {"nodejs@24": {}}] packages: [yarn, {package: jq, channel: unstable}] scalar: - type: composable:25.11 + type: composable:26.05 stack: runtimes: php@8.4 packages: yarn @@ -333,13 +333,13 @@ routes: content: ` applications: empty_list: - type: composable:25.11 + type: composable:26.05 stack: [] empty_map: - type: composable:25.11 + type: composable:26.05 stack: {} empty_runtimes: - type: composable:25.11 + type: composable:26.05 stack: {runtimes: [], packages: []} classic: type: php:8.4 @@ -380,7 +380,7 @@ routes: content: ` applications: app: - type: composable:25.11 + type: composable:26.05 stack: {runtimes: ["php@8.4"]} egress: runtime: @@ -402,7 +402,7 @@ applications: content: ` applications: app: - type: composable:25.11 + type: composable:26.05 stack: ["php@8.4"] `, wantErrors: `Linter errors: diff --git a/pkg/lint/testdata/registry.json b/pkg/lint/testdata/registry.json index 2053ec17..5d01e291 100644 --- a/pkg/lint/testdata/registry.json +++ b/pkg/lint/testdata/registry.json @@ -43,6 +43,19 @@ ] } }, + "composable": { + "name": "Composable image", + "type": "composable", + "runtime": true, + "versions": { + "supported": [ + "26.05" + ], + "retired": [ + "25.11" + ] + } + }, "dotnet": { "description": "ASP.NET 5 application container.", "repo_name": "dotnet", @@ -490,62 +503,6 @@ ] } }, - "mysql": { - "description": "A manufacture-based container for MariaDB", - "repo_name": "mariadb", - "disk": true, - "docs": { - "relationship_name": "mysql", - "service_name": "mysql", - "url": "/add-services/mysql.html" - }, - "endpoint": "mysql", - "min_disk_size": 256, - "name": "MariaDB/MySQL", - "runtime": false, - "type": "mysql", - "versions": { - "deprecated": [ - "10.2", - "10.1", - "10.0", - "5.5" - ], - "supported": [ - "11.0", - "10.11", - "10.6", - "10.5", - "10.4", - "10.3" - ] - }, - "versions-dedicated-gen-2": { - "supported": [ - "10.5 Galera", - "10.4 Galera", - "10.3 Galera" - ], - "deprecated": [ - "10.2 Galera", - "10.1 Galera", - "10.0 Galera" - ] - }, - "versions-dedicated-gen-3": { - "supported": [ - "10.11 Galera", - "10.6 Galera", - "10.5 Galera", - "10.4 Galera", - "10.3 Galera" - ], - "deprecated": [ - "10.2 Galera", - "10.1 Galera" - ] - } - }, "memcached": { "description": "Memcached service.", "repo_name": "memcached", @@ -638,6 +595,62 @@ ] } }, + "mysql": { + "description": "A manufacture-based container for MariaDB", + "repo_name": "mariadb", + "disk": true, + "docs": { + "relationship_name": "mysql", + "service_name": "mysql", + "url": "/add-services/mysql.html" + }, + "endpoint": "mysql", + "min_disk_size": 256, + "name": "MariaDB/MySQL", + "runtime": false, + "type": "mysql", + "versions": { + "deprecated": [ + "10.2", + "10.1", + "10.0", + "5.5" + ], + "supported": [ + "11.0", + "10.11", + "10.6", + "10.5", + "10.4", + "10.3" + ] + }, + "versions-dedicated-gen-2": { + "supported": [ + "10.5 Galera", + "10.4 Galera", + "10.3 Galera" + ], + "deprecated": [ + "10.2 Galera", + "10.1 Galera", + "10.0 Galera" + ] + }, + "versions-dedicated-gen-3": { + "supported": [ + "10.11 Galera", + "10.6 Galera", + "10.5 Galera", + "10.4 Galera", + "10.3 Galera" + ], + "deprecated": [ + "10.2 Galera", + "10.1 Galera" + ] + } + }, "network-storage": { "description": "", "repo_name": "network-storage", diff --git a/pkg/lint/types.go b/pkg/lint/types.go index 03989e38..6700983a 100644 --- a/pkg/lint/types.go +++ b/pkg/lint/types.go @@ -3,6 +3,7 @@ package lint import ( "fmt" "slices" + "strconv" "strings" "github.com/upsun/cli/pkg/registry" @@ -12,7 +13,7 @@ import ( func checkTypes(cfg *config, reg registry.Registry) *Result { result := &Result{} - // check reports an error, or a warning for a retired version, at path. + // check reports an error, or a warning for a retired or newer version, at path. check := func(path, t string, runtime bool) { warning, err := checkType(t, reg, runtime) if err != nil { @@ -76,7 +77,8 @@ func checkTypes(cfg *config, reg registry.Registry) *Result { } // checkType validates an image type and version. It returns a warning for a -// retired version, or an error if the type or version is not allowed. +// retired version or an unknown one that could be newer, or an error if the +// type or version is not allowed. func checkType(t string, reg registry.Registry, runtime bool) (string, error) { if t == "" { return "", fmt.Errorf("type cannot be empty") @@ -114,6 +116,13 @@ func checkType(t string, reg registry.Registry, runtime bool) (string, error) { return "", fmt.Errorf("version '%s' is not precise enough for type '%s'%s", version, imageType, mustBeOneOf) } + // A version newer than all known ones may have been released since the registry was generated. + if len(img.Versions.Supported) > 0 { + if newest := slices.MaxFunc(allVersions, registry.CompareVersions); isNextVersion(version, newest) { + return fmt.Sprintf("unknown version '%s' of type '%s' (the newest known is %s)", + version, imageType, newest), nil + } + } return "", fmt.Errorf("version '%s' is not supported for type '%s'%s", version, imageType, mustBeOneOf) } @@ -133,3 +142,48 @@ func hasMajorVersion(l []string, v string) bool { } return false } + +// isNextVersion reports whether v could be a version released after newest. It +// must have as many numeric parts, and zero-padded parts as wide as newest's +// (e.g. 26.05). +// At the first part that differs, it must be at most one higher for the major +// part, and at most 12 higher for others (e.g. month-numbered versions, from +// 26.05 to 26.11). This leaves typos such as "84", "8.44" or "8.06" for "8.4" +// as errors. +func isNextVersion(v, newest string) bool { + vParts, newestParts := strings.Split(v, "."), strings.Split(newest, ".") + if len(vParts) != len(newestParts) { + return false + } + for i, p := range vParts { + if p == "" || strings.Trim(p, "0123456789") != "" { + return false + } + if n := newestParts[i]; (isZeroPadded(p) || isZeroPadded(n)) && len(p) != len(n) { + return false + } + } + for i, p := range vParts { + if p == newestParts[i] { + continue + } + vn, err := strconv.Atoi(p) + if err != nil { + return false + } + newestN, err := strconv.Atoi(newestParts[i]) + if err != nil { + return false + } + maxStep := 12 + if i == 0 { + maxStep = 1 + } + return vn > newestN && vn-newestN <= maxStep + } + return false +} + +func isZeroPadded(p string) bool { + return len(p) > 1 && p[0] == '0' +} diff --git a/pkg/lint/types_test.go b/pkg/lint/types_test.go index 4b8d2457..f25cb7ee 100644 --- a/pkg/lint/types_test.go +++ b/pkg/lint/types_test.go @@ -80,10 +80,10 @@ services: }, { name: "composable_without_stack", - content: fmt.Sprintf(` + content: ` applications: foo: - type: composable:%s`, registry.ChannelStable), + type: composable:26.05`, expectErrorMessage: `Linter warnings: - applications.foo: 'stack' should be specified when using a composable image`, }, @@ -189,3 +189,110 @@ services: Path: "services.unknown.type", Message: "version '9.0' is not supported for type 'elasticsearch'", }) } + +func TestCheckTypes_NewerVersion(t *testing.T) { + reg := registry.Registry{ + "composable": {Type: "composable", IsRuntime: true, Versions: registry.VersionInfo{ + Supported: []string{"26.05"}, + Retired: []string{"25.11"}, + }}, + "php": {Type: "php", IsRuntime: true, Versions: registry.VersionInfo{ + Supported: []string{"8.5", "8.4"}, + Legacy: []string{"5.4"}, + }}, + "nixos": {Type: "nixos", IsRuntime: true, Versions: registry.VersionInfo{Supported: []string{"26.11"}}}, + "python": {Type: "python", IsRuntime: true, Versions: registry.VersionInfo{Supported: []string{"3.14"}}}, + "clickhouse": {Type: "clickhouse", Versions: registry.VersionInfo{Supported: []string{"26.8"}}}, + "frankenphp": {Type: "frankenphp", IsRuntime: true, Versions: registry.VersionInfo{Supported: []string{"1.8.5"}}}, + "elasticsearch": {Type: "elasticsearch", Versions: registry.VersionInfo{Retired: []string{"7.2"}}}, + } + unknown := func(v, t, newest string) string { + return fmt.Sprintf("unknown version '%s' of type '%s' (the newest known is %s)", v, t, newest) + } + + cases := []struct { + name string + t string + service bool + warning string + err string + }{ + {name: "newer_channel", t: "composable:26.11", + warning: unknown("26.11", "composable", "26.05")}, + {name: "newer_minor", t: "php:8.6", + warning: unknown("8.6", "php", "8.5")}, + {name: "newer_major", t: "php:9.0", + warning: unknown("9.0", "php", "8.5")}, + {name: "newer_composable_major", t: "composable:27.05", warning: unknown("27.05", "composable", "26.05")}, + {name: "two_digit_minor", t: "php:8.10", warning: unknown("8.10", "php", "8.5")}, + {name: "major_after_two_digit_minor", t: "python:4.0", warning: unknown("4.0", "python", "3.14")}, + {name: "month_numbered", t: "clickhouse:26.10", service: true, warning: unknown("26.10", "clickhouse", "26.8")}, + {name: "two_digit_patch", t: "frankenphp:1.8.10", warning: unknown("1.8.10", "frankenphp", "1.8.5")}, + {name: "minor_too_far_ahead", t: "php:8.18", + err: "version '8.18' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "typo", t: "php:84", + err: "version '84' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "two_majors_ahead", t: "php:10.0", + err: "version '10.0' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "more_parts", t: "php:8.6.1", + err: "version '8.6.1' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "signed", t: "php:+9.0", + err: "version '+9.0' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "overflow", t: "php:99999999999999999999.0", + err: "version '99999999999999999999.0' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "digits_8_44", t: "php:8.44", + err: "version '8.44' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "digits_8_06", t: "php:8.06", + err: "version '8.06' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "digits_08_6", t: "php:08.6", + err: "version '08.6' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "digits_26_055", t: "composable:26.055", + err: "version '26.055' is not supported for type 'composable'; it must be exactly one of: 26.05"}, + {name: "digits_26_5", t: "composable:26.5", + err: "version '26.5' is not supported for type 'composable'; it must be exactly one of: 26.05"}, + {name: "malformed_9_x", t: "php:9.x", + err: "version '9.x' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "malformed_9_", t: "php:9.", + err: "version '9.' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "malformed_9_latest", t: "php:9.latest", + err: "version '9.latest' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "malformed_9_0000", t: "php:9.0000", + err: "version '9.0000' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "composable_27_abc", t: "composable:27.abc", + err: "version '27.abc' is not supported for type 'composable'; it must be exactly one of: 26.05"}, + {name: "composable_26_6", t: "composable:26.6", + err: "version '26.6' is not supported for type 'composable'; it must be exactly one of: 26.05"}, + {name: "composable_26_011", t: "composable:26.011", + err: "version '26.011' is not supported for type 'composable'; it must be exactly one of: 26.05"}, + {name: "zero_padded_after_rollover", t: "nixos:27.05", + warning: unknown("27.05", "nixos", "26.11")}, + {name: "zero_padded", t: "composable:26.08", warning: unknown("26.08", "composable", "26.05")}, + {name: "older_unknown", t: "composable:25.08", + err: "version '25.08' is not supported for type 'composable'; it must be exactly one of: 26.05"}, + {name: "imprecise", t: "php:8", + err: "version '8' is not precise enough for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "not_numeric", t: "php:latest", + err: "version 'latest' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "empty", t: "php", + err: "version '' is not supported for type 'php'; it must be exactly one of: 8.5, 8.4"}, + {name: "no_supported_versions", t: "elasticsearch:9.0", service: true, + err: "version '9.0' is not supported for type 'elasticsearch'"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + yaml, path := "applications:\n app:\n type: "+c.t+"\n stack: []", "applications.app.type" + if c.service { + yaml, path = "services:\n db:\n type: "+c.t, "services.db.type" + } + cfg, err := lint.DecodeConfig(yaml) + require.NoError(t, err) + result := lint.CheckTypes(cfg, reg) + if c.warning != "" { + assert.Empty(t, result.Errors) + assert.Equal(t, []lint.Issue{{Path: path, Message: c.warning}}, result.Warnings) + } else { + assert.Equal(t, []lint.Issue{{Path: path, Message: c.err}}, result.Errors) + } + }) + } +} diff --git a/pkg/registry/gen.go b/pkg/registry/gen.go index eed7c58f..914187e7 100644 --- a/pkg/registry/gen.go +++ b/pkg/registry/gen.go @@ -1,7 +1,8 @@ //go:build ignore -// Command gen fetches the container image registry from meta.upsun.com and -// writes registry.json in the format consumed by the registry package. +// Command gen fetches the container image registry and the composable image +// channels from meta.upsun.com, and writes registry.json in the format consumed +// by the registry package. // // Run it with: go run gen.go (or `go generate ./pkg/registry`). package main @@ -11,17 +12,19 @@ import ( "fmt" "net/http" "os" - "sort" - "strconv" - "strings" + "slices" "time" "github.com/upsun/cli/pkg/registry" ) -const imagesURL = "https://meta.upsun.com/images" +const ( + imagesURL = "https://meta.upsun.com/images" + composableURL = "https://meta.upsun.com/composable" +) -// metaImage is the shape of an image entry served by meta.upsun.com/images. +// metaImage is the shape of an image entry served by meta.upsun.com/images, and +// of the composable image served by meta.upsun.com/composable. type metaImage struct { Name string `json:"name"` Service bool `json:"service"` @@ -41,19 +44,19 @@ func main() { func run() error { client := &http.Client{Timeout: 30 * time.Second} - resp, err := client.Get(imagesURL) - if err != nil { + var images map[string]metaImage + if err := fetch(client, imagesURL, &images); err != nil { return err } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("unexpected status %s from %s", resp.Status, imagesURL) - } - - var images map[string]metaImage - if err := json.NewDecoder(resp.Body).Decode(&images); err != nil { + var composable metaImage + if err := fetch(client, composableURL, &composable); err != nil { return err } + if len(composable.Versions) == 0 { + return fmt.Errorf("no versions found at %s", composableURL) + } + composable.Name = "Composable image" + images["composable"] = composable reg := make(registry.Registry, len(images)) for typeName, img := range images { @@ -89,29 +92,21 @@ func run() error { return os.WriteFile("registry.json", append(out, '\n'), 0o644) } +func fetch(client *http.Client, url string, v any) error { + resp, err := client.Get(url) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status %s from %s", resp.Status, url) + } + return json.NewDecoder(resp.Body).Decode(v) +} + // sortVersionsDescending sorts version strings newest-first (e.g. 8.3 before 8.1). func sortVersionsDescending(versions []string) { - sort.Slice(versions, func(i, j int) bool { - return compareVersions(versions[i], versions[j]) > 0 + slices.SortFunc(versions, func(a, b string) int { + return registry.CompareVersions(b, a) }) } - -// compareVersions compares dotted numeric version strings, falling back to -// string comparison for non-numeric parts. -func compareVersions(a, b string) int { - pa, pb := strings.Split(a, "."), strings.Split(b, ".") - for i := 0; i < len(pa) && i < len(pb); i++ { - na, ea := strconv.Atoi(pa[i]) - nb, eb := strconv.Atoi(pb[i]) - if ea == nil && eb == nil { - if na != nb { - return na - nb - } - continue - } - if c := strings.Compare(pa[i], pb[i]); c != 0 { - return c - } - } - return len(pa) - len(pb) -} diff --git a/pkg/registry/model_test.go b/pkg/registry/model_test.go index d96c1e9d..5ff9c207 100644 --- a/pkg/registry/model_test.go +++ b/pkg/registry/model_test.go @@ -2,7 +2,6 @@ package registry_test import ( "encoding/json" - "fmt" "testing" "github.com/stretchr/testify/assert" @@ -27,9 +26,9 @@ func TestVersionInfo_UnmarshalJSON(t *testing.T) { }, { name: "string_version", - json: fmt.Sprintf(`%q`, registry.ChannelStable), + json: `"26.05"`, expected: registry.VersionInfo{ - Supported: []string{registry.ChannelStable}, + Supported: []string{"26.05"}, }, }, { diff --git a/pkg/registry/registry.go b/pkg/registry/registry.go index 9ccbf3e5..cf1a10bd 100644 --- a/pkg/registry/registry.go +++ b/pkg/registry/registry.go @@ -6,10 +6,8 @@ import ( "sync" ) -// ChannelStable is the current stable NixOS channel, used for composable images. -const ChannelStable = "25.11" - -// registry.json is generated from https://meta.upsun.com/images by gen.go. +// registry.json is generated from https://meta.upsun.com/images and +// https://meta.upsun.com/composable by gen.go. // //go:generate go run gen.go //go:embed registry.json @@ -67,14 +65,6 @@ func clean(reg Registry) { Versions: VersionInfo{Supported: []string{"8"}}, } } - if _, ok := reg["composable"]; !ok { - reg["composable"] = Image{ - Name: "Composable image", - Type: "composable", - Versions: VersionInfo{Supported: []string{ChannelStable}}, - IsRuntime: true, - } - } if _, ok := reg["redis-persistent"]; !ok { // Treat "redis-persistent" as a copy of "redis". if redis, ok := reg["redis"]; ok { diff --git a/pkg/registry/registry.json b/pkg/registry/registry.json index e07b86da..45f1d2c7 100644 --- a/pkg/registry/registry.json +++ b/pkg/registry/registry.json @@ -37,6 +37,22 @@ ] } }, + "composable": { + "name": "Composable image", + "type": "composable", + "runtime": true, + "versions": { + "supported": [ + "26.05" + ], + "retired": [ + "25.11", + "25.05", + "24.11", + "24.05" + ] + } + }, "dotnet": { "name": "C#/.Net Core", "type": "dotnet", diff --git a/pkg/registry/registry_test.go b/pkg/registry/registry_test.go index 310ea679..b8314a1e 100644 --- a/pkg/registry/registry_test.go +++ b/pkg/registry/registry_test.go @@ -54,3 +54,12 @@ func TestRegistry_ReplicaVersions(t *testing.T) { }) } } + +// Composable image channels come from meta.upsun.com/composable. +func TestRegistry_Composable(t *testing.T) { + reg, err := registry.Load() + assert.NoError(t, err) + assert.Contains(t, reg, "composable") + assert.True(t, reg["composable"].IsRuntime) + assert.NotEmpty(t, reg["composable"].Versions.Supported) +} diff --git a/pkg/registry/version.go b/pkg/registry/version.go new file mode 100644 index 00000000..4afe89be --- /dev/null +++ b/pkg/registry/version.go @@ -0,0 +1,27 @@ +package registry + +import ( + "strconv" + "strings" +) + +// CompareVersions compares dotted version strings, numerically where both +// parts are numbers, returning a negative number if a < b, positive if a > b, +// or 0 if they are equal. +func CompareVersions(a, b string) int { + pa, pb := strings.Split(a, "."), strings.Split(b, ".") + for i := 0; i < len(pa) && i < len(pb); i++ { + na, ea := strconv.Atoi(pa[i]) + nb, eb := strconv.Atoi(pb[i]) + if ea == nil && eb == nil { + if na != nb { + return na - nb + } + continue + } + if c := strings.Compare(pa[i], pb[i]); c != 0 { + return c + } + } + return len(pa) - len(pb) +} diff --git a/pkg/registry/version_test.go b/pkg/registry/version_test.go new file mode 100644 index 00000000..9ee71c77 --- /dev/null +++ b/pkg/registry/version_test.go @@ -0,0 +1,28 @@ +package registry_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/upsun/cli/pkg/registry" +) + +func TestCompareVersions(t *testing.T) { + cases := []struct { + a, b string + expected int + }{ + {"8.4", "8.4", 0}, + {"8.10", "8.4", 1}, + {"8.4", "9.0", -1}, + {"26.05", "25.11", 1}, + {"8.4", "8.4.1", -1}, + {"17", "16", 1}, + } + for _, c := range cases { + t.Run(c.a+"_"+c.b, func(t *testing.T) { + assert.Equal(t, c.expected, max(-1, min(1, registry.CompareVersions(c.a, c.b)))) + }) + } +}