Skip to main content

config_disassembler/xml/handlers/
reassemble.rs

1//! Reassemble XML from disassembled directory.
2
3use crate::xml::builders::{build_xml_string, merge_xml_elements, reorder_root_keys};
4use crate::xml::multi_level::{ensure_segment_files_structure, load_multi_level_config};
5use crate::xml::parsers::parse_to_xml_object;
6use crate::xml::types::{MultiLevelRule, SidecarSpec, XmlElement};
7use crate::xml::utils::normalize_path_unix;
8use serde_json::Value;
9use std::collections::HashSet;
10use std::ffi::OsString;
11use std::future::Future;
12use std::path::{Path, PathBuf};
13use std::pin::Pin;
14use tokio::fs;
15
16/// Read a `.key_order.json` file (if present) and parse it as a list of root key names.
17async fn read_key_order(path: &Path) -> Option<Vec<String>> {
18    let bytes = fs::read(path).await.ok()?;
19    serde_json::from_slice::<Vec<String>>(&bytes).ok()
20}
21
22/// Read a `.trailing_newline.json` file (if present) and parse it as a bool. Absent --
23/// e.g. a directory disassembled by a crate version predating this sidecar -- defaults
24/// to `false`, preserving the pre-existing "always trim trailing whitespace" behavior.
25async fn read_trailing_newline(path: &Path) -> Option<bool> {
26    let bytes = fs::read(path).await.ok()?;
27    String::from_utf8(bytes).ok()?.trim().parse::<bool>().ok()
28}
29
30/// Remove @xmlns from an object so the reassembled segment wrapper (e.g. programProcesses) has no xmlns.
31fn strip_xmlns_from_value(v: Value) -> Value {
32    match v {
33        Value::Object(obj) => {
34            Value::Object(obj.into_iter().filter(|(k, _)| k != "@xmlns").collect())
35        }
36        other => other,
37    }
38}
39
40/// When recursing into a nested multi-level rule's `path_segment`, the
41/// deeper-level recursion needs the *sibling* rules — every rule
42/// except the one we just matched — so a sub-directory that happens
43/// to share its parent's `path_segment` doesn't re-enter the same
44/// rule. Returns the cloned slice with the matched segment filtered
45/// out. Pure helper extracted from
46/// `reassemble_multi_level_segment_inner`.
47fn deeper_candidate_rules(
48    all_rules: &[MultiLevelRule],
49    exclude_path_segment: &str,
50) -> Vec<MultiLevelRule> {
51    all_rules
52        .iter()
53        .filter(|r| r.path_segment != exclude_path_segment)
54        .cloned()
55        .collect()
56}
57
58/// True when the current directory is the disassembly root for any
59/// of the supplied multi-level rules. Each rule stores the base path
60/// it was disassembled from; if `dir_path` matches one, the caller is
61/// allowed to match that rule's child segments. Pure helper extracted
62/// from `process_files_in_directory` so the `dir_path == base`
63/// equality is testable without a temporary directory tree.
64fn is_at_base_path(dir_path: &str, base_segments: &[(String, String, bool)]) -> bool {
65    base_segments.iter().any(|(base, _, _)| dir_path == base)
66}
67
68type ProcessDirFuture<'a> = Pin<
69    Box<
70        dyn Future<Output = Result<Vec<XmlElement>, Box<dyn std::error::Error + Send + Sync>>>
71            + Send
72            + 'a,
73    >,
74>;
75
76type SegmentFuture<'a> =
77    Pin<Box<dyn Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>> + Send + 'a>>;
78
79pub struct ReassembleXmlFileHandler;
80
81impl ReassembleXmlFileHandler {
82    pub fn new() -> Self {
83        Self
84    }
85
86    pub async fn reassemble(
87        &self,
88        file_path: &str,
89        file_extension: Option<&str>,
90        post_purge: bool,
91        sidecar_specs: Option<&[SidecarSpec]>,
92    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
93        let file_path = normalize_path_unix(file_path);
94        if !self.validate_directory(&file_path).await? {
95            return Ok(());
96        }
97
98        let path = Path::new(&file_path);
99        let config = load_multi_level_config(path).await;
100        if let Some(ref config) = config {
101            // Process each rule whose path_segment exists as a directory at the
102            // disassembly root. Inner-only rules (whose segment lives nested under another
103            // rule's item dir) are handled dynamically when the parent rule walks its
104            // items; we hand them in as `nested_rules` candidates here.
105            for (i, rule) in config.rules.iter().enumerate() {
106                let segment_path = path.join(&rule.path_segment);
107                if !segment_path.is_dir() {
108                    continue;
109                }
110                let nested: Vec<MultiLevelRule> = config
111                    .rules
112                    .iter()
113                    .enumerate()
114                    .filter(|(j, _)| *j != i)
115                    .map(|(_, r)| r.clone())
116                    .collect();
117                self.reassemble_multi_level_segment(&segment_path, rule, &nested)
118                    .await?;
119            }
120        }
121
122        // Build one base-segment entry per multi-level rule so the recursive walker can
123        // recognize each rule's path_segment under the disassembly root.
124        let base_segments: Vec<(String, String, bool)> = config
125            .as_ref()
126            .map(|c| {
127                c.rules
128                    .iter()
129                    .map(|r| (file_path.clone(), r.path_segment.clone(), true))
130                    .collect()
131            })
132            .unwrap_or_default();
133        // When multi-level reassembly is done, purge the entire disassembled directory
134        let post_purge_final = post_purge || config.is_some();
135        self.reassemble_plain(
136            &file_path,
137            file_extension,
138            post_purge_final,
139            &base_segments,
140            sidecar_specs,
141        )
142        .await
143    }
144
145    /// Reassemble a single multi-level segment directory.
146    ///
147    /// For each item directory under `segment_path` (e.g. each `<dialog>/` under
148    /// `botDialogs/`):
149    ///
150    /// 1. **Phase 1 — nested rules first.** For every immediate sub-directory whose name
151    ///    matches a `nested_rules` candidate's `path_segment`, recursively reassemble
152    ///    that sub-directory as its own segment. This wraps each per-step file in
153    ///    `<wrap_root_element><inner_segment>...</inner_segment></wrap_root_element>` *before*
154    ///    the outer-level merge sees it, so multiple inner items survive as siblings
155    ///    rather than collapsing into a single bag of leaves.
156    ///
157    /// 2. **Phase 2 — flat sub-directories.** Any remaining sub-directory (anything not
158    ///    consumed by phase 1) is collapsed into a per-item `.xml` at the parent level
159    ///    via [`Self::reassemble_plain`], the original behaviour for things like
160    ///    decompose-rule outputs.
161    ///
162    /// 3. **Phase 3 — merge item.** Everything in the item directory (the `.xml` files
163    ///    written by phases 1 and 2 plus any leaf `.xml` already there) is merged into
164    ///    a single `.xml` at the parent level.
165    ///
166    /// Finally, [`ensure_segment_files_structure`] wraps every `.xml` in `segment_path`
167    /// in `<wrap_root_element><path_segment>...</path_segment></wrap_root_element>` so
168    /// the parent reassembly sees correctly-wrapped siblings.
169    fn reassemble_multi_level_segment<'a>(
170        &'a self,
171        segment_path: &'a Path,
172        rule: &'a MultiLevelRule,
173        nested_rules: &'a [MultiLevelRule],
174    ) -> SegmentFuture<'a> {
175        let segment_path = segment_path.to_path_buf();
176        let rule = rule.clone();
177        let nested_rules = nested_rules.to_vec();
178        Box::pin(async move {
179            self.reassemble_multi_level_segment_inner(&segment_path, &rule, &nested_rules)
180                .await
181        })
182    }
183
184    async fn reassemble_multi_level_segment_inner(
185        &self,
186        segment_path: &Path,
187        rule: &MultiLevelRule,
188        nested_rules: &[MultiLevelRule],
189    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
190        if !segment_path.is_dir() {
191            return Ok(());
192        }
193        let mut entries = Vec::new();
194        let mut read_dir = fs::read_dir(segment_path).await?;
195        while let Some(entry) = read_dir.next_entry().await? {
196            entries.push(entry);
197        }
198        entries.sort_by_key(|e| e.file_name());
199        for entry in entries {
200            let process_path = entry.path();
201            if !process_path.is_dir() {
202                continue;
203            }
204            let process_path_str = normalize_path_unix(&process_path.to_string_lossy());
205            let mut sub_entries = Vec::new();
206            let mut sub_read = fs::read_dir(&process_path).await?;
207            while let Some(e) = sub_read.next_entry().await? {
208                sub_entries.push(e);
209            }
210            sub_entries.sort_by_key(|e| e.file_name());
211
212            // Phase 1: drain any sub-directory that matches a nested rule's
213            // `path_segment` so it is re-wrapped before the outer merge runs.
214            let mut handled: HashSet<OsString> = HashSet::new();
215            for sub_entry in &sub_entries {
216                let sub_path: PathBuf = sub_entry.path();
217                if !sub_path.is_dir() {
218                    continue;
219                }
220                let sub_name = sub_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
221                let Some(nested_rule) = nested_rules.iter().find(|r| r.path_segment == sub_name)
222                else {
223                    continue;
224                };
225                // Pass everything *except* the rule we just matched as deeper candidates.
226                // Sibling rules remain candidates further down the tree without re-entering
227                // the same rule on a sub-dir that happens to share its name.
228                let deeper = deeper_candidate_rules(nested_rules, &nested_rule.path_segment);
229                self.reassemble_multi_level_segment(&sub_path, nested_rule, &deeper)
230                    .await?;
231                handled.insert(sub_entry.file_name());
232            }
233
234            // Phase 2: collapse remaining sub-directories into per-item .xml files at
235            // the parent level (preserves existing behaviour for non-nested-rule subdirs).
236            for sub_entry in &sub_entries {
237                let sub_path = sub_entry.path();
238                if !sub_path.is_dir() {
239                    continue;
240                }
241                if handled.contains(&sub_entry.file_name()) {
242                    continue;
243                }
244                let sub_path_str = normalize_path_unix(&sub_path.to_string_lossy());
245                self.reassemble_plain(&sub_path_str, Some("xml"), true, &[], None)
246                    .await?;
247            }
248
249            // Phase 3: merge everything in the item dir into a single .xml at the parent.
250            self.reassemble_plain(&process_path_str, Some("xml"), true, &[], None)
251                .await?;
252        }
253        ensure_segment_files_structure(
254            segment_path,
255            &rule.wrap_root_element,
256            &rule.path_segment,
257            &rule.wrap_xmlns,
258        )
259        .await?;
260        Ok(())
261    }
262
263    /// Merge and write reassembled XML (no multi-level pre-step). Used internally.
264    /// `base_segments` carries one tuple `(base_path, segment_name, extract_inner)` per
265    /// multi-level rule. When the recursive walker reaches `base_path` and finds a subdir
266    /// whose name matches one of the segment_names, that subdir's XML files are folded
267    /// into a single array under the segment_name key. When extract_inner is true, each
268    /// file's structure is `document_root > segment_name > content` and only the content
269    /// is collected; otherwise the whole root is kept.
270    async fn reassemble_plain(
271        &self,
272        file_path: &str,
273        file_extension: Option<&str>,
274        post_purge: bool,
275        base_segments: &[(String, String, bool)],
276        sidecar_specs: Option<&[SidecarSpec]>,
277    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
278        let file_path = normalize_path_unix(file_path);
279        log::debug!("Parsing directory to reassemble: {}", file_path);
280        let parsed_objects = self
281            .process_files_in_directory(file_path.to_string(), base_segments.to_vec())
282            .await?;
283
284        if parsed_objects.is_empty() {
285            log::error!(
286                "No files under {} were parsed successfully. A reassembled XML file was not created.",
287                file_path
288            );
289            return Ok(());
290        }
291
292        // merge_xml_elements only returns None when every parsed element is empty or
293        // declaration-only (no usable root). Treat that the same as "nothing parsed"
294        // rather than emitting an `<root></root>` stub.
295        let Some(mut merged) = merge_xml_elements(&parsed_objects) else {
296            log::error!(
297                "No usable root element found while merging files under {}. A reassembled XML file was not created.",
298                file_path
299            );
300            return Ok(());
301        };
302
303        // Resolve sidecar specs: use the caller-supplied slice when non-empty,
304        // otherwise auto-detect from .sidecars.json written by disassembly.
305        let auto_specs: Vec<crate::xml::types::SidecarSpec>;
306        let effective_specs: Option<&[crate::xml::types::SidecarSpec]> =
307            if sidecar_specs.is_some_and(|s| !s.is_empty()) {
308                sidecar_specs
309            } else {
310                let meta_path = Path::new(&file_path).join(".sidecars.json");
311                if let Ok(content) = fs::read_to_string(&meta_path).await {
312                    if let Ok(parsed) =
313                        serde_json::from_str::<Vec<crate::xml::types::SidecarSpec>>(&content)
314                    {
315                        auto_specs = parsed;
316                        Some(auto_specs.as_slice())
317                    } else {
318                        None
319                    }
320                } else {
321                    None
322                }
323            };
324
325        // Inject sidecar element content before key reordering so the element
326        // lands at its original position rather than being appended at the end.
327        if let Some(specs) = effective_specs {
328            inject_sidecar_elements(&file_path, &mut merged, specs).await?;
329        }
330
331        // Apply stored key order so reassembled XML matches original document order.
332        let key_order_path = Path::new(&file_path).join(".key_order.json");
333        if let Some(reordered) = read_key_order(&key_order_path)
334            .await
335            .and_then(|order| reorder_root_keys(&merged, &order))
336        {
337            merged = reordered;
338        }
339
340        let mut final_xml = build_xml_string(&merged);
341
342        // Reproduce the original file's trailing newline (or lack of one) instead of
343        // always trimming it away -- see `.trailing_newline.json` in build_disassembled_files.rs.
344        let trailing_newline_path = Path::new(&file_path).join(".trailing_newline.json");
345        if read_trailing_newline(&trailing_newline_path)
346            .await
347            .unwrap_or(false)
348        {
349            final_xml.push('\n');
350        }
351
352        let output_path = self.get_output_path(&file_path, file_extension);
353
354        fs::write(&output_path, &final_xml).await?;
355
356        // Remove sidecar files and metadata after successful injection. They are
357        // decomposition artifacts: the content is now inside the reassembled XML.
358        // Only done when post_purge is requested.
359        if post_purge {
360            if let Some(specs) = effective_specs {
361                let path = Path::new(&file_path);
362                let base = path
363                    .file_name()
364                    .and_then(|n| n.to_str())
365                    .unwrap_or("output");
366                for spec in specs {
367                    let sidecar = path.join(format!("{}.{}", base, spec.extension));
368                    fs::remove_file(&sidecar).await.ok();
369                }
370            }
371            fs::remove_dir_all(file_path).await.ok();
372        }
373
374        Ok(())
375    }
376
377    fn process_files_in_directory<'a>(
378        &'a self,
379        dir_path: String,
380        base_segments: Vec<(String, String, bool)>,
381    ) -> ProcessDirFuture<'a> {
382        Box::pin(async move {
383            let mut parsed = Vec::new();
384            let mut entries = Vec::new();
385            let mut read_dir = fs::read_dir(&dir_path).await?;
386            while let Some(entry) = read_dir.next_entry().await? {
387                entries.push(entry);
388            }
389            // Sort by full filename for deterministic cross-platform ordering
390            entries.sort_by(|a, b| {
391                let a_name = a.file_name().to_string_lossy().to_string();
392                let b_name = b.file_name().to_string_lossy().to_string();
393                a_name.cmp(&b_name)
394            });
395
396            // We are at the disassembly root for a given rule when our dir_path matches
397            // the base_path stored on that rule. Each rule shares the same base_path in
398            // the current implementation, but tracking them per-entry keeps the door open
399            // for future per-rule base_paths without another signature change.
400            let is_base = is_at_base_path(&dir_path, &base_segments);
401
402            for entry in entries {
403                let path = entry.path();
404                let file_path = normalize_path_unix(&path.to_string_lossy()).to_string();
405
406                if path.is_file() {
407                    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
408                    if !name.starts_with('.') && self.is_parsable_file(name) {
409                        if let Some(parsed_obj) = parse_to_xml_object(&file_path).await {
410                            parsed.push(parsed_obj);
411                        }
412                    }
413                } else {
414                    // Anything not a regular file is treated as a directory; symlinks and
415                    // other exotic entries simply recurse via read_dir below.
416                    let dir_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
417                    let matched_segment = if is_base {
418                        base_segments
419                            .iter()
420                            .find(|(_, seg_name, _)| seg_name == dir_name)
421                            .cloned()
422                    } else {
423                        None
424                    };
425                    if let Some((_, segment_name, extract_inner)) = matched_segment {
426                        let segment_element = self
427                            .collect_segment_as_array(&file_path, &segment_name, extract_inner)
428                            .await?;
429                        if let Some(el) = segment_element {
430                            parsed.push(el);
431                        }
432                    } else {
433                        let sub_parsed = self
434                            .process_files_in_directory(file_path, base_segments.clone())
435                            .await?;
436                        parsed.extend(sub_parsed);
437                    }
438                }
439            }
440
441            Ok(parsed)
442        })
443    }
444
445    /// Collect all .xml files in a directory, parse each, and build one element with
446    /// root_key and single key segment_name whose value is array of each file's content.
447    /// When extract_inner is true, each file has root > segment_name > content; we push that content.
448    async fn collect_segment_as_array(
449        &self,
450        segment_dir: &str,
451        segment_name: &str,
452        extract_inner: bool,
453    ) -> Result<Option<XmlElement>, Box<dyn std::error::Error + Send + Sync>> {
454        let mut xml_files = Vec::new();
455        let mut read_dir = fs::read_dir(segment_dir).await?;
456        while let Some(entry) = read_dir.next_entry().await? {
457            let path = entry.path();
458            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
459            if path.is_file() && !name.starts_with('.') && self.is_parsable_file(name) {
460                xml_files.push(normalize_path_unix(&path.to_string_lossy()));
461            }
462        }
463        xml_files.sort();
464
465        let mut root_contents = Vec::new();
466        let mut first_xml: Option<(String, Option<Value>)> = None;
467        for file_path in &xml_files {
468            // parse_to_xml_object always yields a JSON object on success; treat any other
469            // shape (including parse failure) as a skip without branching explicitly.
470            let Some(parsed) = parse_to_xml_object(file_path).await else {
471                continue;
472            };
473            let obj_owned = parsed.as_object().cloned().unwrap_or_default();
474            let obj = &obj_owned;
475            let Some(root_key) = obj.keys().find(|k| *k != "?xml").cloned() else {
476                continue;
477            };
478            let root_val = obj
479                .get(&root_key)
480                .cloned()
481                .unwrap_or(Value::Object(serde_json::Map::new()));
482            let mut content = if extract_inner {
483                root_val
484                    .get(segment_name)
485                    .cloned()
486                    .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
487            } else {
488                root_val
489            };
490            // Inner segment element (e.g. programProcesses) should not have xmlns in output
491            if extract_inner {
492                content = strip_xmlns_from_value(content);
493            }
494            root_contents.push(content);
495            if first_xml.is_none() {
496                first_xml = Some((root_key, obj.get("?xml").cloned()));
497            }
498        }
499        if root_contents.is_empty() {
500            return Ok(None);
501        }
502        let (root_key, decl_opt) = first_xml.unwrap();
503        let mut content = serde_json::Map::new();
504        content.insert(segment_name.to_string(), Value::Array(root_contents));
505        let mut top = serde_json::Map::new();
506        if let Some(decl) = decl_opt {
507            top.insert("?xml".to_string(), decl);
508        } else {
509            let mut d = serde_json::Map::new();
510            d.insert("@version".to_string(), Value::String("1.0".to_string()));
511            d.insert("@encoding".to_string(), Value::String("UTF-8".to_string()));
512            top.insert("?xml".to_string(), Value::Object(d));
513        }
514        top.insert(root_key, Value::Object(content));
515        Ok(Some(Value::Object(top)))
516    }
517
518    fn is_parsable_file(&self, file_name: &str) -> bool {
519        let lower = file_name.to_lowercase();
520        lower.ends_with(".xml")
521            || lower.ends_with(".json")
522            || lower.ends_with(".json5")
523            || lower.ends_with(".yaml")
524            || lower.ends_with(".yml")
525    }
526
527    async fn validate_directory(
528        &self,
529        path: &str,
530    ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
531        let meta = fs::metadata(path).await?;
532        if !meta.is_dir() {
533            log::error!(
534                "The provided path to reassemble is not a directory: {}",
535                path
536            );
537            return Ok(false);
538        }
539        Ok(true)
540    }
541
542    fn get_output_path(&self, dir_path: &str, extension: Option<&str>) -> String {
543        let path = Path::new(dir_path);
544        let parent = path.parent().unwrap_or(Path::new("."));
545        let base_name = path
546            .file_name()
547            .and_then(|n| n.to_str())
548            .unwrap_or("output");
549        let ext = extension.unwrap_or("xml");
550        parent
551            .join(format!("{}.{}", base_name, ext))
552            .to_string_lossy()
553            .to_string()
554    }
555}
556
557impl Default for ReassembleXmlFileHandler {
558    fn default() -> Self {
559        Self::new()
560    }
561}
562
563/// Convert `content` (in whatever format the sidecar file uses) to `target_format`.
564///
565/// - `"json"` → parse as YAML (superset of JSON) then emit as pretty JSON
566/// - `"yaml"` / `"yml"` → only convert when content is strict JSON; YAML passes through
567/// - anything else → pass through unchanged
568///
569/// Falls back to raw content with a warning when conversion fails.
570fn convert_to_format(content: &str, target_format: &str) -> String {
571    match target_format.to_ascii_lowercase().as_str() {
572        "json" => {
573            match serde_saphyr::from_str::<serde_json::Value>(content) {
574                // Serializing a serde_json::Value cannot fail.
575                Ok(val) => {
576                    serde_json::to_string_pretty(&val).unwrap_or_else(|_| content.to_string())
577                }
578                Err(e) => {
579                    log::warn!("sidecar reassemble: could not parse content for JSON conversion ({e}); using raw content");
580                    content.to_string()
581                }
582            }
583        }
584        "yaml" | "yml" => {
585            if serde_json::from_str::<serde_json::Value>(content).is_ok() {
586                match serde_json::from_str::<serde_json::Value>(content)
587                    .ok()
588                    .and_then(|v| serde_saphyr::to_string(&v).ok())
589                {
590                    Some(yaml) => yaml,
591                    None => {
592                        log::warn!(
593                            "sidecar reassemble: YAML serialization failed; using raw content"
594                        );
595                        content.to_string()
596                    }
597                }
598            } else {
599                content.to_string()
600            }
601        }
602        _ => content.to_string(),
603    }
604}
605
606/// Read sidecar files and inject their content back into the merged XML value
607/// before serialisation.
608///
609/// Each sidecar is located inside the decomposed directory itself
610/// (e.g. `MySvc/MySvc.yaml`). If a sidecar is absent (element was not in
611/// the original XML, or was never extracted), the spec is silently skipped.
612///
613/// The injected value uses the `{"#raw-text": content}` shape that `build_xml_string`
614/// writes with `partial_escape`: mandatory XML chars (`<`, `>`, `&`) are escaped
615/// but `"` is left as-is so YAML content round-trips without `&quot;` inflation.
616async fn inject_sidecar_elements(
617    dir_path: &str,
618    merged: &mut XmlElement,
619    specs: &[SidecarSpec],
620) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
621    let path = Path::new(dir_path);
622    let base = path
623        .file_name()
624        .and_then(|n| n.to_str())
625        .unwrap_or("output");
626
627    let root_key = merged
628        .as_object()
629        .and_then(|o| o.keys().find(|k| *k != "?xml").cloned());
630    let Some(root_key) = root_key else {
631        return Ok(());
632    };
633
634    if let Some(root_val) = merged.as_object_mut().and_then(|o| o.get_mut(&root_key)) {
635        if let Some(root_obj) = root_val.as_object_mut() {
636            for spec in specs {
637                let sidecar_path = path.join(format!("{}.{}", base, spec.extension));
638                let Ok(content) = fs::read_to_string(&sidecar_path).await else {
639                    continue;
640                };
641                // When the original XML embedded a different format than the sidecar
642                // extension (e.g. JSON schema extracted to a .yaml sidecar), convert
643                // the sidecar content back to the original format before injecting.
644                let final_content = match &spec.original_format {
645                    Some(fmt) => convert_to_format(&content, fmt),
646                    None => content,
647                };
648                root_obj.insert(
649                    spec.element.clone(),
650                    serde_json::json!({ "#raw-text": final_content }),
651                );
652            }
653        }
654    }
655
656    Ok(())
657}
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662    use serde_json::json;
663
664    #[test]
665    #[allow(clippy::default_constructed_unit_structs)]
666    fn reassemble_handler_default_equals_new() {
667        let _ = ReassembleXmlFileHandler::default();
668    }
669
670    #[test]
671    fn strip_xmlns_from_value_passes_non_object_through() {
672        let s = Value::String("hello".to_string());
673        assert_eq!(
674            strip_xmlns_from_value(s),
675            Value::String("hello".to_string())
676        );
677        let arr = json!([1, 2]);
678        assert_eq!(strip_xmlns_from_value(arr.clone()), arr);
679    }
680
681    #[test]
682    fn strip_xmlns_from_value_removes_xmlns_key() {
683        let obj = json!({ "@xmlns": "ns", "child": 1 });
684        let stripped = strip_xmlns_from_value(obj);
685        let map = stripped.as_object().unwrap();
686        assert!(map.get("@xmlns").is_none());
687        assert_eq!(map.get("child").and_then(|v| v.as_i64()), Some(1));
688    }
689
690    #[test]
691    fn is_parsable_file_recognises_supported_extensions() {
692        let h = ReassembleXmlFileHandler::new();
693        assert!(h.is_parsable_file("a.xml"));
694        assert!(h.is_parsable_file("a.json"));
695        assert!(h.is_parsable_file("a.json5"));
696        assert!(h.is_parsable_file("a.yaml"));
697        assert!(h.is_parsable_file("a.yml"));
698        assert!(h.is_parsable_file("A.XML"));
699        assert!(!h.is_parsable_file("a.txt"));
700    }
701
702    #[test]
703    fn get_output_path_appends_extension_and_uses_parent_dir() {
704        let h = ReassembleXmlFileHandler::new();
705        let out = h.get_output_path("/tmp/foo", Some("xml"));
706        assert!(out.ends_with("foo.xml"));
707        let out_default = h.get_output_path("/tmp/bar", None);
708        assert!(out_default.ends_with("bar.xml"));
709        // No parent - uses "." fallback
710        assert_eq!(h.get_output_path("only", Some("json")), "only.json");
711    }
712
713    #[tokio::test]
714    async fn reassemble_multi_level_segment_noop_when_not_dir() {
715        let h = ReassembleXmlFileHandler::new();
716        let tmp = tempfile::tempdir().unwrap();
717        let file = tmp.path().join("not_a_dir.txt");
718        tokio::fs::write(&file, "hi").await.unwrap();
719        let rule = crate::xml::types::MultiLevelRule {
720            file_pattern: String::new(),
721            root_to_strip: String::new(),
722            unique_id_elements: String::new(),
723            path_segment: String::new(),
724            wrap_root_element: "Root".to_string(),
725            wrap_xmlns: String::new(),
726        };
727        h.reassemble_multi_level_segment(&file, &rule, &[])
728            .await
729            .unwrap();
730    }
731
732    #[tokio::test]
733    async fn reassemble_multi_level_segment_skips_files_in_segment_root() {
734        let h = ReassembleXmlFileHandler::new();
735        let tmp = tempfile::tempdir().unwrap();
736        let segment = tmp.path().join("segment");
737        tokio::fs::create_dir(&segment).await.unwrap();
738        // A bare file inside the segment dir should be skipped (not a subdir).
739        tokio::fs::write(segment.join("stray.txt"), "x")
740            .await
741            .unwrap();
742        let rule = crate::xml::types::MultiLevelRule {
743            file_pattern: String::new(),
744            root_to_strip: String::new(),
745            unique_id_elements: String::new(),
746            path_segment: "segment".to_string(),
747            wrap_root_element: "Root".to_string(),
748            wrap_xmlns: "http://example.com".to_string(),
749        };
750        h.reassemble_multi_level_segment(&segment, &rule, &[])
751            .await
752            .unwrap();
753    }
754
755    #[tokio::test]
756    async fn collect_segment_as_array_returns_none_for_empty_dir() {
757        let h = ReassembleXmlFileHandler::new();
758        let tmp = tempfile::tempdir().unwrap();
759        let out = h
760            .collect_segment_as_array(tmp.path().to_str().unwrap(), "seg", true)
761            .await
762            .unwrap();
763        assert!(out.is_none());
764    }
765
766    #[tokio::test]
767    async fn collect_segment_as_array_skips_unparseable_and_empty_roots() {
768        let h = ReassembleXmlFileHandler::new();
769        let tmp = tempfile::tempdir().unwrap();
770        // Unparseable XML
771        tokio::fs::write(tmp.path().join("bad.xml"), "<<")
772            .await
773            .unwrap();
774        // Valid XML but only declaration and no root after parse
775        tokio::fs::write(tmp.path().join("only-decl.xml"), "")
776            .await
777            .unwrap();
778        // Hidden file is skipped
779        tokio::fs::write(tmp.path().join(".hidden.xml"), "<r/>")
780            .await
781            .unwrap();
782        let out = h
783            .collect_segment_as_array(tmp.path().to_str().unwrap(), "seg", false)
784            .await
785            .unwrap();
786        assert!(out.is_none());
787    }
788
789    #[tokio::test]
790    async fn collect_segment_as_array_without_xml_decl_inserts_default_decl() {
791        // XML files without a `<?xml ?>` declaration: the `else` branch in
792        // collect_segment_as_array must synthesize a default declaration with
793        // version="1.0" and encoding="UTF-8".
794        let h = ReassembleXmlFileHandler::new();
795        let tmp = tempfile::tempdir().unwrap();
796        tokio::fs::write(
797            tmp.path().join("a.xml"),
798            r#"<Root><seg><x>1</x></seg></Root>"#,
799        )
800        .await
801        .unwrap();
802        let out = h
803            .collect_segment_as_array(tmp.path().to_str().unwrap(), "seg", true)
804            .await
805            .unwrap()
806            .unwrap();
807        let obj = out.as_object().unwrap();
808        let decl = obj
809            .get("?xml")
810            .and_then(|v| v.as_object())
811            .expect("default declaration must be inserted when XML has none");
812        assert_eq!(decl.get("@version").and_then(|v| v.as_str()), Some("1.0"));
813        assert_eq!(
814            decl.get("@encoding").and_then(|v| v.as_str()),
815            Some("UTF-8")
816        );
817    }
818
819    #[tokio::test]
820    async fn collect_segment_as_array_with_xml_decl_preserves_it() {
821        // XML file WITH a `<?xml ?>` declaration: `decl_opt` is Some → line 438
822        // `top.insert("?xml", decl)` is executed (the `if let Some(decl)` branch).
823        let h = ReassembleXmlFileHandler::new();
824        let tmp = tempfile::tempdir().unwrap();
825        tokio::fs::write(
826            tmp.path().join("a.xml"),
827            r#"<?xml version="1.0" encoding="UTF-8"?><Root><seg><x>1</x></seg></Root>"#,
828        )
829        .await
830        .unwrap();
831        let out = h
832            .collect_segment_as_array(tmp.path().to_str().unwrap(), "seg", true)
833            .await
834            .unwrap()
835            .unwrap();
836        let obj = out.as_object().unwrap();
837        let decl = obj
838            .get("?xml")
839            .and_then(|v| v.as_object())
840            .expect("?xml declaration must be preserved from source");
841        assert_eq!(decl.get("@version").and_then(|v| v.as_str()), Some("1.0"));
842        assert_eq!(
843            decl.get("@encoding").and_then(|v| v.as_str()),
844            Some("UTF-8")
845        );
846    }
847
848    #[tokio::test]
849    async fn collect_segment_as_array_without_extract_inner_wraps_root() {
850        let h = ReassembleXmlFileHandler::new();
851        let tmp = tempfile::tempdir().unwrap();
852        tokio::fs::write(tmp.path().join("a.xml"), r#"<Root><child>1</child></Root>"#)
853            .await
854            .unwrap();
855        let out = h
856            .collect_segment_as_array(tmp.path().to_str().unwrap(), "seg", false)
857            .await
858            .unwrap()
859            .unwrap();
860        let obj = out.as_object().unwrap();
861        assert!(obj.contains_key("?xml"));
862        let root = obj.get("Root").and_then(|r| r.as_object()).unwrap();
863        assert!(root.get("seg").and_then(|v| v.as_array()).is_some());
864    }
865
866    fn rule_with_segment(segment: &str) -> MultiLevelRule {
867        MultiLevelRule {
868            file_pattern: String::new(),
869            root_to_strip: String::new(),
870            unique_id_elements: String::new(),
871            path_segment: segment.to_string(),
872            wrap_root_element: String::new(),
873            wrap_xmlns: String::new(),
874        }
875    }
876
877    #[test]
878    fn deeper_candidate_rules_excludes_the_matched_segment() {
879        // The matched rule must be filtered out, otherwise the
880        // recursion would re-enter that rule when a child directory
881        // happens to share its `path_segment`.
882        let rules = vec![rule_with_segment("seg_a"), rule_with_segment("seg_b")];
883        let deeper = deeper_candidate_rules(&rules, "seg_a");
884        assert_eq!(deeper.len(), 1);
885        assert_eq!(deeper[0].path_segment, "seg_b");
886    }
887
888    #[test]
889    fn deeper_candidate_rules_keeps_all_when_no_segment_matches() {
890        // When `exclude_path_segment` doesn't correspond to any rule
891        // the input is forwarded unchanged. Pins the `!= -> ==` mutant
892        // which would otherwise return an empty vec here.
893        let rules = vec![rule_with_segment("seg_a"), rule_with_segment("seg_b")];
894        let deeper = deeper_candidate_rules(&rules, "missing");
895        assert_eq!(deeper.len(), 2);
896    }
897
898    #[test]
899    fn deeper_candidate_rules_returns_empty_for_empty_input() {
900        let deeper: Vec<MultiLevelRule> = deeper_candidate_rules(&[], "anything");
901        assert!(deeper.is_empty());
902    }
903
904    #[test]
905    fn is_at_base_path_true_when_dir_matches_any_segment() {
906        let segs = vec![
907            ("/base/other".to_string(), "seg1".to_string(), false),
908            ("/base/here".to_string(), "seg2".to_string(), false),
909        ];
910        assert!(is_at_base_path("/base/here", &segs));
911    }
912
913    #[test]
914    fn is_at_base_path_false_when_dir_matches_nothing() {
915        let segs = vec![("/base/a".to_string(), "seg".to_string(), false)];
916        assert!(!is_at_base_path("/base/b", &segs));
917    }
918
919    #[test]
920    fn is_at_base_path_false_for_empty_segments() {
921        let segs: Vec<(String, String, bool)> = Vec::new();
922        assert!(!is_at_base_path("/anywhere", &segs));
923    }
924
925    // Pins the `delete ! in is_some_and(|s| !s.is_empty())` mutant at line 299.
926    // When sidecar_specs is Some(&[]) the caller supplied nothing useful, so the
927    // code must fall through to auto-detect via .sidecars.json — not treat the
928    // empty slice as authoritative.
929    #[tokio::test]
930    async fn reassemble_plain_some_empty_sidecar_specs_falls_through_to_auto_detect() {
931        let h = ReassembleXmlFileHandler::new();
932        let tmp = tempfile::tempdir().unwrap();
933        let dir = tmp.path().join("mydir");
934        tokio::fs::create_dir(&dir).await.unwrap();
935
936        tokio::fs::write(
937            dir.join("a.xml"),
938            r#"<?xml version="1.0" encoding="UTF-8"?><Root><Child>hello</Child></Root>"#,
939        )
940        .await
941        .unwrap();
942
943        tokio::fs::write(
944            dir.join(".sidecars.json"),
945            r#"[{"element":"Notes","extension":"yaml"}]"#,
946        )
947        .await
948        .unwrap();
949
950        // Sidecar file name = directory name + extension (matches inject_sidecar_elements logic).
951        tokio::fs::write(dir.join("mydir.yaml"), "key: value")
952            .await
953            .unwrap();
954
955        h.reassemble_plain(dir.to_str().unwrap(), Some("xml"), false, &[], Some(&[]))
956            .await
957            .unwrap();
958
959        let output = tokio::fs::read_to_string(tmp.path().join("mydir.xml"))
960            .await
961            .unwrap();
962        assert!(
963            output.contains("key: value"),
964            "sidecar content missing — auto-detect did not run:\n{output}"
965        );
966    }
967
968    // Pins `delete match arm "json"` mutant: without the arm, YAML input to
969    // convert_to_format("json") falls through to `_ =>` and returns raw YAML.
970    #[test]
971    fn convert_to_format_yaml_to_json() {
972        let yaml = "openapi: 3.0.1\ninfo:\n  title: \"Test API\"\n  version: 1.0.0\n";
973        let out = convert_to_format(yaml, "json");
974        let val: serde_json::Value = serde_json::from_str(&out).expect("output must be valid JSON");
975        assert_eq!(val["openapi"], "3.0.1");
976        assert_eq!(val["info"]["title"], "Test API");
977        assert_eq!(val["info"]["version"], "1.0.0");
978    }
979
980    // Pins `delete match arm "yaml" | "yml"` mutant: without the arm, JSON input
981    // to convert_to_format("yaml") falls through to `_ =>` and returns raw JSON.
982    #[test]
983    fn convert_to_format_json_to_yaml() {
984        let json = r#"{"key":"value","num":42}"#;
985        let out = convert_to_format(json, "yaml");
986        assert!(
987            serde_json::from_str::<serde_json::Value>(&out).is_err(),
988            "output must be YAML format, not raw JSON: {out}"
989        );
990        let val: serde_json::Value =
991            serde_saphyr::from_str(&out).expect("output must be valid YAML");
992        assert_eq!(val["key"], "value");
993        assert_eq!(val["num"], 42);
994    }
995
996    #[test]
997    fn convert_to_format_yml_extension_same_as_yaml() {
998        let json = r#"{"x":true}"#;
999        let out = convert_to_format(json, "yml");
1000        let val: serde_json::Value = serde_saphyr::from_str(&out).unwrap();
1001        assert_eq!(val["x"], true);
1002    }
1003
1004    #[test]
1005    fn convert_to_format_yaml_passes_through_unchanged() {
1006        // Pure YAML fails serde_json parse → returned as-is without re-serialization.
1007        let yaml = "title: \"@AuraEnabled\"\nversion: 1.0.0\n";
1008        assert_eq!(convert_to_format(yaml, "yaml"), yaml);
1009    }
1010
1011    #[test]
1012    fn convert_to_format_unknown_extension_passes_through() {
1013        let raw = "arbitrary content";
1014        assert_eq!(convert_to_format(raw, "txt"), raw);
1015        assert_eq!(convert_to_format(raw, ""), raw);
1016    }
1017
1018    #[test]
1019    fn convert_to_format_malformed_falls_back_to_raw() {
1020        let bad = "{{{{ not valid json or yaml at all >>>>>";
1021        assert_eq!(convert_to_format(bad, "json"), bad);
1022    }
1023
1024    #[test]
1025    fn convert_to_format_non_string_key_falls_back_to_raw() {
1026        // YAML permits compound (sequence) mapping keys via explicit-key
1027        // syntax; JSON object keys must be strings, so parsing this into a
1028        // serde_json::Value fails and the raw content must come back unchanged.
1029        let yaml_with_sequence_key = "? [a, b]\n: value\n";
1030        assert_eq!(
1031            convert_to_format(yaml_with_sequence_key, "json"),
1032            yaml_with_sequence_key
1033        );
1034    }
1035
1036    #[tokio::test]
1037    async fn reassemble_plain_uses_caller_supplied_sidecar_specs_directly() {
1038        // Exercises the `sidecar_specs` (non-empty, caller-supplied) arm
1039        // rather than falling through to `.sidecars.json` auto-detection.
1040        let h = ReassembleXmlFileHandler::new();
1041        let tmp = tempfile::tempdir().unwrap();
1042        let dir = tmp.path().join("mydir");
1043        tokio::fs::create_dir(&dir).await.unwrap();
1044
1045        tokio::fs::write(
1046            dir.join("a.xml"),
1047            r#"<?xml version="1.0" encoding="UTF-8"?><Root><Child>hello</Child></Root>"#,
1048        )
1049        .await
1050        .unwrap();
1051        // Deliberately no .sidecars.json — the caller-supplied spec must be used as-is.
1052        tokio::fs::write(dir.join("mydir.yaml"), "key: value")
1053            .await
1054            .unwrap();
1055
1056        let specs = [SidecarSpec {
1057            element: "Notes".to_string(),
1058            extension: "yaml".to_string(),
1059            original_format: None,
1060        }];
1061        h.reassemble_plain(dir.to_str().unwrap(), Some("xml"), false, &[], Some(&specs))
1062            .await
1063            .unwrap();
1064
1065        let output = tokio::fs::read_to_string(tmp.path().join("mydir.xml"))
1066            .await
1067            .unwrap();
1068        assert!(
1069            output.contains("key: value"),
1070            "caller-supplied sidecar spec was not used:\n{output}"
1071        );
1072    }
1073
1074    #[tokio::test]
1075    async fn reassemble_plain_ignores_malformed_sidecars_json() {
1076        // Exercises the `Err(_)` arm of parsing `.sidecars.json`: malformed
1077        // content must not fail reassembly, just skip sidecar injection.
1078        let h = ReassembleXmlFileHandler::new();
1079        let tmp = tempfile::tempdir().unwrap();
1080        let dir = tmp.path().join("mydir");
1081        tokio::fs::create_dir(&dir).await.unwrap();
1082
1083        tokio::fs::write(
1084            dir.join("a.xml"),
1085            r#"<?xml version="1.0" encoding="UTF-8"?><Root><Child>hello</Child></Root>"#,
1086        )
1087        .await
1088        .unwrap();
1089        tokio::fs::write(dir.join(".sidecars.json"), "not valid json")
1090            .await
1091            .unwrap();
1092
1093        h.reassemble_plain(dir.to_str().unwrap(), Some("xml"), false, &[], None)
1094            .await
1095            .unwrap();
1096
1097        let output = tokio::fs::read_to_string(tmp.path().join("mydir.xml"))
1098            .await
1099            .unwrap();
1100        assert!(output.contains("Child"), "reassembly must still succeed");
1101    }
1102
1103    #[tokio::test]
1104    async fn reassemble_plain_post_purge_removes_sidecar_files() {
1105        // Exercises the post_purge branch that removes sidecar files (and
1106        // the disassembled directory) once their content has been injected.
1107        let h = ReassembleXmlFileHandler::new();
1108        let tmp = tempfile::tempdir().unwrap();
1109        let dir = tmp.path().join("mydir");
1110        tokio::fs::create_dir(&dir).await.unwrap();
1111
1112        tokio::fs::write(
1113            dir.join("a.xml"),
1114            r#"<?xml version="1.0" encoding="UTF-8"?><Root><Child>hello</Child></Root>"#,
1115        )
1116        .await
1117        .unwrap();
1118        let sidecar_path = dir.join("mydir.yaml");
1119        tokio::fs::write(&sidecar_path, "key: value").await.unwrap();
1120
1121        let specs = [SidecarSpec {
1122            element: "Notes".to_string(),
1123            extension: "yaml".to_string(),
1124            original_format: None,
1125        }];
1126        h.reassemble_plain(dir.to_str().unwrap(), Some("xml"), true, &[], Some(&specs))
1127            .await
1128            .unwrap();
1129
1130        assert!(!dir.exists(), "post_purge must remove the disassembled dir");
1131        let output = tokio::fs::read_to_string(tmp.path().join("mydir.xml"))
1132            .await
1133            .unwrap();
1134        assert!(output.contains("key: value"));
1135    }
1136
1137    #[tokio::test]
1138    async fn inject_sidecar_elements_ok_when_no_root_key() {
1139        // A merged value with no usable root key (only "?xml") must return
1140        // Ok(()) without attempting injection.
1141        let mut merged: XmlElement = json!({ "?xml": { "@version": "1.0" } });
1142        let specs = [SidecarSpec {
1143            element: "Notes".to_string(),
1144            extension: "yaml".to_string(),
1145            original_format: None,
1146        }];
1147        inject_sidecar_elements("does-not-matter", &mut merged, &specs)
1148            .await
1149            .unwrap();
1150        assert_eq!(merged, json!({ "?xml": { "@version": "1.0" } }));
1151    }
1152
1153    #[tokio::test]
1154    async fn inject_sidecar_elements_skips_missing_sidecar_file() {
1155        // When the sidecar file referenced by the spec doesn't exist on disk,
1156        // the spec must be silently skipped rather than erroring.
1157        let tmp = tempfile::tempdir().unwrap();
1158        let dir = tmp.path().join("mydir");
1159        tokio::fs::create_dir(&dir).await.unwrap();
1160        let mut merged: XmlElement = json!({ "Root": { "Child": { "#text": "hello" } } });
1161        let specs = [SidecarSpec {
1162            element: "Notes".to_string(),
1163            extension: "yaml".to_string(),
1164            original_format: None,
1165        }];
1166        inject_sidecar_elements(dir.to_str().unwrap(), &mut merged, &specs)
1167            .await
1168            .unwrap();
1169        assert_eq!(merged, json!({ "Root": { "Child": { "#text": "hello" } } }));
1170    }
1171}