Skip to content

Commit

Permalink
Add timestamp parse function
Browse files Browse the repository at this point in the history
Add function to parse an input string as a timestamp using layouts from
the YAML specifiction.

Add test case based on user feedback.
  • Loading branch information
HeavyWombat committed Mar 27, 2022
1 parent ac1add6 commit a148ed4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
22 changes: 20 additions & 2 deletions output_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ func cast(node yamlv3.Node) (interface{}, error) {
return node.Value, nil

case "!!timestamp":
return time.Parse(time.RFC3339, node.Value)
return parseTime(node.Value)

case "!!int":
return strconv.Atoi(node.Value)
Expand All @@ -413,6 +413,24 @@ func cast(node yamlv3.Node) (interface{}, error) {
default:
return nil, fmt.Errorf("unknown tag %s", node.Tag)
}
}

func parseTime(value string) (time.Time, error) {
// YAML Spec regarding timestamp: https://yaml.org/type/timestamp.html
var layouts = [...]string{
time.RFC3339,
"2006-01-02T15:04:05.999999999Z",
"2006-01-02t15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999 07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02",
}

for _, layout := range layouts {
if result, err := time.Parse(layout, value); err == nil {
return result, nil
}
}

// return nil, fmt.Errorf("failed to cast scalar node to a type")
return time.Time{}, fmt.Errorf("value %q cannot be parsed as a timestamp", value)
}
15 changes: 15 additions & 0 deletions output_json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,21 @@ var _ = Describe("JSON output", func() {
Expect(err).ToNot(HaveOccurred())
Expect(result).To(Equal(`{
"timestamp": "2021-08-21T00:00:00Z"
}`))
})

It("should parse all YAML spec conform timestamps", func() {
var example yamlv3.Node
Expect(yamlv3.Unmarshal([]byte(`timestamp: 2033-12-20`), &example)).To(BeNil())

result, err := NewOutputProcessor(false, false, &DefaultColorSchema).ToCompactJSON(example)
Expect(err).ToNot(HaveOccurred())
Expect(result).To(Equal(`{"timestamp": "2033-12-20T00:00:00Z"}`))

result, err = NewOutputProcessor(false, false, &DefaultColorSchema).ToJSON(example)
Expect(err).ToNot(HaveOccurred())
Expect(result).To(Equal(`{
"timestamp": "2033-12-20T00:00:00Z"
}`))
})
})
Expand Down

0 comments on commit a148ed4

Please sign in to comment.