diff --git a/SOURCEGRAPH.md b/SOURCEGRAPH.md index cbeea3a..527aa22 100644 --- a/SOURCEGRAPH.md +++ b/SOURCEGRAPH.md @@ -41,6 +41,26 @@ This file lists every way `main` differs from upstream v0.8.2. Merging from upst - Tests: `TestRequiredKeySubstrings`, and `TestRequiredKeySubstringsHoldWhereSelected`, which checks each clause against the keys of documents the path selects from, with and without `ignoreCase`, under the default and Sourcegraph options (`pkg/jsonpath/required_keys_test.go`). - Upstream: not proposed. +### Version comparison function `semver()` + +`semver(value, range)` in a filter is true when both arguments are versions or version ranges and some version is in both. Workiva asked for semver comparisons; versions in config files are often not strict semver, so the parser is loose and a value it can't read is false, not an error. + +- Ranges use npm's syntax: `1.2.3`, `=1.2.3`, `<`, `<=`, `>`, `>=`, `^`, `~`, wildcards (`1.x`, `1.2.*`, `*`), hyphen ranges (`1.2 - 1.4`), comparators separated by spaces or commas that all must hold (`>=1.2 <2`, `>=7.4,<8.0`), and alternatives separated by `||` or Composer's `|`. +- Versions may start with `v`, have fewer than three parts, a prerelease (with or without a hyphen, as in `3.12.0b1`) and `+build` metadata, which is ignored. A version with fewer parts, such as `v4` or `18`, means every version that starts with it, as in npm, so `actions/checkout@v4` matches `<4.2` and `4.1.7` but not `<4`. +- Before parsing, text up to the last `@` (`actions/checkout@v4`, `pnpm@9.15.0`, `npm:react@^18`), a pnpm lockfile peer suffix (`18.2.0(react@18.2.0)`), and the `npm:` and `workspace:` protocols are dropped. +- Both arguments are parsed the same way, so the function is symmetric. With a range on one side and a version on the other, it tests whether the range accepts the version (Workiva's `accepts(18.3.1)`). With two ranges, it tests whether they overlap, so `semver(@, '<1.4.2')` selects a dependency that may resolve below 1.4.2, and `!semver(@, '<1.4.2')` one that can't (or that isn't a version). +- Versions are totally ordered as in semver: a prerelease sorts before its release. Unlike npm, a range's comparators also match prereleases: `2.0.0-rc.1` matches `<2.0.0`. A partial upper bound excludes the prereleases of its first version, as npm desugars it: `2.0.0-rc.1` doesn't match `<2`. +- Not versions, and therefore false: `catalog:`, `latest`, branch names, commit SHAs, URLs, paths, Docker tags such as `node:18-alpine`, four-part versions such as `1.2.3.4`, and Ruby's `~>`. A query argument must select one string or number; numbers are read as written, so YAML's `python-version: 3.10` is `3.10`. A missing member, booleans, objects and arrays are false. +- A string literal argument that doesn't parse, or a non-string literal, is a parse error. Like `match()` and `search()`, the result can't be compared. `config.WithStrictRFC9535()` rejects it as an unknown function. +- Code: `pkg/jsonpath/semver.go`; `functionTypeSemver` (`pkg/jsonpath/filter.go`); `isFunctionName` (`pkg/jsonpath/token/token.go`); the `functionTypeSemver` cases of `parseFunctionExpr` and `parseComparable` (`pkg/jsonpath/parser.go`); `functionExpr.semver` and `semverArg` (`pkg/jsonpath/yaml_eval.go`); `functionExpr.requiredKeys` gives the member names of both query arguments (`pkg/jsonpath/required_keys.go`). +- Examples, for `dependencies: {react: "^17.0.2", left-pad: "github:foo/left-pad", lodash: "4.17.21"}` and `steps: [{uses: actions/checkout@v3}, {run: make}, {uses: actions/setup-node@v4}]`: + - `$.dependencies[?semver(@, '<18')]` returns `"^17.0.2"` and `"4.17.21"`. + - `$.dependencies[?!semver(@, '<18')]` returns `"github:foo/left-pad"`. + - `$.dependencies[?semver(@, '17.0.5')]` returns `"^17.0.2"`, the range that accepts 17.0.5. + - `$.steps[?semver(@.uses, '<4')].uses` returns `"actions/checkout@v3"`. +- Tests: `TestSemver` (real-world values and ranges, as a literal and from the document), `TestSemverFilter` and `TestSemverParse` (`pkg/jsonpath/semver_test.go`, run under the default and Sourcegraph options); semver cases in `TestRequiredKeySubstrings` and `TestRequiredKeySubstringsHoldWhereSelected`. +- Upstream: not proposed. + ## Bug fixes ### A leading `!` binds only to the next basic expression diff --git a/pkg/jsonpath/filter.go b/pkg/jsonpath/filter.go index 2d6606c..fecbf5f 100644 --- a/pkg/jsonpath/filter.go +++ b/pkg/jsonpath/filter.go @@ -164,6 +164,8 @@ const ( functionTypeMatch functionTypeSearch functionTypeValue + // Sourcegraph extension, see SOURCEGRAPH.md + functionTypeSemver // JSONPath Plus type selector functions functionTypeIsNull functionTypeIsBoolean @@ -180,6 +182,7 @@ var functionTypeMap = map[string]functionType{ "match": functionTypeMatch, "search": functionTypeSearch, "value": functionTypeValue, + "semver": functionTypeSemver, } // typeSelectorFunctionMap maps JSONPath Plus type selector function names to their types. diff --git a/pkg/jsonpath/parser.go b/pkg/jsonpath/parser.go index 80428b7..29e564d 100644 --- a/pkg/jsonpath/parser.go +++ b/pkg/jsonpath/parser.go @@ -521,6 +521,8 @@ func (p *JSONPath) parseComparable() (*comparable, error) { return nil, p.parseFailure(&p.tokens[p.current], "match result cannot be compared") } else if funcExpr.funcType == functionTypeSearch { return nil, p.parseFailure(&p.tokens[p.current], "search result cannot be compared") + } else if funcExpr.funcType == functionTypeSemver { + return nil, p.parseFailure(&p.tokens[p.current], "semver result cannot be compared") } return &comparable{functionExpr: funcExpr}, nil } @@ -693,6 +695,33 @@ func (p *JSONPath) parseFunctionExpr() (*functionExpr, error) { return nil, err } args = append(args, arg) + case functionTypeSemver: + if !p.config.JSONPathPlusEnabled() { + return nil, p.parseFailure(&p.tokens[p.current-2], "unknown function: "+functionName) + } + for i := 0; i < 2; i++ { + if i == 1 { + if p.tokens[p.current].Token != token.COMMA { + return nil, p.parseFailure(&p.tokens[p.current], "expected ','") + } + p.current++ + } + arg, err := p.parseFunctionArgument(false) + if err != nil { + return nil, err + } + // A version written in the expression must parse, unlike values + // in the document, which are false when they don't. + if arg.literal != nil { + if arg.literal.string == nil { + return nil, p.parseFailure(&p.tokens[p.current-1], "semver arguments must be strings or queries") + } + if _, ok := parseVersionRange(*arg.literal.string); !ok { + return nil, p.parseFailure(&p.tokens[p.current-1], "invalid version or range in semver: "+*arg.literal.string) + } + } + args = append(args, arg) + } default: return nil, p.parseFailure(&p.tokens[p.current], "unknown function: "+functionName) } diff --git a/pkg/jsonpath/required_keys.go b/pkg/jsonpath/required_keys.go index 69f9c34..f1ba5a4 100644 --- a/pkg/jsonpath/required_keys.go +++ b/pkg/jsonpath/required_keys.go @@ -139,8 +139,18 @@ func (q *filterQuery) requiredKeys(ignoreCase bool) [][]string { } // requiredKeys of search() and match(), which are false unless their first -// argument is a string. +// argument is a string, and semver(), which is false unless both arguments +// are. func (e *functionExpr) requiredKeys(ignoreCase bool) [][]string { + if e.funcType == functionTypeSemver { + var clauses [][]string + for _, arg := range e.args { + if arg.filterQuery != nil { + clauses = append(clauses, arg.filterQuery.requiredKeys(ignoreCase)...) + } + } + return clauses + } if (e.funcType != functionTypeSearch && e.funcType != functionTypeMatch) || len(e.args) != 2 { return nil } diff --git a/pkg/jsonpath/required_keys_test.go b/pkg/jsonpath/required_keys_test.go index badc731..b274cd9 100644 --- a/pkg/jsonpath/required_keys_test.go +++ b/pkg/jsonpath/required_keys_test.go @@ -37,6 +37,8 @@ func TestRequiredKeySubstrings(t *testing.T) { `$..[?@.a && @.b || @property == 'c']`: "a|c", `$['a',?@.b]`: "a|b", `$..[?!!@.a]`: "a", + `$..[?semver(@.version, '<2')]`: "version", + `$..[?semver(@.a, @.b)]`: "a,b", // Conditions that can be true without the key. `$..[?@property == 'react' || @ == 1]`: "", @@ -56,6 +58,8 @@ func TestRequiredKeySubstrings(t *testing.T) { `$..[?@property =~ /\d+/]`: "", `$.steps[?@property == '0']`: "steps", `$..[?@property =~ /^1/]`: "", + `$..[?!semver(@.version, '<2')]`: "", + `$..[?semver(@, '<2')]`: "", } for expr, want := range tests { path, err := NewPath(expr, config.WithPropertyNameExtension(), config.WithLazyContextTracking()) @@ -108,6 +112,8 @@ func TestRequiredKeySubstringsHoldWhereSelected(t *testing.T) { `$..[?@ == 'react']`, `$..[?@property =~ /sdk/i]`, `$..[?search(@property, '(?i)^react$') || @property == 'vue']`, + `$..steps[?semver(@.uses, '>=4')]`, + `$..[?semver(@.react, '18.3.1')]`, } configs := map[string][]config.Option{ "default": nil, diff --git a/pkg/jsonpath/semver.go b/pkg/jsonpath/semver.go new file mode 100644 index 0000000..204bff9 --- /dev/null +++ b/pkg/jsonpath/semver.go @@ -0,0 +1,371 @@ +package jsonpath + +import ( + "cmp" + "strconv" + "strings" +) + +// This file implements the semver() function: a best-effort comparison of the +// loose versions and npm-style ranges found in package.json files, lockfiles +// and GitHub Actions workflows. See SOURCEGRAPH.md for the accepted syntax. + +// version is a version with three numeric parts and an optional prerelease. +// Build metadata is dropped when parsing, since it does not affect order. +type version struct { + nums [3]uint64 + pre []string // nil for a release +} + +// compareVersions orders versions as semver does: by their numeric parts, +// then a prerelease before its release, then by prerelease identifiers. +func compareVersions(a, b version) int { + for i := range a.nums { + if c := cmp.Compare(a.nums[i], b.nums[i]); c != 0 { + return c + } + } + switch { + case a.pre == nil && b.pre == nil: + return 0 + case a.pre == nil: + return 1 + case b.pre == nil: + return -1 + } + for i := 0; i < len(a.pre) && i < len(b.pre); i++ { + an, aErr := strconv.ParseUint(a.pre[i], 10, 64) + bn, bErr := strconv.ParseUint(b.pre[i], 10, 64) + var c int + switch { + case aErr == nil && bErr == nil: + c = cmp.Compare(an, bn) + case aErr == nil: + c = -1 + case bErr == nil: + c = 1 + default: + c = strings.Compare(a.pre[i], b.pre[i]) + } + if c != 0 { + return c + } + } + return cmp.Compare(len(a.pre), len(b.pre)) +} + +// bound is one end of an interval. An unset bound is unbounded. +type bound struct { + v version + inclusive bool + set bool +} + +type interval struct{ lo, hi bound } + +func (i interval) empty() bool { + if !i.lo.set || !i.hi.set { + return false + } + c := compareVersions(i.lo.v, i.hi.v) + return c > 0 || c == 0 && !(i.lo.inclusive && i.hi.inclusive) +} + +func (i interval) intersect(j interval) interval { + return interval{lo: tighter(i.lo, j.lo, 1), hi: tighter(i.hi, j.hi, -1)} +} + +// tighter returns the bound that excludes more: the greater lower bound +// (sign 1) or the lesser upper bound (sign -1). +func tighter(a, b bound, sign int) bound { + switch { + case !a.set: + return b + case !b.set: + return a + } + if c := compareVersions(a.v, b.v) * sign; c != 0 { + if c > 0 { + return a + } + return b + } + if !a.inclusive { + return a + } + return b +} + +// versionRange is the set of versions in any of its intervals. +type versionRange []interval + +func (r versionRange) overlaps(s versionRange) bool { + for _, i := range r { + for _, j := range s { + if !i.intersect(j).empty() { + return true + } + } + } + return false +} + +// parseVersionRange parses a version or range loosely. A value such as +// actions/checkout@v4 or pnpm@9.1.0 is read from after its last @, pnpm +// lockfiles' peer suffix in 18.2.0(react@18.2.0) is dropped, and so are the +// npm: and workspace: protocols. Alternatives are separated by || or, as in +// Composer, |. A version with fewer than three parts, such as v4 or 18.x, is +// the range of versions that start with it. +func parseVersionRange(s string) (versionRange, bool) { + if i := strings.IndexByte(s, '('); i >= 0 { + s = s[:i] + } + if i := strings.LastIndexByte(s, '@'); i >= 0 { + s = s[i+1:] + } + s = strings.TrimSpace(s) + s = strings.TrimPrefix(s, "npm:") + s = strings.TrimPrefix(s, "workspace:") + var r versionRange + for _, alt := range strings.Split(strings.ReplaceAll(s, "||", "|"), "|") { + i, ok := parseComparatorSet(alt) + if !ok { + return nil, false + } + r = append(r, i) + } + return r, true +} + +// parseComparatorSet parses comparators separated by spaces or commas, which +// all must hold, or a hyphen range such as 1.2 - 1.4. +func parseComparatorSet(s string) (interval, bool) { + var fields []string + pendingOp := "" + for _, f := range strings.FieldsFunc(s, func(r rune) bool { return r == ' ' || r == '\t' || r == ',' }) { + // Join an operator written apart from its version, as in ">= 1.2". + if strings.Trim(f, "<>=^~") == "" { + pendingOp += f + continue + } + fields = append(fields, pendingOp+f) + pendingOp = "" + } + if pendingOp != "" || len(fields) == 0 { + return interval{}, false + } + + if len(fields) == 3 && fields[1] == "-" { + from, ok1 := parsePartial(fields[0]) + to, ok2 := parsePartial(fields[2]) + if !ok1 || !ok2 { + return interval{}, false + } + var i interval + if from.n > 0 { + i.lo = bound{v: from.floor(), inclusive: true, set: true} + } + if to.n == 3 { + i.hi = bound{v: to.floor(), inclusive: true, set: true} + } else if to.n > 0 { + i.hi = bound{v: to.next(), set: true} + } + return i, true + } + + var res interval + for _, f := range fields { + i, ok := parseComparator(f) + if !ok { + return interval{}, false + } + res = res.intersect(i) + } + return res, true +} + +// parseComparator parses an operator (<, <=, >, >=, =, ==, ^ or ~, or none) +// followed by a version, with the meanings npm gives them. +func parseComparator(s string) (interval, bool) { + op := "" + for _, o := range []string{"<=", ">=", "==", "<", ">", "=", "^", "~"} { + if strings.HasPrefix(s, o) { + op, s = o, s[len(o):] + break + } + } + p, ok := parsePartial(s) + if !ok { + return interval{}, false + } + floor := bound{v: p.floor(), inclusive: true, set: true} + next := bound{v: p.next(), set: p.n < 3 && p.n > 0} + nothing := interval{lo: floor, hi: bound{v: p.floor(), set: true}} + switch op { + case "", "=", "==": + if p.n == 3 { + return interval{lo: floor, hi: floor}, true + } + if p.n == 0 { + return interval{}, true + } + return interval{lo: floor, hi: next}, true + case ">": + if p.n == 3 { + return interval{lo: bound{v: p.floor(), set: true}}, true + } + if p.n == 0 { + return nothing, true + } + next.inclusive = true + return interval{lo: next}, true + case ">=": + if p.n == 0 { + return interval{}, true + } + return interval{lo: floor}, true + case "<": + if p.n == 0 { + return nothing, true + } + hi := bound{v: p.floor(), set: true} + if p.n < 3 { + hi.v.pre = []string{"0"} + } + return interval{hi: hi}, true + case "<=": + if p.n == 3 { + return interval{hi: floor}, true + } + return interval{hi: next}, true + case "^": + if p.n == 0 { + return interval{}, true + } + var hi version + switch { + case p.nums[0] > 0 || p.n == 1: + hi.nums = [3]uint64{p.nums[0] + 1} + case p.nums[1] > 0 || p.n == 2: + hi.nums = [3]uint64{0, p.nums[1] + 1} + default: + hi.nums = [3]uint64{0, 0, p.nums[2] + 1} + } + hi.pre = []string{"0"} + return interval{lo: floor, hi: bound{v: hi, set: true}}, true + case "~": + if p.n == 0 { + return interval{}, true + } + hi := version{nums: [3]uint64{p.nums[0] + 1}, pre: []string{"0"}} + if p.n >= 2 { + hi.nums = [3]uint64{p.nums[0], p.nums[1] + 1} + } + return interval{lo: floor, hi: bound{v: hi, set: true}}, true + } + return interval{}, false +} + +// partial is a version that may stop early or end in a wildcard, such as 1, +// v1.2, 1.x or *. n is the number of numeric parts before the first +// wildcard or the end. +type partial struct { + nums [3]uint64 + n int + pre []string +} + +// floor is the lowest version that starts with p. +func (p partial) floor() version { + return version{nums: p.nums, pre: p.pre} +} + +// next is the lowest version above every version that starts with p, for +// 0 < n < 3: 2.0.0-0 for 1 and 1.3.0-0 for 1.2. +func (p partial) next() version { + v := version{pre: []string{"0"}} + if p.n == 1 { + v.nums = [3]uint64{p.nums[0] + 1} + } else { + v.nums = [3]uint64{p.nums[0], p.nums[1] + 1} + } + return v +} + +// parsePartial parses an optional v, up to three numeric or wildcard (x, X +// or *) parts, and, after three numeric parts, an optional prerelease and +// build metadata. The prerelease may follow without a hyphen when it starts +// with a letter, as in 3.12.0b1. +func parsePartial(s string) (partial, bool) { + var p partial + s = strings.TrimLeft(s, "vV") + wildcard := false + for i := 0; i < 3; i++ { + if s != "" && (s[0] == 'x' || s[0] == 'X' || s[0] == '*') { + wildcard = true + s = s[1:] + } else { + end := 0 + for end < len(s) && s[end] >= '0' && s[end] <= '9' { + end++ + } + if end == 0 { + return p, false + } + // 63 bits so that the next major or minor does not overflow. + num, err := strconv.ParseUint(s[:end], 10, 63) + if err != nil { + return p, false + } + s = s[end:] + if !wildcard { + p.nums[i] = num + p.n = i + 1 + } + } + if i == 2 || s == "" || s[0] != '.' { + break + } + s = s[1:] + } + + if build := strings.IndexByte(s, '+'); build >= 0 { + if !validIdentifiers(s[build+1:]) { + return p, false + } + s = s[:build] + } + if s == "" { + return p, true + } + if p.n < 3 { + return p, false + } + if s[0] == '-' { + s = s[1:] + } else if !isLetter(s[0]) { + return p, false + } + if !validIdentifiers(s) { + return p, false + } + p.pre = strings.Split(s, ".") + return p, true +} + +func isLetter(c byte) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' +} + +// validIdentifiers reports whether s is dot-separated non-empty identifiers +// of letters, digits and hyphens. +func validIdentifiers(s string) bool { + for _, id := range strings.Split(s, ".") { + if id == "" || strings.ContainsFunc(id, func(r rune) bool { + return !(r < 128 && (isLetter(byte(r)) || r >= '0' && r <= '9' || r == '-')) + }) { + return false + } + } + return true +} diff --git a/pkg/jsonpath/semver_test.go b/pkg/jsonpath/semver_test.go new file mode 100644 index 0000000..8613435 --- /dev/null +++ b/pkg/jsonpath/semver_test.go @@ -0,0 +1,236 @@ +package jsonpath + +import ( + "encoding/json" + "testing" + + "github.com/sourcegraph/jsonpath/pkg/jsonpath/config" + "github.com/stretchr/testify/assert" + "go.yaml.in/yaml/v4" +) + +var semverConfigs = map[string][]config.Option{ + "default": nil, + // The options Sourcegraph's jsonpath: search filter uses. + "sourcegraph": {config.WithPropertyNameExtension(), config.WithLazyContextTracking()}, +} + +// TestSemver checks semver(value, range) for versions and ranges as they are +// written in package.json files, lockfiles and GitHub Actions workflows. +func TestSemver(t *testing.T) { + tests := []struct { + value, rng string + want bool + }{ + // Exact versions, with the loose forms that config files use. + {"1.2.3", "1.2.3", true}, + {"1.2.3", "1.2.4", false}, + {"v1.2.3", "=1.2.3", true}, + {"V1.2.3", "==1.2.3", true}, + {"1.2.3", "<1.10.0", true}, // numeric, not text, order + {"1.10.0", "<1.9", false}, + {"1.2.3+build.5", "1.2.3", true}, + {"1.2.3", ">1.2.3", false}, + {"1.2.3", ">=1.2.3", true}, + {"1.2.3", "<=1.2.3", true}, + {"1.2.3", "<1.2.3", false}, + + // Prereleases sort before their release, by identifier. + {"2.0.0-rc.1", "<2.0.0", true}, + {"2.0.0-rc.1", ">=2.0.0", false}, + {"2.0.0-rc.10", ">2.0.0-rc.9", true}, // numeric identifiers + {"2.0.0-beta", "<2.0.0-alpha", false}, // text identifiers + {"2.0.0-1", "<2.0.0-alpha", true}, // numbers before text + {"2.0.0-rc.1", "<2.0.0-rc.1.1", true}, // shorter first + {"3.12.0b1", "<3.12.0", true}, // Python's prerelease without a hyphen + {"1.0.0rc1", ">=1.0.0-rc0", true}, + // A partial upper bound excludes the prereleases of its first version, + // as in npm: 2.0.0-rc.1 is a version 2. + {"2.0.0-rc.1", "<2", false}, + {"2.0.0-rc.1", "2", false}, + + // Versions with fewer parts are every version that starts with them. + {"actions/checkout@v4", ">=4", true}, + {"actions/checkout@v4", "<4", false}, + {"actions/checkout@v3", "<4", true}, + {"actions/checkout@v4", "4.1.7", true}, + {"actions/checkout@v4", "<4.2", true}, + {"actions/checkout@v4", ">=5", false}, + {"actions/setup-node@v4.0.2", "<4.1", true}, + {"18", "18.20.4", true}, + {"18", "19.0.0", false}, + {"16.x", ">=16.13.0", true}, + {"1.21.x", ">=1.22", false}, + {"3.x", "3.12", true}, + {"*", "<1", true}, + {"x", "99.0.0", true}, + + // Ranges select dependencies that may resolve to a matching version. + {"^17.0.2", "<18", true}, + {"^18.2.0", "<18", false}, + {"^18.2.0", "18.3.1", true}, // the range accepts 18.3.1 + {"^18.2.0", "19.0.0", false}, + {"^18", "18.0.0", true}, + {"^0.2.3", "0.2.9", true}, + {"^0.2.3", "0.3.0", false}, + {"^0.0.3", "0.0.4", false}, + {"^0.0", "0.0.9", true}, + {"^0.0", "0.1.0", false}, + {"~1.2.3", "1.2.9", true}, + {"~1.2.3", "1.3.0", false}, + {"~1.2", "1.2.0", true}, + {"~1", "1.9.0", true}, + {"~1", "2.0.0", false}, + {">=14.24.0", ">=20", true}, + {">=14.24.0", "<14", false}, + {">= 16", "16.0.0", true}, + {">=1.2.3 <2.0.0", "2.0.0", false}, + {">=1.2.3 <2.0.0", "1.9.9", true}, + {">=7.4,<8.0", "7.4.33", true}, + {">1.2", "1.2.9", false}, + {">1.2", "1.3.0", true}, + {"<=1.2", "1.2.9", true}, + {"<=1.2", "1.3.0", false}, + {"1.2.3 - 2.3.4", "2.3.4", true}, + {"1.2.3 - 2.3.4", "2.3.5", false}, + {"1.2 - 2.3", "2.3.9", true}, + {"1.2 - 2.3", "1.1.9", false}, + {"20 || 22 || 24", "21.0.0", false}, + {"20 || 22 || 24", "22.11.0", true}, + {"^7.4|^8.0", "8.2.0", true}, // Composer + {">=2 <1", "1.5.0", false}, + {">=2.17.0 <3.0.0", "^2.19.0", true}, // two ranges overlap + {">=2.17.0 <3.0.0", "^3.4.0", false}, + + // Lockfiles and package managers. + {"pnpm@9.15.0+sha512.76e2379760a4328ec4415815bcd6628dee727af3779aaa4c914e3944156c4299921a89f976381ee107d41f12cfa4b66681ca9c718f0668fa0831ed4c6d8ba56c", ">=9.12", true}, + {"18.2.0(react@18.2.0)", "<18.3", true}, // pnpm-lock.yaml + {"react-dom@18.2.0(react@18.2.0)", "18.2.0", true}, + {"npm:react@^18.2.0", "18.3.1", true}, + {"lodash@npm:^4.17.21", "4.17.20", false}, // a Yarn Berry key + {"workspace:^1.2.0", "<1.2", false}, + {"v5.4.21", "^5.4", true}, // composer.lock + + // Values that aren't versions are false, so their negation is true. + {"catalog:", "*", false}, + {"workspace:*", "<1", true}, + {"latest", "*", false}, + {"main", "*", false}, + {"lts/*", "*", false}, + {"github:foo/left-pad", "*", false}, + {"git+https://github.com/foo/bar.git#v1.2.3", "*", false}, + {"file:../shared", "*", false}, + {"actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3", "*", false}, + {"actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683", "*", false}, + {"docker://alpine:3.18", "*", false}, + {"./.github/actions/setup", "*", false}, + {"node:18-alpine", "*", false}, + {"1.2.3.4", "*", false}, + {"1.2-beta", "*", false}, + {"1.2.3-", "*", false}, + {"1.2.3+", "*", false}, + {"99999999999999999999.0.0", "*", false}, + {"", "*", false}, + {"~> 1.2", "*", false}, + {">=", "*", false}, + } + for name, opts := range semverConfigs { + for _, tt := range tests { + value, _ := json.Marshal(tt.value) + rng, _ := json.Marshal(tt.rng) + // The range as a literal, and as a value in the document. + for _, expr := range []string{ + `$[?semver(@.v, '` + tt.rng + `')]`, + `$[?semver(@.v, $.x.r)]`, + } { + doc := `{"x": {"v": ` + string(value) + `, "r": ` + string(rng) + `}}` + var node yaml.Node + assert.NoError(t, yaml.Unmarshal([]byte(doc), &node)) + path, err := NewPath(expr, opts...) + if !assert.NoError(t, err, expr) { + continue + } + got := len(path.Query(&node)) == 1 + assert.Equal(t, tt.want, got, "%s: semver(%q, %q)", name, tt.value, tt.rng) + } + } + } +} + +func TestSemverFilter(t *testing.T) { + yamlData := ` +python-version: 3.10 +node-version: 18 +enabled: true +dependencies: + react: "^17.0.2" + left-pad: "github:foo/left-pad" + jquery: "catalog:" + lodash: "4.17.21" +jobs: + build: + steps: + - uses: actions/checkout@v3 + - run: make + - uses: actions/setup-node@v4 +` + var node yaml.Node + assert.NoError(t, yaml.Unmarshal([]byte(yamlData), &node)) + + tests := []struct { + path string + expected []string + }{ + {`$.dependencies[?semver(@, '<18')]`, []string{"^17.0.2", "4.17.21"}}, + // Values that aren't versions are excluded by semver() and kept by its negation. + {`$.dependencies[?!semver(@, '<18')]`, []string{"github:foo/left-pad", "catalog:"}}, + {`$.dependencies[?semver(@, '<18') && @property != 'lodash']`, []string{"^17.0.2"}}, + {`$.jobs.*.steps[?semver(@.uses, '<4')].uses`, []string{"actions/checkout@v3"}}, + // A missing member is false. + {`$.jobs.*.steps[?!semver(@.uses, '<4')]['run','uses']`, []string{"make", "actions/setup-node@v4"}}, + // Numbers are read as written: YAML's 3.10 is 3.10, not 3.1. + {`$[?semver(@, '>=3.10 <4')]`, []string{"3.10"}}, + {`$[?semver(@, '18.20.4')]`, []string{"18"}}, + // Booleans, objects and arrays are not versions. + {`$[?semver(@, '*')]`, []string{"3.10", "18"}}, + {`$..[?semver(@, '*')]`, []string{"3.10", "18", "^17.0.2", "4.17.21", "actions/checkout@v3", "actions/setup-node@v4"}}, + } + for name, opts := range semverConfigs { + for _, tt := range tests { + t.Run(name+"/"+tt.path, func(t *testing.T) { + path, err := NewPath(tt.path, opts...) + assert.NoError(t, err) + var values []string + for _, r := range path.Query(&node) { + values = append(values, r.Value) + } + assert.Equal(t, tt.expected, values) + }) + } + } +} + +func TestSemverParse(t *testing.T) { + path, err := NewPath(`$[?semver(@, '>=1.2')]`) + assert.NoError(t, err) + assert.Equal(t, `$[?semver(@, '>=1.2')]`, path.String()) + + for expr, wantErr := range map[string]string{ + `$[?semver(@, 'catalog:')]`: "invalid version or range in semver: catalog:", + `$[?semver('latest', @)]`: "invalid version or range in semver: latest", + `$[?semver(@, 4)]`: "semver arguments must be strings or queries", + `$[?semver(@)]`: "expected ','", + `$[?semver(@, '1') == true]`: "", // rejected like search(@, '1') == true + `$[?semver(@, '1', '2')]`: "expected ')'", + } { + _, err := NewPath(expr) + if assert.Error(t, err, expr) { + assert.Contains(t, err.Error(), wantErr, expr) + } + } + + _, err = NewPath(`$[?semver(@, '1')]`, config.WithStrictRFC9535()) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), "unknown function: semver") + } +} diff --git a/pkg/jsonpath/token/token.go b/pkg/jsonpath/token/token.go index 94cd440..b6ba1f2 100644 --- a/pkg/jsonpath/token/token.go +++ b/pkg/jsonpath/token/token.go @@ -881,6 +881,9 @@ func isFunctionName(literal string) bool { // RFC 9535 standard functions case "length", "count", "match", "search", "value": return true + // Sourcegraph's version comparison extension + case "semver": + return true // JSONPath Plus type selector functions case "isNull", "isBoolean", "isNumber", "isString", "isArray", "isObject", "isInteger": return true diff --git a/pkg/jsonpath/yaml_eval.go b/pkg/jsonpath/yaml_eval.go index 30d7b58..f69406c 100644 --- a/pkg/jsonpath/yaml_eval.go +++ b/pkg/jsonpath/yaml_eval.go @@ -240,6 +240,40 @@ func (e functionExpr) search(idx index, node *yaml.Node, root *yaml.Node) litera return literal{bool: &matched} } +// semver is true when both arguments are versions or ranges, as parsed by +// parseVersionRange, and some version is in both. A value that is not a +// version, such as catalog: or main, is false rather than an error. +func (e functionExpr) semver(idx index, node *yaml.Node, root *yaml.Node) literal { + a, ok := e.semverArg(0, idx, node, root) + if !ok { + return literal{bool: &falseLit} + } + b, ok := e.semverArg(1, idx, node, root) + res := ok && a.overlaps(b) + return literal{bool: &res} +} + +// semverArg parses argument i as a version range. A query must select one +// string or number; numbers are read as written, so YAML's 3.10 is 3.10. +func (e functionExpr) semverArg(i int, idx index, node *yaml.Node, root *yaml.Node) (versionRange, bool) { + if q := e.args[i].filterQuery; q != nil { + nodes := q.Query(idx, node, root) + if len(nodes) != 1 || nodes[0].Kind != yaml.ScalarNode { + return nil, false + } + switch nodes[0].Tag { + case "!!str", "!!int", "!!float": + return parseVersionRange(nodes[0].Value) + } + return nil, false + } + arg := e.args[i].Eval(idx, node, root) + if !isStringArg(arg) { + return nil, false + } + return parseVersionRange(*arg.literal.string) +} + func (e functionExpr) value(idx index, node *yaml.Node, root *yaml.Node) literal { // 2.4.8. value() Function Extension // @@ -299,6 +333,8 @@ func (e functionExpr) Evaluate(idx index, node *yaml.Node, root *yaml.Node) lite return e.search(idx, node, root) case functionTypeValue: return e.value(idx, node, root) + case functionTypeSemver: + return e.semver(idx, node, root) // JSONPath Plus type selector functions case functionTypeIsNull: return e.isNull(idx, node, root)