|
| 1 | +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 2 | +// or more contributor license agreements. Licensed under the Elastic License; |
| 3 | +// you may not use this file except in compliance with the Elastic License. |
| 4 | + |
| 5 | +package semantic |
| 6 | + |
| 7 | +import ( |
| 8 | + "errors" |
| 9 | + "fmt" |
| 10 | + |
| 11 | + "github.com/Masterminds/semver/v3" |
| 12 | + |
| 13 | + "github.com/elastic/package-spec/v3/code/go/internal/fspath" |
| 14 | + "github.com/elastic/package-spec/v3/code/go/internal/pkgpath" |
| 15 | + "github.com/elastic/package-spec/v3/code/go/pkg/specerrors" |
| 16 | +) |
| 17 | + |
| 18 | +var ( |
| 19 | + errInvalidAgentVersionCondition = fmt.Errorf("invalid agent.version condition") |
| 20 | + errAgentVersionIncorrectType = fmt.Errorf("manifest agent version is not a string") |
| 21 | +) |
| 22 | + |
| 23 | +// ValidateMinimumAgentVersion checks that the package manifest includes the agent.version condition. |
| 24 | +func ValidateMinimumAgentVersion(fsys fspath.FS) specerrors.ValidationErrors { |
| 25 | + manifest, err := readManifest(fsys) |
| 26 | + if err != nil { |
| 27 | + return specerrors.ValidationErrors{specerrors.NewStructuredError(err, specerrors.UnassignedCode)} |
| 28 | + } |
| 29 | + |
| 30 | + agentVersionCondition, err := getAgentVersionCondition(*manifest) |
| 31 | + if err != nil { |
| 32 | + return specerrors.ValidationErrors{specerrors.NewStructuredError(err, specerrors.UnassignedCode)} |
| 33 | + } |
| 34 | + |
| 35 | + if agentVersionCondition != "" { |
| 36 | + if _, err := semver.NewConstraint(agentVersionCondition); err != nil { |
| 37 | + return specerrors.ValidationErrors{specerrors.NewStructuredError(errors.Join(err, errInvalidAgentVersionCondition), specerrors.UnassignedCode)} |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return nil |
| 42 | +} |
| 43 | + |
| 44 | +func getAgentVersionCondition(manifest pkgpath.File) (string, error) { |
| 45 | + val, err := manifest.Values("$.conditions[\"agent.version\"]") |
| 46 | + if err != nil { |
| 47 | + val, err = manifest.Values("$.conditions.agent.version") |
| 48 | + if err != nil { |
| 49 | + return "", nil |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + sVal, ok := val.(string) |
| 54 | + if !ok { |
| 55 | + return "", errAgentVersionIncorrectType |
| 56 | + } |
| 57 | + |
| 58 | + return sVal, nil |
| 59 | +} |
0 commit comments