Debian Codegraph @

pkg/cel/library/semverlib.go

raw
1 /*
2 Copyright 2024 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package library
18
19 import (
20 "errors"
21 "math"
22 "strings"
23
24 "github.com/blang/semver/v4"
25 "github.com/google/cel-go/cel"
26 "github.com/google/cel-go/common/types"
27 "github.com/google/cel-go/common/types/ref"
28
29 apiservercel "k8s.io/apiserver/pkg/cel"
30 )
31
32 // Semver provides a CEL function library extension for [semver.Version].
33 //
34 // semver
35 //
36 // Converts a string to a semantic version or results in an error if the string is not a valid semantic version. Refer
37 // to semver.org documentation for information on accepted patterns.
38 // An optional "normalize" argument can be passed to enable normalization. Normalization removes any "v" prefix, adds a
39 // 0 minor and patch numbers to versions with only major or major.minor components specified, and removes any leading 0s.
40 // semver(<string>) <Semver>
41 // semver(<string>, <bool>) <Semver>
42 //
43 // Examples:
44 //
45 // semver('1.0.0') // returns a Semver
46 // semver('0.1.0-alpha.1') // returns a Semver
47 // semver('200K') // error
48 // semver('Three') // error
49 // semver('Mi') // error
50 // semver('v1.0.0', true) // Applies normalization to remove the leading "v". Returns a Semver of "1.0.0".
51 // semver('1.0', true) // Applies normalization to add the missing patch version. Returns a Semver of "1.0.0"
52 // semver('01.01.01', true) // Applies normalization to remove leading zeros. Returns a Semver of "1.1.1"
53 //
54 // isSemver
55 //
56 // Returns true if a string is a valid Semver. isSemver returns true if and
57 // only if semver does not result in error.
58 // An optional "normalize" argument can be passed to enable normalization. Normalization removes any "v" prefix, adds a
59 // 0 minor and patch numbers to versions with only major or major.minor components specified, and removes any leading 0s.
60 //
61 // isSemver( <string>) <bool>
62 // isSemver( <string>, <bool>) <bool>
63 //
64 // Examples:
65 //
66 // isSemver('1.0.0') // returns true
67 // isSemver('hello') // returns false
68 // isSemver('v1.0') // returns false (leading "v" is not allowed unless normalization is enabled)
69 // isSemver('v1.0', true) // Applies normalization to remove leading "v". returns true
70 // semver('1.0', true) // Applies normalization to add the missing patch version. Returns true
71 // semver('01.01.01', true) // Applies normalization to remove leading zeros. Returns true
72 //
73 // Conversion to Scalars:
74 //
75 // - major/minor/patch: return the major version number as int64.
76 //
77 // <Semver>.major() <int>
78 //
79 // Examples:
80 //
81 // semver("1.2.3").major() // returns 1
82 //
83 // Comparisons
84 //
85 // - isGreaterThan: Returns true if and only if the receiver is greater than the operand
86 //
87 // - isLessThan: Returns true if and only if the receiver is less than the operand
88 //
89 // - compareTo: Compares receiver to operand and returns 0 if they are equal, 1 if the receiver is greater, or -1 if the receiver is less than the operand
90 //
91 //
92 // <Semver>.isLessThan(<semver>) <bool>
93 // <Semver>.isGreaterThan(<semver>) <bool>
94 // <Semver>.compareTo(<semver>) <int>
95 //
96 // Examples:
97 //
98 // semver("1.2.3").compareTo(semver("1.2.3")) // returns 0
99 // semver("1.2.3").compareTo(semver("2.0.0")) // returns -1
100 // semver("1.2.3").compareTo(semver("0.1.2")) // returns 1
101
102 func SemverLib(options ...SemverOption) cel.EnvOption {
103 semverLib := &semverLibType{}
104 for _, o := range options {
105 semverLib = o(semverLib)
106 }
107 return cel.Lib(semverLib)
108 }
109
110 var semverLib = &semverLibType{version: math.MaxUint32} // include all versions
111
112 type semverLibType struct {
113 version uint32
114 }
115
116 // StringsOption is a functional interface for configuring the strings library.
117 type SemverOption func(*semverLibType) *semverLibType
118
119 func SemverVersion(version uint32) SemverOption {
120 return func(lib *semverLibType) *semverLibType {
121 lib.version = version
122 return lib
123 }
124 }
125
126 func (*semverLibType) LibraryName() string {
127 return "kubernetes.Semver"
128 }
129
130 func (*semverLibType) Types() []*cel.Type {
131 return []*cel.Type{apiservercel.SemverType}
132 }
133
134 func (lib *semverLibType) declarations() map[string][]cel.FunctionOpt {
135 fnOpts := map[string][]cel.FunctionOpt{
136 "semver": {
137 cel.Overload("string_to_semver", []*cel.Type{cel.StringType}, apiservercel.SemverType, cel.UnaryBinding((stringToSemver))),
138 },
139 "isSemver": {
140 cel.Overload("is_semver_string", []*cel.Type{cel.StringType}, cel.BoolType, cel.UnaryBinding(isSemver)),
141 },
142 "isGreaterThan": {
143 cel.MemberOverload("semver_is_greater_than", []*cel.Type{apiservercel.SemverType, apiservercel.SemverType}, cel.BoolType, cel.BinaryBinding(semverIsGreaterThan)),
144 },
145 "isLessThan": {
146 cel.MemberOverload("semver_is_less_than", []*cel.Type{apiservercel.SemverType, apiservercel.SemverType}, cel.BoolType, cel.BinaryBinding(semverIsLessThan)),
147 },
148 "compareTo": {
149 cel.MemberOverload("semver_compare_to", []*cel.Type{apiservercel.SemverType, apiservercel.SemverType}, cel.IntType, cel.BinaryBinding(semverCompareTo)),
150 },
151 "major": {
152 cel.MemberOverload("semver_major", []*cel.Type{apiservercel.SemverType}, cel.IntType, cel.UnaryBinding(semverMajor)),
153 },
154 "minor": {
155 cel.MemberOverload("semver_minor", []*cel.Type{apiservercel.SemverType}, cel.IntType, cel.UnaryBinding(semverMinor)),
156 },
157 "patch": {
158 cel.MemberOverload("semver_patch", []*cel.Type{apiservercel.SemverType}, cel.IntType, cel.UnaryBinding(semverPatch)),
159 },
160 }
161 if lib.version >= 1 {
162 fnOpts["semver"] = append(fnOpts["semver"], cel.Overload("string_bool_to_semver", []*cel.Type{cel.StringType, cel.BoolType}, apiservercel.SemverType, cel.BinaryBinding((stringToSemverNormalize))))
163 fnOpts["isSemver"] = append(fnOpts["isSemver"], cel.Overload("is_semver_string_bool", []*cel.Type{cel.StringType, cel.BoolType}, cel.BoolType, cel.BinaryBinding(isSemverNormalize)))
164 }
165 return fnOpts
166 }
167
168 func (s *semverLibType) CompileOptions() []cel.EnvOption {
169 // Defined in this function to avoid an initialization order problem.
170 semverLibraryDecls := s.declarations()
171 options := make([]cel.EnvOption, 0, len(semverLibraryDecls))
172 for name, overloads := range semverLibraryDecls {
173 options = append(options, cel.Function(name, overloads...))
174 }
175 return options
176 }
177
178 func (*semverLibType) ProgramOptions() []cel.ProgramOption {
179 return []cel.ProgramOption{}
180 }
181
182 func isSemver(arg ref.Val) ref.Val {
183 return isSemverNormalize(arg, types.Bool(false))
184 }
185 func isSemverNormalize(arg ref.Val, normalizeArg ref.Val) ref.Val {
186 str, ok := arg.Value().(string)
187 if !ok {
188 return types.MaybeNoSuchOverloadErr(arg)
189 }
190
191 normalize, ok := normalizeArg.Value().(bool)
192 if !ok {
193 return types.MaybeNoSuchOverloadErr(arg)
194 }
195
196 // Using semver/v4 here is okay because this function isn't
197 // used to validate the Kubernetes API. In the CEL base library
198 // we would have to use the regular expression from
199 // pkg/apis/resource/structured/namedresources/validation/validation.go.
200 var err error
201 if normalize {
202 _, err = normalizeAndParse(str)
203 } else {
204 _, err = semver.Parse(str)
205 }
206 if err != nil {
207 return types.Bool(false)
208 }
209
210 return types.Bool(true)
211 }
212
213 func stringToSemver(arg ref.Val) ref.Val {
214 return stringToSemverNormalize(arg, types.Bool(false))
215 }
216 func stringToSemverNormalize(arg ref.Val, normalizeArg ref.Val) ref.Val {
217 str, ok := arg.Value().(string)
218 if !ok {
219 return types.MaybeNoSuchOverloadErr(arg)
220 }
221
222 normalize, ok := normalizeArg.Value().(bool)
223 if !ok {
224 return types.MaybeNoSuchOverloadErr(arg)
225 }
226
227 // Using semver/v4 here is okay because this function isn't
228 // used to validate the Kubernetes API. In the CEL base library
229 // we would have to use the regular expression from
230 // pkg/apis/resource/structured/namedresources/validation/validation.go
231 // first before parsing.
232 var err error
233 var v semver.Version
234 if normalize {
235 v, err = normalizeAndParse(str)
236 } else {
237 v, err = semver.Parse(str)
238 }
239 if err != nil {
240 return types.WrapErr(err)
241 }
242
243 return apiservercel.Semver{Version: v}
244 }
245
246 func semverMajor(arg ref.Val) ref.Val {
247 v, ok := arg.Value().(semver.Version)
248 if !ok {
249 return types.MaybeNoSuchOverloadErr(arg)
250 }
251 return types.Int(v.Major)
252 }
253
254 func semverMinor(arg ref.Val) ref.Val {
255 v, ok := arg.Value().(semver.Version)
256 if !ok {
257 return types.MaybeNoSuchOverloadErr(arg)
258 }
259 return types.Int(v.Minor)
260 }
261
262 func semverPatch(arg ref.Val) ref.Val {
263 v, ok := arg.Value().(semver.Version)
264 if !ok {
265 return types.MaybeNoSuchOverloadErr(arg)
266 }
267 return types.Int(v.Patch)
268 }
269
270 func semverIsGreaterThan(arg ref.Val, other ref.Val) ref.Val {
271 v, ok := arg.Value().(semver.Version)
272 if !ok {
273 return types.MaybeNoSuchOverloadErr(arg)
274 }
275
276 v2, ok := other.Value().(semver.Version)
277 if !ok {
278 return types.MaybeNoSuchOverloadErr(arg)
279 }
280
281 return types.Bool(v.Compare(v2) == 1)
282 }
283
284 func semverIsLessThan(arg ref.Val, other ref.Val) ref.Val {
285 v, ok := arg.Value().(semver.Version)
286 if !ok {
287 return types.MaybeNoSuchOverloadErr(arg)
288 }
289
290 v2, ok := other.Value().(semver.Version)
291 if !ok {
292 return types.MaybeNoSuchOverloadErr(arg)
293 }
294
295 return types.Bool(v.Compare(v2) == -1)
296 }
297
298 func semverCompareTo(arg ref.Val, other ref.Val) ref.Val {
299 v, ok := arg.Value().(semver.Version)
300 if !ok {
301 return types.MaybeNoSuchOverloadErr(arg)
302 }
303
304 v2, ok := other.Value().(semver.Version)
305 if !ok {
306 return types.MaybeNoSuchOverloadErr(arg)
307 }
308
309 return types.Int(v.Compare(v2))
310 }
311
312 // normalizeAndParse removes any "v" prefix, adds a 0 minor and patch numbers to versions with
313 // only major or major.minor components specified, and removes any leading 0s.
314 // normalizeAndParse is based on semver.ParseTolerant but does not trim extra whitespace and is
315 // guaranteed to not change behavior in the future.
316 func normalizeAndParse(s string) (semver.Version, error) {
317 s = strings.TrimPrefix(s, "v")
318
319 // Split into major.minor.(patch+pr+meta)
320 parts := strings.SplitN(s, ".", 3)
321 // Remove leading zeros.
322 for i, p := range parts {
323 if len(p) > 1 {
324 p = strings.TrimLeft(p, "0")
325 if len(p) == 0 || !strings.ContainsAny(p[0:1], "0123456789") {
326 p = "0" + p
327 }
328 parts[i] = p
329 }
330 }
331
332 // Fill up shortened versions.
333 if len(parts) < 3 {
334 if strings.ContainsAny(parts[len(parts)-1], "+-") {
335 return semver.Version{}, errors.New("short version cannot contain PreRelease/Build meta data")
336 }
337 for len(parts) < 3 {
338 parts = append(parts, "0")
339 }
340 }
341 s = strings.Join(parts, ".")
342
343 return semver.Parse(s)
344 }