Skip to main content

config_disassembler/xml/parsers/
parse_xml.rs

1//! Parse XML file from path into XmlElement structure.
2
3use serde_json::Value;
4use tokio::fs;
5
6use crate::xml::parsers::parse_xml_cdata;
7use crate::xml::parsers::strip_whitespace_text_nodes;
8use crate::xml::types::XmlElement;
9
10/// Parses an XML file from a path.
11pub async fn parse_xml(file_path: &str) -> Option<XmlElement> {
12    let content = match fs::read_to_string(file_path).await {
13        Ok(c) => c,
14        Err(e) => {
15            log::error!(
16                "{} was unable to be parsed and will not be processed. Confirm formatting and try again.",
17                file_path
18            );
19            log::debug!("Parse error: {}", e);
20            return None;
21        }
22    };
23    parse_xml_from_str(&content, file_path)
24}
25
26/// Parses XML from a string. The file_path is used for error logging only.
27/// Uses custom parser that preserves CDATA sections (output as #cdata key).
28pub fn parse_xml_from_str(content: &str, file_path: &str) -> Option<XmlElement> {
29    let parsed: Value = match parse_xml_cdata::parse_xml_with_cdata(content) {
30        Ok(v) => v,
31        Err(e) => {
32            log::error!(
33                "{} was unable to be parsed and will not be processed. Confirm formatting and try again.",
34                file_path
35            );
36            log::debug!("Parse error: {}", e);
37            return None;
38        }
39    };
40
41    let cleaned = strip_whitespace_text_nodes(&parsed);
42    Some(cleaned)
43}
44
45/// Extract xmlns attribute from raw XML (quickxml_to_serde drops it).
46/// Returns Some(value) if found, None otherwise.
47pub fn extract_xmlns_from_raw(xml_content: &str) -> Option<String> {
48    let re = regex::Regex::new(r#"xmlns="([^"]*)""#).ok()?;
49    re.captures(xml_content).map(|c| c[1].to_string())
50}
51
52/// Extract XML declaration from raw XML (quickxml_to_serde drops it).
53/// Returns a Value object like {"@version": "1.0", "@encoding": "UTF-8", "@standalone": "yes"}
54/// for use in build_xml_string. None if no declaration found.
55pub fn extract_xml_declaration_from_raw(xml_content: &str) -> Option<XmlElement> {
56    let decl_re = regex::Regex::new(r#"<\?xml\s+([^?]+)\?>"#).ok()?;
57    let decl_content = decl_re.captures(xml_content)?.get(1)?.as_str();
58    let mut decl = serde_json::Map::new();
59    let version_re = regex::Regex::new(r#"version="([^"]*)""#).ok()?;
60    {
61        let cap = version_re.captures(decl_content)?;
62        decl.insert("@version".to_string(), Value::String(cap[1].to_string()));
63    }
64    let encoding_re = regex::Regex::new(r#"encoding="([^"]*)""#).ok()?;
65    if let Some(cap) = encoding_re.captures(decl_content) {
66        decl.insert("@encoding".to_string(), Value::String(cap[1].to_string()));
67    }
68    let standalone_re = regex::Regex::new(r#"standalone="([^"]*)""#).ok()?;
69    if let Some(cap) = standalone_re.captures(decl_content) {
70        decl.insert("@standalone".to_string(), Value::String(cap[1].to_string()));
71    }
72    Some(Value::Object(decl))
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn extract_xmlns_from_raw_finds_namespace() {
81        let xml = r#"<root xmlns="http://soap.sforce.com/2006/04/metadata"><a/></root>"#;
82        assert_eq!(
83            extract_xmlns_from_raw(xml),
84            Some("http://soap.sforce.com/2006/04/metadata".to_string())
85        );
86    }
87
88    #[test]
89    fn extract_xmlns_from_raw_returns_none_when_absent() {
90        let xml = r#"<root><a/></root>"#;
91        assert_eq!(extract_xmlns_from_raw(xml), None);
92    }
93
94    #[test]
95    fn extract_xml_declaration_from_raw_parses_version_and_encoding() {
96        let xml = r#"<?xml version="1.0" encoding="UTF-8"?><root/>"#;
97        let decl = extract_xml_declaration_from_raw(xml).unwrap();
98        let obj = decl.as_object().unwrap();
99        assert_eq!(obj.get("@version").and_then(|v| v.as_str()), Some("1.0"));
100        assert_eq!(obj.get("@encoding").and_then(|v| v.as_str()), Some("UTF-8"));
101    }
102
103    #[test]
104    fn extract_xml_declaration_from_raw_parses_standalone() {
105        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root/>"#;
106        let decl = extract_xml_declaration_from_raw(xml).unwrap();
107        let obj = decl.as_object().unwrap();
108        assert_eq!(obj.get("@standalone").and_then(|v| v.as_str()), Some("yes"));
109    }
110
111    #[test]
112    fn extract_xml_declaration_from_raw_returns_none_without_declaration() {
113        let xml = r#"<root/>"#;
114        assert!(extract_xml_declaration_from_raw(xml).is_none());
115    }
116
117    #[test]
118    fn extract_xml_declaration_from_raw_returns_none_when_version_missing() {
119        let xml = r#"<?xml encoding="UTF-8"?><root/>"#;
120        assert!(extract_xml_declaration_from_raw(xml).is_none());
121    }
122
123    #[test]
124    fn extract_xml_declaration_from_raw_version_only_no_encoding_no_standalone() {
125        // Exercises the false branches of both the encoding and standalone
126        // `if let Some(cap)` checks inside extract_xml_declaration_from_raw.
127        let xml = r#"<?xml version="1.0"?><root/>"#;
128        let decl = extract_xml_declaration_from_raw(xml).unwrap();
129        let obj = decl.as_object().unwrap();
130        assert_eq!(obj.get("@version").and_then(|v| v.as_str()), Some("1.0"));
131        assert!(
132            obj.get("@encoding").is_none(),
133            "encoding must be absent when not in source"
134        );
135        assert!(
136            obj.get("@standalone").is_none(),
137            "standalone must be absent when not in source"
138        );
139    }
140
141    #[test]
142    fn parse_xml_from_str_invalid_xml_returns_none() {
143        let result = parse_xml_from_str("<<", "test.xml");
144        assert!(result.is_none());
145    }
146
147    #[tokio::test]
148    async fn parse_xml_missing_file_returns_none() {
149        let result = parse_xml("/nonexistent/path/file.xml").await;
150        assert!(result.is_none());
151    }
152}