Skip to content

Commit a148ed4

Browse files
committed
Add timestamp parse function
Add function to parse an input string as a timestamp using layouts from the YAML specifiction. Add test case based on user feedback.
1 parent ac1add6 commit a148ed4

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

output_json.go

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ func cast(node yamlv3.Node) (interface{}, error) {
396396
return node.Value, nil
397397

398398
case "!!timestamp":
399-
return time.Parse(time.RFC3339, node.Value)
399+
return parseTime(node.Value)
400400

401401
case "!!int":
402402
return strconv.Atoi(node.Value)
@@ -413,6 +413,24 @@ func cast(node yamlv3.Node) (interface{}, error) {
413413
default:
414414
return nil, fmt.Errorf("unknown tag %s", node.Tag)
415415
}
416+
}
417+
418+
func parseTime(value string) (time.Time, error) {
419+
// YAML Spec regarding timestamp: https://yaml.org/type/timestamp.html
420+
var layouts = [...]string{
421+
time.RFC3339,
422+
"2006-01-02T15:04:05.999999999Z",
423+
"2006-01-02t15:04:05.999999999-07:00",
424+
"2006-01-02 15:04:05.999999999 07:00",
425+
"2006-01-02 15:04:05.999999999",
426+
"2006-01-02",
427+
}
428+
429+
for _, layout := range layouts {
430+
if result, err := time.Parse(layout, value); err == nil {
431+
return result, nil
432+
}
433+
}
416434

417-
// return nil, fmt.Errorf("failed to cast scalar node to a type")
435+
return time.Time{}, fmt.Errorf("value %q cannot be parsed as a timestamp", value)
418436
}

output_json_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,21 @@ var _ = Describe("JSON output", func() {
178178
Expect(err).ToNot(HaveOccurred())
179179
Expect(result).To(Equal(`{
180180
"timestamp": "2021-08-21T00:00:00Z"
181+
}`))
182+
})
183+
184+
It("should parse all YAML spec conform timestamps", func() {
185+
var example yamlv3.Node
186+
Expect(yamlv3.Unmarshal([]byte(`timestamp: 2033-12-20`), &example)).To(BeNil())
187+
188+
result, err := NewOutputProcessor(false, false, &DefaultColorSchema).ToCompactJSON(example)
189+
Expect(err).ToNot(HaveOccurred())
190+
Expect(result).To(Equal(`{"timestamp": "2033-12-20T00:00:00Z"}`))
191+
192+
result, err = NewOutputProcessor(false, false, &DefaultColorSchema).ToJSON(example)
193+
Expect(err).ToNot(HaveOccurred())
194+
Expect(result).To(Equal(`{
195+
"timestamp": "2033-12-20T00:00:00Z"
181196
}`))
182197
})
183198
})

0 commit comments

Comments
 (0)