xuri / xgen

XSD (XML Schema Definition) parser and Go/C/Java/Rust/TypeScript code generator
BSD 3-Clause "New" or "Revised" License
313 stars 74 forks source link

Fix Generated Go code for time.Time fields resulting in parsing errors #37

Closed alexandre-normand closed 2 years ago

alexandre-normand commented 2 years ago

PR Details

This fixes #13: Go code generated with time.Time which would cause parsing errors on any datetime values not compliant with RFC-3339. The xsd:datetime spec states that the format is inspired by ISO-8601 which is not the same as RFC-3339. As a result, prior to this change, the generated code was likely to result in parsing errors on those time.Time fields.

This changes the mapping of the datetime and related types to string for Go. This removes the potential for parsing errors with the tradeoff that users would now have to do parsing of the time.Time values in post-processing. This seems like the better tradeoff given that users would potentially have data on which time formats their apps actually need to support.

Description

I added a time.Time field to the base64 example and updated the xmlFixture for xml_test.go to show how this would fail when the field was defined as time.Time even if the value was compliant with the xsd:datetime spec. Prior to the fix (the update to the type mapping), the generated code would be:

type TopLevel struct {
    CostAttr float64  `xml:"cost,attr,omitempty"`
    LastUpdatedAttr time.Time  `xml:"LastUpdated,attr,omitempty"`
    Nested   *MyType7 `xml:"nested"`
    *MyType6
}

Which would cause this error in xml_test with the updated fixture:

Received unexpected error:
       parsing time "2021-09-14T12:04:09.69" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "Z07:00"

I also had to update the xml_test.go because my XMLEqual which was inspired by testify's JSONeq was flawed because unmarshaling XML to an interface{} doesn't work like it does with json unmarshaling. Instead, I reverted to a string equality check which mens that fixtures have to match the order of attributes and elements as well as indentation. This seems like an okay solution and does validate that the generated struct doesn't lose any data and marshals/unmarshals without errors.

Related Issue

Motivation and Context

How Has This Been Tested

Types of changes

Checklist

xuri commented 2 years ago

LGTM, thanks @alexandre-normand.