]> git.maquefel.me Git - brevno-suite/hugo/commitdiff
parser/metadecoder: Improve errors for non-map XML root values
authorVille Vesilehto <ville@vesilehto.fi>
Sat, 22 Mar 2025 17:48:23 +0000 (19:48 +0200)
committerGitHub <noreply@github.com>
Sat, 22 Mar 2025 17:48:23 +0000 (18:48 +0100)
Previously, the XML decoder would panic when encountering a root element with
a non-map value due to an unsafe type assertion.

The fix adds proper type checking before the map conversion and provides
clear error messages to help users identify and fix invalid XML structures.

Example error for invalid XML like:
<root>just text</root>

Will now return:
"XML root element 'root' must be a map/object, got string"

parser/metadecoders/decoder.go
parser/metadecoders/decoder_test.go

index eb33f1ee9211a9a3121338893befe073eea52204..1655ea513a3f7834c12451f3b61ad6225827604e 100644 (file)
@@ -152,7 +152,19 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v any) error {
                        if err != nil {
                                return toFileError(f, data, fmt.Errorf("failed to unmarshal XML: %w", err))
                        }
-                       xmlValue = xmlRoot[xmlRootName].(map[string]any)
+
+                       // Get the root value and verify it's a map
+                       rootValue := xmlRoot[xmlRootName]
+                       if rootValue == nil {
+                               return toFileError(f, data, fmt.Errorf("XML root element '%s' has no value", xmlRootName))
+                       }
+
+                       // Type check before conversion
+                       mapValue, ok := rootValue.(map[string]any)
+                       if !ok {
+                               return toFileError(f, data, fmt.Errorf("XML root element '%s' must be a map/object, got %T", xmlRootName, rootValue))
+                       }
+                       xmlValue = mapValue
                }
 
                switch v := v.(type) {
index f0ebe57e57ce3e53426c929fcf0a4328c72311f1..d78293402889122be7a9741d84e319aaee991af5 100644 (file)
@@ -99,6 +99,7 @@ func TestUnmarshalToMap(t *testing.T) {
                // errors
                {`a = b`, TOML, false},
                {`a,b,c`, CSV, false}, // Use Unmarshal for CSV
+               {`<root>just a string</root>`, XML, false},
        } {
                msg := qt.Commentf("%d: %s", i, test.format)
                m, err := d.UnmarshalToMap([]byte(test.data), test.format)