| 1 | package xml |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/xml" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | "unicode/utf8" |
| 9 | |
| 10 | "github.com/tomwright/dasel/v3/model" |
| 11 | "github.com/tomwright/dasel/v3/parsing" |
| 12 | ) |
| 13 | |
| 14 | // isValidXMLNameStartChar reports whether r is a valid first character of an |
| 15 | // XML Name, per the XML 1.0 (Fifth Edition) specification §2.3. |
| 16 | func isValidXMLNameStartChar(r rune) bool { |
| 17 | return r == ':' || r == '_' || |
| 18 | (r >= 'A' && r <= 'Z') || |
| 19 | (r >= 'a' && r <= 'z') || |
| 20 | (r >= 0xC0 && r <= 0xD6) || |
| 21 | (r >= 0xD8 && r <= 0xF6) || |
| 22 | (r >= 0xF8 && r <= 0x2FF) || |
| 23 | (r >= 0x370 && r <= 0x37D) || |
| 24 | (r >= 0x37F && r <= 0x1FFF) || |
| 25 | (r >= 0x200C && r <= 0x200D) || |
| 26 | (r >= 0x2070 && r <= 0x218F) || |
| 27 | (r >= 0x2C00 && r <= 0x2FEF) || |
| 28 | (r >= 0x3001 && r <= 0xD7FF) || |
| 29 | (r >= 0xF900 && r <= 0xFDCF) || |
| 30 | (r >= 0xFDF0 && r <= 0xFFFD) || |
| 31 | (r >= 0x10000 && r <= 0xEFFFF) |
| 32 | } |
| 33 | |
| 34 | // isValidXMLNameChar reports whether r is a valid subsequent character of an |
| 35 | // XML Name, per the XML 1.0 (Fifth Edition) specification §2.3. |
| 36 | func isValidXMLNameChar(r rune) bool { |
| 37 | return isValidXMLNameStartChar(r) || |
| 38 | r == '-' || r == '.' || |
| 39 | (r >= '0' && r <= '9') || |
| 40 | r == 0xB7 || |
| 41 | (r >= 0x0300 && r <= 0x036F) || |
| 42 | (r >= 0x203F && r <= 0x2040) |
| 43 | } |
| 44 | |
| 45 | // isValidXMLName reports whether s is a valid XML element or attribute name. |
| 46 | func isValidXMLName(s string) bool { |
| 47 | if s == "" { |
| 48 | return false |
| 49 | } |
| 50 | first, size := utf8.DecodeRuneInString(s) |
| 51 | if (first == utf8.RuneError && size == 1) || !isValidXMLNameStartChar(first) { |
| 52 | return false |
| 53 | } |
| 54 | for i := size; i < len(s); { |
| 55 | r, w := utf8.DecodeRuneInString(s[i:]) |
| 56 | if (r == utf8.RuneError && w == 1) || !isValidXMLNameChar(r) { |
| 57 | return false |
| 58 | } |
| 59 | i += w |
| 60 | } |
| 61 | return true |
| 62 | } |
| 63 | |
| 64 | func newXMLWriter(options parsing.WriterOptions) (parsing.Writer, error) { |
| 65 | return &xmlWriter{ |
| 66 | options: options, |
| 67 | }, nil |
| 68 | } |
| 69 | |
| 70 | type xmlWriter struct { |
| 71 | options parsing.WriterOptions |
| 72 | } |
| 73 | |
| 74 | // Write writes a value to a byte slice. |
| 75 | func (j *xmlWriter) Write(value *model.Value) ([]byte, error) { |
| 76 | buf := new(bytes.Buffer) |
| 77 | writer := xml.NewEncoder(buf) |
| 78 | defer func() { |
| 79 | _ = writer.Close() |
| 80 | }() |
| 81 | if j.options.Compact { |
| 82 | writer.Indent("", "") |
| 83 | } else { |
| 84 | writer.Indent("", " ") |
| 85 | } |
| 86 | |
| 87 | element, err := j.toElement("root", value) |
| 88 | if err != nil { |
| 89 | return nil, fmt.Errorf("failed to convert to element: %w", err) |
| 90 | } |
| 91 | for _, c := range element.Children { |
| 92 | c.compact = j.options.Compact |
| 93 | if err := writer.Encode(c); err != nil { |
| 94 | return nil, err |
| 95 | } |
| 96 | if !j.options.Compact { |
| 97 | if err := writer.EncodeToken(xml.CharData("\n")); err != nil { |
| 98 | return nil, err |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | if err := writer.Flush(); err != nil { |
| 104 | return nil, err |
| 105 | } |
| 106 | outBytes := buf.Bytes() |
| 107 | if !bytes.HasSuffix(outBytes, []byte("\n")) { |
| 108 | outBytes = append(outBytes, '\n') |
| 109 | } |
| 110 | return outBytes, nil |
| 111 | } |
| 112 | |
| 113 | func (j *xmlWriter) toElement(key string, value *model.Value) (*xmlElement, error) { |
| 114 | if !isValidXMLName(key) { |
| 115 | return nil, fmt.Errorf("key %q is not a valid XML element name", key) |
| 116 | } |
| 117 | readProcessingInstructions := func() []*xmlProcessingInstruction { |
| 118 | if piMeta, ok := value.MetadataValue("xml_processing_instructions"); ok && piMeta != nil { |
| 119 | if pis, ok := piMeta.([]*xmlProcessingInstruction); ok { |
| 120 | return pis |
| 121 | } |
| 122 | } |
| 123 | return nil |
| 124 | } |
| 125 | readComments := func() []*xmlComment { |
| 126 | if commentMeta, ok := value.MetadataValue("xml_comments"); ok && commentMeta != nil { |
| 127 | if comments, ok := commentMeta.([]*xmlComment); ok { |
| 128 | return comments |
| 129 | } |
| 130 | } |
| 131 | return nil |
| 132 | } |
| 133 | switch value.Type() { |
| 134 | |
| 135 | case model.TypeString: |
| 136 | strVal, err := valueToString(value) |
| 137 | return &xmlElement{ |
| 138 | Name: key, |
| 139 | Content: strVal, |
| 140 | ProcessingInstructions: readProcessingInstructions(), |
| 141 | Comments: readComments(), |
| 142 | }, err |
| 143 | |
| 144 | case model.TypeMap: |
| 145 | kvs, err := value.MapKeyValues() |
| 146 | if err != nil { |
| 147 | return nil, err |
| 148 | } |
| 149 | |
| 150 | el := &xmlElement{ |
| 151 | Name: key, |
| 152 | ProcessingInstructions: readProcessingInstructions(), |
| 153 | Comments: readComments(), |
| 154 | } |
| 155 | |
| 156 | if err := extractAttrsAndText(kvs, el); err != nil { |
| 157 | return nil, err |
| 158 | } |
| 159 | |
| 160 | orderMeta, hasOrder := value.MetadataValue(xmlChildOrderKey) |
| 161 | if hasOrder { |
| 162 | childOrder, ok := orderMeta.([]string) |
| 163 | if !ok { |
| 164 | hasOrder = false |
| 165 | } else { |
| 166 | if err := j.buildChildrenOrdered(kvs, el, childOrder); err != nil { |
| 167 | return nil, err |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | if !hasOrder { |
| 173 | if err := j.buildChildrenUnordered(kvs, el); err != nil { |
| 174 | return nil, err |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | return el, nil |
| 179 | case model.TypeSlice: |
| 180 | el := &xmlElement{ |
| 181 | Name: "root", |
| 182 | ProcessingInstructions: readProcessingInstructions(), |
| 183 | Comments: readComments(), |
| 184 | useChildrenOnly: true, |
| 185 | } |
| 186 | if err := value.RangeSlice(func(i int, value *model.Value) error { |
| 187 | childEl, err := j.toElement(key, value) |
| 188 | if err != nil { |
| 189 | return err |
| 190 | } |
| 191 | el.appendChild(childEl) |
| 192 | |
| 193 | return nil |
| 194 | }); err != nil { |
| 195 | return nil, err |
| 196 | } |
| 197 | return el, nil |
| 198 | default: |
| 199 | return nil, fmt.Errorf("xml writer does not support value type: %s", value.Type()) |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | // extractAttrsAndText iterates kvs and extracts "-" prefixed attributes into |
| 204 | // el.Attrs and "#text" into el.Content. |
| 205 | func extractAttrsAndText(kvs []model.KeyValue, el *xmlElement) error { |
| 206 | for _, kv := range kvs { |
| 207 | if strings.HasPrefix(kv.Key, "-") { |
| 208 | attrName := kv.Key[1:] |
| 209 | if !isValidXMLName(attrName) { |
| 210 | return fmt.Errorf("invalid XML attribute name %q from map key %q", attrName, kv.Key) |
| 211 | } |
| 212 | attr := xmlAttr{ |
| 213 | Name: attrName, |
| 214 | } |
| 215 | var err error |
| 216 | attr.Value, err = valueToString(kv.Value) |
| 217 | if err != nil { |
| 218 | return fmt.Errorf("failed to convert attribute %q to string: %w", attr.Name, err) |
| 219 | } |
| 220 | el.Attrs = append(el.Attrs, attr) |
| 221 | continue |
| 222 | } |
| 223 | |
| 224 | if kv.Key == "#text" { |
| 225 | var err error |
| 226 | el.Content, err = valueToString(kv.Value) |
| 227 | if err != nil { |
| 228 | return fmt.Errorf("failed to convert content to string: %w", err) |
| 229 | } |
| 230 | continue |
| 231 | } |
| 232 | } |
| 233 | return nil |
| 234 | } |
| 235 | |
| 236 | // buildChildrenOrdered reconstructs child elements using counter-based ordering |
| 237 | // from the childOrder metadata slice. |
| 238 | func (j *xmlWriter) buildChildrenOrdered(kvs []model.KeyValue, el *xmlElement, childOrder []string) error { |
| 239 | // Build local map for fast lookups without GetMapKey overhead. |
| 240 | childValues := make(map[string]*model.Value, len(kvs)) |
| 241 | for _, kv := range kvs { |
| 242 | if !strings.HasPrefix(kv.Key, "-") && kv.Key != "#text" { |
| 243 | childValues[kv.Key] = kv.Value |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | counters := make(map[string]int, len(childValues)) |
| 248 | seen := make(map[string]bool, len(childValues)) |
| 249 | |
| 250 | for _, name := range childOrder { |
| 251 | seen[name] = true |
| 252 | childVal, exists := childValues[name] |
| 253 | if !exists { |
| 254 | // Key not in map (stale metadata after delete), skip. |
| 255 | counters[name]++ |
| 256 | continue |
| 257 | } |
| 258 | |
| 259 | index := counters[name] |
| 260 | counters[name]++ |
| 261 | |
| 262 | if childVal.Type() == model.TypeSlice { |
| 263 | // SliceLen error is impossible after TypeSlice type check above. |
| 264 | sliceLen, _ := childVal.SliceLen() |
| 265 | if index >= sliceLen { |
| 266 | // Counter overflow (more metadata entries than actual values), skip. |
| 267 | continue |
| 268 | } |
| 269 | item, sliceErr := childVal.GetSliceIndex(index) |
| 270 | if sliceErr != nil { |
| 271 | // Should not happen after bounds check; skip gracefully if model is inconsistent. |
| 272 | continue |
| 273 | } |
| 274 | childEl, childErr := j.toElement(name, item) |
| 275 | if childErr != nil { |
| 276 | return fmt.Errorf("failed to convert child element %q to element: %w", name, childErr) |
| 277 | } |
| 278 | el.appendChild(childEl) |
| 279 | } else { |
| 280 | if index >= 1 { |
| 281 | // Scalar value, can only be emitted once. |
| 282 | continue |
| 283 | } |
| 284 | childEl, childErr := j.toElement(name, childVal) |
| 285 | if childErr != nil { |
| 286 | return fmt.Errorf("failed to convert child element %q to element: %w", name, childErr) |
| 287 | } |
| 288 | el.appendChild(childEl) |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | // Append any map keys not in the ordering (new keys from mutations). |
| 293 | for _, kv := range kvs { |
| 294 | if strings.HasPrefix(kv.Key, "-") || kv.Key == "#text" || seen[kv.Key] { |
| 295 | continue |
| 296 | } |
| 297 | childEl, childErr := j.toElement(kv.Key, kv.Value) |
| 298 | if childErr != nil { |
| 299 | return fmt.Errorf("failed to convert child element %q to element: %w", kv.Key, childErr) |
| 300 | } |
| 301 | el.appendChild(childEl) |
| 302 | } |
| 303 | |
| 304 | return nil |
| 305 | } |
| 306 | |
| 307 | // buildChildrenUnordered iterates map keys in insertion order, skipping |
| 308 | // attributes and #text (backward-compatible fallback). |
| 309 | func (j *xmlWriter) buildChildrenUnordered(kvs []model.KeyValue, el *xmlElement) error { |
| 310 | for _, kv := range kvs { |
| 311 | if strings.HasPrefix(kv.Key, "-") || kv.Key == "#text" { |
| 312 | continue |
| 313 | } |
| 314 | childEl, childErr := j.toElement(kv.Key, kv.Value) |
| 315 | if childErr != nil { |
| 316 | return fmt.Errorf("failed to convert child element %q to element: %w", kv.Key, childErr) |
| 317 | } |
| 318 | el.appendChild(childEl) |
| 319 | } |
| 320 | return nil |
| 321 | } |
| 322 | |
| 323 | func valueToString(v *model.Value) (string, error) { |
| 324 | if v.IsNull() { |
| 325 | return "", nil |
| 326 | } |
| 327 | |
| 328 | switch v.Type() { |
| 329 | case model.TypeString: |
| 330 | stringValue, err := v.StringValue() |
| 331 | if err != nil { |
| 332 | return "", err |
| 333 | } |
| 334 | return stringValue, nil |
| 335 | case model.TypeInt: |
| 336 | i, err := v.IntValue() |
| 337 | if err != nil { |
| 338 | return "", err |
| 339 | } |
| 340 | return fmt.Sprintf("%d", i), nil |
| 341 | case model.TypeFloat: |
| 342 | i, err := v.FloatValue() |
| 343 | if err != nil { |
| 344 | return "", err |
| 345 | } |
| 346 | return fmt.Sprintf("%g", i), nil |
| 347 | case model.TypeBool: |
| 348 | i, err := v.BoolValue() |
| 349 | if err != nil { |
| 350 | return "", err |
| 351 | } |
| 352 | return fmt.Sprintf("%t", i), nil |
| 353 | default: |
| 354 | return "", fmt.Errorf("xml writer cannot format type %s to string", v.Type()) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | // indentString returns the indentation for a given depth level. |
| 359 | func indentString(depth int) string { |
| 360 | return strings.Repeat(" ", depth) |
| 361 | } |
| 362 | |
| 363 | func (e *xmlElement) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { |
| 364 | // Write processing instructions before the element (document-level) |
| 365 | if len(e.ProcessingInstructions) > 0 { |
| 366 | for _, pi := range e.ProcessingInstructions { |
| 367 | if err := enc.EncodeToken(xml.ProcInst{ |
| 368 | Target: pi.Target, |
| 369 | Inst: []byte(pi.Value), |
| 370 | }); err != nil { |
| 371 | return err |
| 372 | } |
| 373 | if !e.compact { |
| 374 | if err := enc.EncodeToken(xml.CharData("\n")); err != nil { |
| 375 | return err |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | } |
| 380 | // Write comments before the element (document-level comments only) |
| 381 | // Child-level comments are written by the parent inside its body |
| 382 | if e.depth == 0 && len(e.Comments) > 0 { |
| 383 | for _, comment := range e.Comments { |
| 384 | if strings.Contains(comment.Text, "--") { |
| 385 | return fmt.Errorf("comment text cannot contain '--' sequence (invalid XML comment)") |
| 386 | } |
| 387 | if err := enc.EncodeToken(xml.Comment(comment.Text)); err != nil { |
| 388 | return fmt.Errorf("failed to encode comment: %w", err) |
| 389 | } |
| 390 | if !e.compact { |
| 391 | if err := enc.EncodeToken(xml.CharData("\n")); err != nil { |
| 392 | return err |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | } |
| 397 | start.Name = xml.Name{Local: e.Name} |
| 398 | |
| 399 | if len(e.Attrs) > 0 { |
| 400 | for _, attr := range e.Attrs { |
| 401 | start.Attr = append(start.Attr, xml.Attr{ |
| 402 | Name: xml.Name{Local: attr.Name}, |
| 403 | Value: attr.Value, |
| 404 | }) |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | if err := enc.EncodeToken(start); err != nil { |
| 409 | return err |
| 410 | } |
| 411 | |
| 412 | // TODO : Handle CDATA sections on write. |
| 413 | |
| 414 | if len(e.Content) > 0 { |
| 415 | if err := enc.EncodeToken(xml.CharData(e.Content)); err != nil { |
| 416 | return err |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | // Write children with their preceding comments |
| 421 | childDepth := e.depth + 1 |
| 422 | for _, child := range e.Children { |
| 423 | // Write child's comments inside parent, before the child element |
| 424 | if len(child.Comments) > 0 { |
| 425 | for _, comment := range child.Comments { |
| 426 | if strings.Contains(comment.Text, "--") { |
| 427 | return fmt.Errorf("comment text cannot contain '--' sequence (invalid XML comment)") |
| 428 | } |
| 429 | if !e.compact { |
| 430 | // Add newline + indentation before comment |
| 431 | if err := enc.EncodeToken(xml.CharData("\n" + indentString(childDepth))); err != nil { |
| 432 | return err |
| 433 | } |
| 434 | } |
| 435 | if err := enc.EncodeToken(xml.Comment(comment.Text)); err != nil { |
| 436 | return fmt.Errorf("failed to encode comment: %w", err) |
| 437 | } |
| 438 | } |
| 439 | // Clear comments so child doesn't write them again |
| 440 | child.Comments = nil |
| 441 | } |
| 442 | // Set child depth and compact flag for recursive calls |
| 443 | child.depth = childDepth |
| 444 | child.compact = e.compact |
| 445 | if err := enc.Encode(child); err != nil { |
| 446 | return err |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | return enc.EncodeToken(start.End()) |
| 451 | } |