-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathxml_utils.rs
More file actions
409 lines (360 loc) · 13.4 KB
/
xml_utils.rs
File metadata and controls
409 lines (360 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! XML utilities using quick-xml for efficient XML generation and parsing
//!
//! This module provides helper functions for generating and parsing XML using the quick-xml crate,
//! replacing string-based XML manipulation with proper XML handling.
use color_eyre::{eyre::eyre, Result};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::reader::Reader;
use quick_xml::writer::Writer;
use std::collections::HashMap;
use std::io::Cursor;
/// A builder for creating XML documents with quick-xml
pub struct XmlWriter {
writer: Writer<Cursor<Vec<u8>>>,
}
impl XmlWriter {
/// Create a new XML writer
pub fn new() -> Self {
Self {
writer: Writer::new(Cursor::new(Vec::new())),
}
}
/// Start an XML element with attributes
pub fn start_element(&mut self, name: &str, attributes: &[(&str, &str)]) -> Result<()> {
let mut elem = BytesStart::new(name);
for (key, value) in attributes {
elem.push_attribute((*key, *value));
}
self.writer
.write_event(Event::Start(elem))
.map_err(|e| eyre!("Failed to write start element: {}", e))?;
Ok(())
}
/// Write a simple element with text content
pub fn write_text_element(&mut self, name: &str, text: &str) -> Result<()> {
self.start_element(name, &[])?;
self.write_text(text)?;
self.end_element(name)?;
Ok(())
}
/// Write a simple element with text content and attributes
pub fn write_text_element_with_attrs(
&mut self,
name: &str,
text: &str,
attributes: &[(&str, &str)],
) -> Result<()> {
self.start_element(name, attributes)?;
if !text.is_empty() {
self.write_text(text)?;
}
self.end_element(name)?;
Ok(())
}
/// Write a self-closing element with attributes
pub fn write_empty_element(&mut self, name: &str, attributes: &[(&str, &str)]) -> Result<()> {
let mut elem = BytesStart::new(name);
for (key, value) in attributes {
elem.push_attribute((*key, *value));
}
self.writer
.write_event(Event::Empty(elem))
.map_err(|e| eyre!("Failed to write empty element: {}", e))?;
Ok(())
}
/// Write text content
pub fn write_text(&mut self, text: &str) -> Result<()> {
if !text.is_empty() {
self.writer
.write_event(Event::Text(BytesText::new(text)))
.map_err(|e| eyre!("Failed to write text: {}", e))?;
}
Ok(())
}
/// End an XML element
pub fn end_element(&mut self, name: &str) -> Result<()> {
self.writer
.write_event(Event::End(BytesEnd::new(name)))
.map_err(|e| eyre!("Failed to write end element: {}", e))?;
Ok(())
}
/// Get the generated XML as a string
pub fn into_string(self) -> Result<String> {
let bytes = self.writer.into_inner().into_inner();
String::from_utf8(bytes).map_err(|e| eyre!("Failed to convert XML to string: {}", e))
}
}
impl Default for XmlWriter {
fn default() -> Self {
Self::new()
}
}
/// Simple DOM node for XML parsing
#[derive(Debug, Clone)]
pub struct XmlNode {
pub name: String,
pub attributes: HashMap<String, String>,
pub text: String,
pub children: Vec<XmlNode>,
}
impl XmlNode {
/// Find first element by name (recursive search)
pub fn find(&self, element_name: &str) -> Option<&XmlNode> {
if self.name == element_name {
return Some(self);
}
for child in &self.children {
if let Some(found) = child.find(element_name) {
return Some(found);
}
}
None
}
/// Find first element by name with namespace fallback
pub fn find_with_namespace(&self, element_name: &str) -> Option<&XmlNode> {
// Try namespaced version first
if let Some(found) = self.find(&format!("bootc:{}", element_name)) {
return Some(found);
}
// Fallback to non-namespaced
self.find(element_name)
}
/// Get text content of this node
pub fn text_content(&self) -> &str {
&self.text
}
/// Parse memory value from an XML node with unit attribute
/// Returns the value in megabytes (MB)
pub fn parse_memory_mb(&self) -> Option<u32> {
let value = self.text_content().parse::<u32>().ok()?;
// Convert to MB based on unit attribute (default is KiB per libvirt spec)
let unit = self
.attributes
.get("unit")
.map(|s| s.as_str())
.unwrap_or("KiB");
Some(crate::utils::convert_memory_to_mb(value, unit))
}
}
/// Parse XML string into a simple DOM structure
pub fn parse_xml_dom(xml: &str) -> Result<XmlNode> {
let mut reader = Reader::from_str(xml);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let mut stack: Vec<XmlNode> = Vec::new();
let mut root: Option<XmlNode> = None;
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(e)) => {
let name = String::from_utf8_lossy(e.name().as_ref()).into_owned();
let mut attributes = HashMap::new();
for attr in e.attributes() {
if let Ok(attr) = attr {
let key = String::from_utf8_lossy(attr.key.as_ref()).into_owned();
let value = String::from_utf8_lossy(&attr.value).into_owned();
attributes.insert(key, value);
}
}
let node = XmlNode {
name,
attributes,
text: String::new(),
children: Vec::new(),
};
stack.push(node);
}
Ok(Event::Empty(e)) => {
let name = String::from_utf8_lossy(e.name().as_ref()).into_owned();
let mut attributes = HashMap::new();
for attr in e.attributes() {
if let Ok(attr) = attr {
let key = String::from_utf8_lossy(attr.key.as_ref()).into_owned();
let value = String::from_utf8_lossy(&attr.value).into_owned();
attributes.insert(key, value);
}
}
let node = XmlNode {
name,
attributes,
text: String::new(),
children: Vec::new(),
};
// Add to parent or set as root
if let Some(parent) = stack.last_mut() {
parent.children.push(node);
} else if root.is_none() {
root = Some(node);
}
}
Ok(Event::End(_)) => {
if let Some(completed_node) = stack.pop() {
if let Some(parent) = stack.last_mut() {
parent.children.push(completed_node);
} else {
root = Some(completed_node);
}
}
}
Ok(Event::Text(e)) => {
if let Ok(text) = e.unescape() {
if let Some(current) = stack.last_mut() {
current.text.push_str(&text);
}
}
}
Ok(Event::Eof) => break,
Err(e) => return Err(eyre!("Failed to parse XML: {}", e)),
_ => {}
}
buf.clear();
}
root.ok_or_else(|| eyre!("No root element found in XML"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_xml_writer_basic() {
let mut writer = XmlWriter::new();
writer.start_element("root", &[]).unwrap();
writer.write_text_element("name", "test").unwrap();
writer
.write_text_element_with_attrs("memory", "4096", &[("unit", "MiB")])
.unwrap();
writer
.write_empty_element("disk", &[("type", "file")])
.unwrap();
writer.end_element("root").unwrap();
let xml = writer.into_string().unwrap();
assert!(xml.contains("<root>"));
assert!(xml.contains("<name>test</name>"));
assert!(xml.contains("<memory unit=\"MiB\">4096</memory>"));
assert!(xml.contains("<disk type=\"file\"/>"));
assert!(xml.contains("</root>"));
}
#[test]
fn test_find_with_namespace() {
let xml = r#"
<domain>
<metadata>
<bootc:container xmlns:bootc="https://github.com/containers/bootc">
<bootc:source-image>quay.io/fedora/fedora-bootc:42</bootc:source-image>
<bootc:filesystem>xfs</bootc:filesystem>
</bootc:container>
</metadata>
</domain>
"#;
let dom = parse_xml_dom(xml).unwrap();
assert_eq!(
dom.find_with_namespace("source-image")
.map(|n| n.text_content().to_string()),
Some("quay.io/fedora/fedora-bootc:42".to_string())
);
assert_eq!(
dom.find_with_namespace("filesystem")
.map(|n| n.text_content().to_string()),
Some("xfs".to_string())
);
assert_eq!(
dom.find_with_namespace("nonexistent")
.map(|n| n.text_content().to_string()),
None
);
}
#[test]
fn test_xml_writer_complex() {
let mut writer = XmlWriter::new();
writer.start_element("domain", &[("type", "kvm")]).unwrap();
writer.write_text_element("name", "test-domain").unwrap();
writer
.write_text_element_with_attrs("memory", "4096", &[("unit", "MiB")])
.unwrap();
// Test nested elements
writer.start_element("devices", &[]).unwrap();
writer
.write_empty_element("disk", &[("type", "file"), ("device", "disk")])
.unwrap();
writer
.start_element("interface", &[("type", "network")])
.unwrap();
writer
.write_empty_element("source", &[("network", "default")])
.unwrap();
writer.end_element("interface").unwrap();
writer.end_element("devices").unwrap();
writer.end_element("domain").unwrap();
let xml = writer.into_string().unwrap();
assert!(xml.contains("<domain type=\"kvm\">"));
assert!(xml.contains("<devices>"));
assert!(xml.contains("<disk type=\"file\" device=\"disk\"/>"));
assert!(xml.contains("<interface type=\"network\">"));
assert!(xml.contains("<source network=\"default\"/>"));
assert!(xml.contains("</interface>"));
assert!(xml.contains("</devices>"));
assert!(xml.contains("</domain>"));
}
#[test]
fn test_xml_writer_empty_text() {
let mut writer = XmlWriter::new();
writer.start_element("root", &[]).unwrap();
writer.write_text_element("empty", "").unwrap();
writer
.write_text_element_with_attrs("empty-with-attrs", "", &[("type", "test")])
.unwrap();
writer.end_element("root").unwrap();
let xml = writer.into_string().unwrap();
assert!(xml.contains("<empty></empty>"));
assert!(xml.contains("<empty-with-attrs type=\"test\"></empty-with-attrs>"));
}
#[test]
fn test_find_with_namespace_edge_cases() {
// Test with both namespaced and non-namespaced elements
let xml = r#"
<domain>
<metadata>
<bootc:container xmlns:bootc="https://github.com/containers/bootc">
<bootc:source-image>namespaced-image</bootc:source-image>
<source-image>non-namespaced-image</source-image>
</bootc:container>
</metadata>
</domain>
"#;
let dom = parse_xml_dom(xml).unwrap();
// Should find the namespaced version first
assert_eq!(
dom.find_with_namespace("source-image")
.map(|n| n.text_content().to_string()),
Some("namespaced-image".to_string())
);
}
#[test]
fn test_xml_writer_nested_elements() {
let mut writer = XmlWriter::new();
writer.start_element("root", &[]).unwrap();
writer.write_text_element("custom", "raw content").unwrap();
writer.end_element("root").unwrap();
let xml = writer.into_string().unwrap();
assert!(xml.contains("<root>"));
assert!(xml.contains("<custom>raw content</custom>"));
assert!(xml.contains("</root>"));
}
#[test]
fn test_parse_memory_mb() {
// Test KiB (default unit)
let xml = r#"<memory>4194304</memory>"#;
let dom = parse_xml_dom(xml).unwrap();
assert_eq!(dom.parse_memory_mb(), Some(4096));
// Test MiB
let xml = r#"<memory unit='MiB'>2048</memory>"#;
let dom = parse_xml_dom(xml).unwrap();
assert_eq!(dom.parse_memory_mb(), Some(2048));
// Test GiB
let xml = r#"<memory unit='GiB'>4</memory>"#;
let dom = parse_xml_dom(xml).unwrap();
assert_eq!(dom.parse_memory_mb(), Some(4096));
// Test KB (decimal unit: 1000-based)
let xml = r#"<memory unit='KB'>1048576</memory>"#;
let dom = parse_xml_dom(xml).unwrap();
assert_eq!(dom.parse_memory_mb(), Some(1000));
}
}