1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-30 19:35:06 +00:00

Adds JMESPath filter for returning cron expression for absolute time (#5814)

* time_to_cron

Signed-off-by: Vishal Choudhary <contactvishaltech@gmail.com>

* tests

Signed-off-by: Vishal Choudhary <contactvishaltech@gmail.com>

* Update pkg/engine/jmespath/functions.go

Signed-off-by: shuting <shutting06@gmail.com>

* fix linter

Signed-off-by: ShutingZhao <shuting@nirmata.com>

Signed-off-by: Vishal Choudhary <contactvishaltech@gmail.com>
Signed-off-by: shuting <shutting06@gmail.com>
Signed-off-by: ShutingZhao <shuting@nirmata.com>
Co-authored-by: shuting <shuting@nirmata.com>
Co-authored-by: shuting <shutting06@gmail.com>
This commit is contained in:
Vishal Choudhary 2023-01-06 12:57:57 +05:30 committed by GitHub
parent 7258f7ae3c
commit e9d2c00c16
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 0 deletions

View file

@ -81,6 +81,7 @@ var (
objectFromLists = "object_from_lists"
random = "random"
x509_decode = "x509_decode"
timeToCron = "time_to_cron"
)
const (
@ -490,6 +491,17 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpObject},
Note: "decodes an x.509 certificate to an object. you may also use this in conjunction with `base64_decode` jmespath function to decode a base64-encoded certificate",
},
{
Entry: &gojmespath.FunctionEntry{
Name: timeToCron,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
Handler: jpTimeToCron,
},
ReturnType: []JpType{JpString},
Note: "converts an absolute time (RFC 3339) to a cron expression (string).",
},
}
}
@ -1094,3 +1106,28 @@ func jpX509Decode(arguments []interface{}) (interface{}, error) {
return res, nil
}
func jpTimeToCron(arguments []interface{}) (interface{}, error) {
var err error
ts, err := validateArg("", arguments, 0, reflect.String)
if err != nil {
return nil, err
}
var t time.Time
t, err = time.Parse(time.RFC3339, ts.String())
if err != nil {
return nil, err
}
t = t.UTC()
var cron string = ""
cron += strconv.Itoa(t.Minute()) + " "
cron += strconv.Itoa(t.Hour()) + " "
cron += strconv.Itoa(t.Day()) + " "
cron += strconv.Itoa(int(t.Month())) + " "
cron += strconv.Itoa(int(t.Weekday()))
return cron, nil
}

View file

@ -1549,3 +1549,33 @@ UFOZZVoELaasWS559wy8og39Eq21dDMynb8Bndn/
})
}
}
func Test_TimeToCron(t *testing.T) {
testCases := []struct {
test string
expectedResult string
}{
{
test: "time_to_cron('2023-02-02T15:04:05Z')",
expectedResult: "4 15 2 2 4",
},
{
test: "time_to_cron('2023-02-02T15:04:05-07:00')",
expectedResult: "4 22 2 2 4",
},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) {
query, err := New(tc.test)
assert.NilError(t, err)
res, err := query.Search("")
assert.NilError(t, err)
result, ok := res.(string)
assert.Assert(t, ok)
assert.Equal(t, result, tc.expectedResult)
})
}
}