-
Notifications
You must be signed in to change notification settings - Fork 23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Add Time configtype #1905
Open
rhino1998
wants to merge
12
commits into
main
Choose a base branch
from
feat/configtype-time
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+591
−8
Open
Changes from 2 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
7bc83b0
feat: Add Time configtype
rhino1998 6c6e1a6
cleanup
rhino1998 34a31d6
return zero time on nil Time
rhino1998 93f2449
add time type and fix zero value
rhino1998 852db5a
function typing
rhino1998 70a90a4
zero handling
rhino1998 3111bb1
use time.Time instead of func() time.Time
rhino1998 3c5a1ac
add ParseTime
rhino1998 26eea6b
new duration parsing
rhino1998 274a303
fix tests and add now
rhino1998 d5ce087
complex literals and better marshalling
rhino1998 99244f8
better test
rhino1998 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
package configtype | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"regexp" | ||
"time" | ||
|
||
"github.com/invopop/jsonschema" | ||
) | ||
|
||
type NowFunc func() time.Time | ||
|
||
// Time is a wrapper around time.Time that should be used in config | ||
// when a time type is required. We wrap the time.Time type so that | ||
// the spec can be extended in the future to support other types of times | ||
type Time struct { | ||
time time.Time | ||
duration time.Duration | ||
} | ||
|
||
func NewTime(t time.Time) Time { | ||
return Time{ | ||
time: t, | ||
} | ||
} | ||
|
||
func NewRelativeTime(d time.Duration) Time { | ||
return Time{ | ||
duration: d, | ||
} | ||
} | ||
|
||
var ( | ||
timeRFC3339Pattern = `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.(\d{3}|\d{6}|\d{9}))?(Z|((-|\+)\d{2}:\d{2}))$` | ||
timeRFC3339Regexp = regexp.MustCompile(timeRFC3339Pattern) | ||
|
||
datePattern = `^\d{4}-\d{2}-\d{2}$` | ||
dateRegexp = regexp.MustCompile(datePattern) | ||
|
||
timePattern = patternCases(timeRFC3339Pattern, datePattern, durationPattern) | ||
) | ||
|
||
func (Time) JSONSchema() *jsonschema.Schema { | ||
return &jsonschema.Schema{ | ||
Type: "string", | ||
Pattern: timePattern, | ||
Title: "CloudQuery configtype.Time", | ||
} | ||
} | ||
|
||
func (t *Time) UnmarshalJSON(b []byte) error { | ||
var s string | ||
if err := json.Unmarshal(b, &s); err != nil { | ||
return err | ||
} | ||
|
||
var err error | ||
switch { | ||
case timeRFC3339Regexp.MatchString(s): | ||
t.time, err = time.Parse(time.RFC3339, s) | ||
case dateRegexp.MatchString(s): | ||
t.time, err = time.Parse(time.DateOnly, s) | ||
case durationRegexp.MatchString(s): | ||
t.duration, err = time.ParseDuration(s) | ||
default: | ||
return fmt.Errorf("invalid time format: %s", s) | ||
} | ||
|
||
if err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (d *Time) MarshalJSON() ([]byte, error) { | ||
if !d.time.IsZero() { | ||
return json.Marshal(d.time) | ||
} | ||
|
||
return json.Marshal(d.duration.String()) | ||
} | ||
|
||
func (t *Time) Time(nowFunc NowFunc) time.Time { | ||
if !t.time.IsZero() { | ||
return t.time | ||
} | ||
|
||
return nowFunc().Add(t.duration) | ||
} | ||
|
||
func (t Time) IsRelative() bool { | ||
return t.time.IsZero() | ||
} | ||
|
||
// Equal compares two Time structs. Note that relative and fixed times are never equal | ||
func (t Time) Equal(other Time) bool { | ||
return t.time.Equal(other.time) && t.duration == other.duration | ||
} | ||
|
||
func (t Time) String() string { | ||
if !t.time.IsZero() { | ||
return t.time.String() | ||
} | ||
return t.duration.String() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
package configtype_test | ||
|
||
import ( | ||
"encoding/json" | ||
"math/rand" | ||
"testing" | ||
"time" | ||
|
||
"github.com/cloudquery/plugin-sdk/v4/configtype" | ||
"github.com/cloudquery/plugin-sdk/v4/plugin" | ||
"github.com/google/go-cmp/cmp" | ||
"github.com/invopop/jsonschema" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestTime(t *testing.T) { | ||
nowTime, _ := time.Parse(time.RFC3339Nano, time.RFC3339Nano) | ||
now := func() time.Time { | ||
return nowTime | ||
} | ||
|
||
cases := []struct { | ||
give string | ||
want time.Time | ||
}{ | ||
{"1ns", nowTime.Add(1 * time.Nanosecond)}, | ||
{"20s", nowTime.Add(20 * time.Second)}, | ||
{"-50m30s", nowTime.Add(-50*time.Minute - 30*time.Second)}, | ||
{"2021-09-01T00:00:00Z", time.Date(2021, 9, 1, 0, 0, 0, 0, time.UTC)}, | ||
{"2021-09-01T00:00:00.123Z", time.Date(2021, 9, 1, 0, 0, 0, 123000000, time.UTC)}, | ||
{"2021-09-01T00:00:00.123456Z", time.Date(2021, 9, 1, 0, 0, 0, 123456000, time.UTC)}, | ||
{"2021-09-01T00:00:00.123456789Z", time.Date(2021, 9, 1, 0, 0, 0, 123456789, time.UTC)}, | ||
{"2021-09-01T00:00:00.123+02:00", time.Date(2021, 9, 1, 0, 0, 0, 123000000, time.FixedZone("CET", 2*60*60))}, | ||
{"2021-09-01T00:00:00.123456+02:00", time.Date(2021, 9, 1, 0, 0, 0, 123456000, time.FixedZone("CET", 2*60*60))}, | ||
{"2021-09-01T00:00:00.123456789+02:00", time.Date(2021, 9, 1, 0, 0, 0, 123456789, time.FixedZone("CET", 2*60*60))}, | ||
{"2021-09-01", time.Date(2021, 9, 1, 0, 0, 0, 0, time.UTC)}, | ||
} | ||
for _, tc := range cases { | ||
var d configtype.Time | ||
err := json.Unmarshal([]byte(`"`+tc.give+`"`), &d) | ||
if err != nil { | ||
t.Fatalf("error calling Unmarshal(%q): %v", tc.give, err) | ||
} | ||
computedTime := d.Time(now) | ||
if !computedTime.Equal(tc.want) { | ||
t.Errorf("Unmarshal(%q) = %v, want %v", tc.give, computedTime, tc.want) | ||
} | ||
} | ||
} | ||
|
||
func TestTime_Comparability(t *testing.T) { | ||
tim1 := time.Now() | ||
tim2 := tim1.Add(1 * time.Second) | ||
|
||
cases := []struct { | ||
give configtype.Time | ||
compare configtype.Time | ||
equal bool | ||
}{ | ||
{configtype.NewRelativeTime(0), configtype.NewRelativeTime(0), true}, | ||
{configtype.NewRelativeTime(0), configtype.NewRelativeTime(1), false}, | ||
{configtype.NewTime(tim1), configtype.NewTime(tim1), false}, | ||
{configtype.NewTime(tim1), configtype.NewTime(tim2), true}, | ||
// relative and fixed times are never equal | ||
{configtype.NewTime(tim1), configtype.NewRelativeTime(1), false}, | ||
} | ||
for _, tc := range cases { | ||
if (tc.give == tc.compare) != tc.equal { | ||
t.Errorf("comparing %v and %v should be %v", tc.give, tc.compare, tc.equal) | ||
} | ||
|
||
diff := cmp.Diff(tc.give, tc.compare) | ||
if tc.equal && diff != "" { | ||
t.Errorf("comparing %v and %v should be equal, but diff is %s", tc.give, tc.compare, diff) | ||
} else if !tc.equal && diff == "" { | ||
t.Errorf("comparing %v and %v should not be equal, but diff is empty", tc.give, tc.compare) | ||
} | ||
} | ||
} | ||
|
||
func TestTime_JSONSchema(t *testing.T) { | ||
sc := (&jsonschema.Reflector{RequiredFromJSONSchemaTags: true}).Reflect(configtype.Time{}) | ||
schema, err := json.MarshalIndent(sc, "", " ") | ||
require.NoError(t, err) | ||
|
||
validator, err := plugin.JSONSchemaValidator(string(schema)) | ||
require.NoError(t, err) | ||
|
||
type testCase struct { | ||
Name string | ||
Spec string | ||
Err bool | ||
} | ||
|
||
for _, tc := range append([]testCase{ | ||
{ | ||
Name: "empty", | ||
Err: true, | ||
Spec: `""`, | ||
}, | ||
{ | ||
Name: "null", | ||
Err: true, | ||
Spec: `null`, | ||
}, | ||
{ | ||
Name: "bad type", | ||
Err: true, | ||
Spec: `false`, | ||
}, | ||
{ | ||
Name: "bad format", | ||
Err: true, | ||
Spec: `false`, | ||
}, | ||
}, | ||
func() []testCase { | ||
rnd := rand.New(rand.NewSource(time.Now().UnixNano())) | ||
const ( | ||
cases = 20 | ||
maxDur = int64(100 * time.Hour) | ||
maxDurHalf = maxDur / 2 | ||
) | ||
now := time.Now() | ||
var result []testCase | ||
for i := 0; i < cases; i++ { | ||
val := rnd.Int63n(maxDur) - maxDurHalf | ||
dur := configtype.NewRelativeTime(time.Duration(val)) | ||
|
||
durationData, err := dur.MarshalJSON() | ||
require.NoError(t, err) | ||
result = append(result, testCase{ | ||
Name: string(durationData), | ||
Spec: string(durationData), | ||
}) | ||
|
||
tim := configtype.NewTime(now.Add(time.Duration(val))) | ||
|
||
timeData, err := tim.MarshalJSON() | ||
require.NoError(t, err) | ||
result = append(result, testCase{ | ||
Name: string(timeData), | ||
Spec: string(timeData), | ||
}) | ||
} | ||
|
||
return result | ||
}()..., | ||
) { | ||
t.Run(tc.Name, func(t *testing.T) { | ||
var val any | ||
err := json.Unmarshal([]byte(tc.Spec), &val) | ||
require.NoError(t, err) | ||
if tc.Err { | ||
require.Error(t, validator.Validate(val)) | ||
} else { | ||
require.NoError(t, validator.Validate(val)) | ||
} | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
package configtype | ||
|
||
import "strings" | ||
|
||
func patternCases(cases ...string) string { | ||
return "(" + strings.Join(cases, "|") + ")" | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of using regular expressions can't we try to parse with each format, then return an error if all formats failed to parse?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, although we still need regexes for the jsonschema definitions
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also, the regexes let us give a more specific error, otherwise we'd always error with a duration parsing error (or whatever the last parsing case is).