Skip to main content

blackline_core/
tree.rs

1//! Path-addressed XML tree mutations.
2//!
3//! This is the unopinionated edit layer. Format-specific operations
4//! (replace a phrase, wrap a tracked insertion, set a cell) compile down
5//! to [`TreeOp`]s against a part's [`crate::XmlDocument`].
6
7use serde::{Deserialize, Serialize};
8
9use crate::error::CoreError;
10use crate::xml::XmlNode;
11
12/// One step in a node path.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum PathStep {
15    /// The `n`th child node (any kind), 0-based.
16    Index(usize),
17    /// The `n`th child *element* with this local name, 0-based.
18    Name {
19        /// Local name to match, ignoring any namespace prefix.
20        local: String,
21        /// 0-based position among sibling elements sharing that local name.
22        index: usize,
23    },
24}
25
26/// A path from a document root to a descendant.
27///
28/// String form accepts either style, mixed:
29///
30/// ```text
31/// document/body/p[2]/r[0]/t
32/// 0/1/3
33/// document/0/t
34/// ```
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct NodePath {
37    /// Path steps from the root (root itself is implied; the first step
38    /// selects a child of the root, or the root when the path is empty).
39    pub steps: Vec<PathStep>,
40}
41
42impl NodePath {
43    /// Empty path — the root itself.
44    pub fn root() -> Self {
45        Self { steps: Vec::new() }
46    }
47
48    /// Parse a `/`-separated path string.
49    pub fn parse(s: &str) -> Result<Self, CoreError> {
50        let s = s.trim().trim_start_matches('/');
51        if s.is_empty() {
52            return Ok(Self::root());
53        }
54        let mut steps = Vec::new();
55        for raw in s.split('/') {
56            let raw = raw.trim();
57            if raw.is_empty() {
58                continue;
59            }
60            steps.push(parse_step(raw)?);
61        }
62        Ok(Self { steps })
63    }
64
65    /// Resolve this path against `root`. The empty path returns `root`.
66    pub fn resolve<'a>(&self, root: &'a XmlNode) -> Result<&'a XmlNode, CoreError> {
67        let mut cur = root;
68        for (i, step) in self.steps.iter().enumerate() {
69            cur = step_get(cur, step).ok_or_else(|| {
70                CoreError::Path(format!(
71                    "failed at step {i} ({step:?}) in {}",
72                    self.display()
73                ))
74            })?;
75        }
76        Ok(cur)
77    }
78
79    /// Mutable resolve.
80    pub fn resolve_mut<'a>(&self, root: &'a mut XmlNode) -> Result<&'a mut XmlNode, CoreError> {
81        let mut cur = root;
82        for (i, step) in self.steps.iter().enumerate() {
83            let next_exists = step_get(cur, step).is_some();
84            if !next_exists {
85                return Err(CoreError::Path(format!(
86                    "failed at step {i} ({step:?}) in {}",
87                    self.display()
88                )));
89            }
90            cur = step_get_mut(cur, step).expect("checked");
91        }
92        Ok(cur)
93    }
94
95    /// Human-readable form.
96    pub fn display(&self) -> String {
97        if self.steps.is_empty() {
98            return "/".into();
99        }
100        let mut out = String::new();
101        for step in &self.steps {
102            out.push('/');
103            match step {
104                PathStep::Index(i) => out.push_str(&i.to_string()),
105                PathStep::Name { local, index } => {
106                    out.push_str(local);
107                    out.push('[');
108                    out.push_str(&index.to_string());
109                    out.push(']');
110                }
111            }
112        }
113        out
114    }
115
116    /// True when this path is the document element.
117    pub fn is_root(&self) -> bool {
118        self.steps.is_empty()
119    }
120
121    /// Parent path, or `None` at the root.
122    pub fn parent(&self) -> Option<Self> {
123        if self.steps.is_empty() {
124            None
125        } else {
126            Some(Self {
127                steps: self.steps[..self.steps.len() - 1].to_vec(),
128            })
129        }
130    }
131
132    /// Path string for a [`TreeOp`] (`""` at the root, no leading slash).
133    pub fn to_op_path(&self) -> String {
134        if self.steps.is_empty() {
135            String::new()
136        } else {
137            self.display().trim_start_matches('/').to_string()
138        }
139    }
140}
141
142/// Raw child index of `path` among its parent's children (all kinds).
143///
144/// [`TreeOp::RemoveChild`] and [`TreeOp::InsertChild`] use this index space,
145/// not the named `p[0]` occurrence.
146pub fn child_index(root: &XmlNode, path: &NodePath) -> Result<usize, CoreError> {
147    let parent_path = path
148        .parent()
149        .ok_or_else(|| CoreError::Path("root has no parent index".into()))?;
150    let parent = parent_path.resolve(root)?;
151    let last = path
152        .steps
153        .last()
154        .ok_or_else(|| CoreError::Path("root has no parent index".into()))?;
155    match last {
156        PathStep::Index(i) => {
157            if *i < parent.children().len() {
158                Ok(*i)
159            } else {
160                Err(CoreError::Path(format!(
161                    "index {i} out of range on {}",
162                    parent_path.display()
163                )))
164            }
165        }
166        PathStep::Name { local, index } => {
167            let mut seen = 0usize;
168            for (i, child) in parent.children().iter().enumerate() {
169                if child.is_element_with_local_name(local) {
170                    if seen == *index {
171                        return Ok(i);
172                    }
173                    seen += 1;
174                }
175            }
176            Err(CoreError::Path(format!(
177                "{local}[{index}] missing on {}",
178                parent_path.display()
179            )))
180        }
181    }
182}
183
184fn parse_step(raw: &str) -> Result<PathStep, CoreError> {
185    if let Some((name, rest)) = raw.split_once('[') {
186        let idx = rest
187            .trim_end_matches(']')
188            .parse::<usize>()
189            .map_err(|_| CoreError::Path(format!("invalid index in path step '{raw}'")))?;
190        if name.chars().all(|c| c.is_ascii_digit()) {
191            return Err(CoreError::Path(format!(
192                "numeric name with bracket is ambiguous: '{raw}'"
193            )));
194        }
195        let local = name.split(':').next_back().unwrap_or(name).to_string();
196        return Ok(PathStep::Name { local, index: idx });
197    }
198    if raw.chars().all(|c| c.is_ascii_digit()) {
199        let i = raw
200            .parse::<usize>()
201            .map_err(|_| CoreError::Path(format!("invalid index '{raw}'")))?;
202        return Ok(PathStep::Index(i));
203    }
204    let local = raw.split(':').next_back().unwrap_or(raw).to_string();
205    Ok(PathStep::Name { local, index: 0 })
206}
207
208fn step_get<'a>(node: &'a XmlNode, step: &PathStep) -> Option<&'a XmlNode> {
209    match step {
210        PathStep::Index(i) => node.children().get(*i),
211        PathStep::Name { local, index } => node.child_named(local, *index),
212    }
213}
214
215fn step_get_mut<'a>(node: &'a mut XmlNode, step: &PathStep) -> Option<&'a mut XmlNode> {
216    match step {
217        PathStep::Index(i) => node.try_children_mut()?.get_mut(*i),
218        PathStep::Name { local, index } => node.child_named_mut(local, *index),
219    }
220}
221
222/// A single tree mutation. Deserializable from JSON so the CLI and agents
223/// can drive the XML layer directly.
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(tag = "action")]
226pub enum TreeOp {
227    /// Set or insert an attribute on the node at `path`.
228    #[serde(rename = "set_attr")]
229    SetAttr {
230        /// Node path.
231        path: String,
232        /// Attribute name (`w:val`, `xml:space`, …).
233        name: String,
234        /// Attribute value.
235        value: String,
236    },
237    /// Remove an attribute.
238    #[serde(rename = "remove_attr")]
239    RemoveAttr {
240        /// Node path.
241        path: String,
242        /// Attribute name.
243        name: String,
244    },
245    /// Replace the node's children with a text node.
246    #[serde(rename = "set_text")]
247    SetText {
248        /// Node path.
249        path: String,
250        /// New text.
251        text: String,
252    },
253    /// Insert a child at `index` (0-based). The child is parsed as an XML
254    /// fragment (a single element) or used as a text node when it does not
255    /// start with `<`.
256    #[serde(rename = "insert_child")]
257    InsertChild {
258        /// Parent path.
259        path: String,
260        /// Insertion index. Omit to append.
261        #[serde(default)]
262        index: Option<usize>,
263        /// XML fragment or plain text.
264        xml: String,
265    },
266    /// Remove the child at `index`.
267    #[serde(rename = "remove_child")]
268    RemoveChild {
269        /// Parent path.
270        path: String,
271        /// Child index.
272        index: usize,
273    },
274    /// Replace the node at `path` with a parsed fragment.
275    #[serde(rename = "replace")]
276    Replace {
277        /// Node path.
278        path: String,
279        /// XML fragment or plain text.
280        xml: String,
281    },
282    /// Change the element's qualified name. Children and attributes stay.
283    #[serde(rename = "rename")]
284    Rename {
285        /// Node path.
286        path: String,
287        /// New qname (`w:p`, `p`, …).
288        name: String,
289    },
290}
291
292/// Result of applying one [`TreeOp`].
293#[derive(Debug, Clone, Serialize)]
294pub struct TreeOpReport {
295    /// Zero-based position in the submitted batch.
296    pub index: usize,
297    /// Action name.
298    pub action: String,
299    /// `applied` or `failed`.
300    pub status: &'static str,
301    /// Detail or failure reason.
302    pub detail: String,
303}
304
305/// Apply `ops` to `root`. Stops on the first failure when `strict` is true.
306pub fn apply_ops(
307    root: &mut XmlNode,
308    ops: &[TreeOp],
309    strict: bool,
310) -> Result<Vec<TreeOpReport>, CoreError> {
311    let mut reports = Vec::new();
312    for (i, op) in ops.iter().enumerate() {
313        match apply_one(root, op) {
314            Ok(detail) => reports.push(TreeOpReport {
315                index: i,
316                action: action_name(op).into(),
317                status: "applied",
318                detail,
319            }),
320            Err(e) => {
321                reports.push(TreeOpReport {
322                    index: i,
323                    action: action_name(op).into(),
324                    status: "failed",
325                    detail: e.to_string(),
326                });
327                if strict {
328                    return Err(e);
329                }
330            }
331        }
332    }
333    Ok(reports)
334}
335
336fn action_name(op: &TreeOp) -> &'static str {
337    match op {
338        TreeOp::SetAttr { .. } => "set_attr",
339        TreeOp::RemoveAttr { .. } => "remove_attr",
340        TreeOp::SetText { .. } => "set_text",
341        TreeOp::InsertChild { .. } => "insert_child",
342        TreeOp::RemoveChild { .. } => "remove_child",
343        TreeOp::Replace { .. } => "replace",
344        TreeOp::Rename { .. } => "rename",
345    }
346}
347
348fn apply_one(root: &mut XmlNode, op: &TreeOp) -> Result<String, CoreError> {
349    match op {
350        TreeOp::SetAttr { path, name, value } => {
351            let node = NodePath::parse(path)?.resolve_mut(root)?;
352            node.set_attr(name, value);
353            Ok(format!("set {name} on {path}"))
354        }
355        TreeOp::RemoveAttr { path, name } => {
356            let node = NodePath::parse(path)?.resolve_mut(root)?;
357            node.remove_attr(name);
358            Ok(format!("removed {name} from {path}"))
359        }
360        TreeOp::SetText { path, text } => {
361            let node = NodePath::parse(path)?.resolve_mut(root)?;
362            node.set_text(text);
363            Ok(format!("set text on {path}"))
364        }
365        TreeOp::InsertChild { path, index, xml } => {
366            let child = parse_fragment(xml)?;
367            let node = NodePath::parse(path)?.resolve_mut(root)?;
368            let kids = node
369                .try_children_mut()
370                .ok_or_else(|| CoreError::Path(format!("{path} is not an element")))?;
371            let i = index.unwrap_or(kids.len());
372            if i > kids.len() {
373                return Err(CoreError::Path(format!(
374                    "insert index {i} out of range (len {})",
375                    kids.len()
376                )));
377            }
378            kids.insert(i, child);
379            Ok(format!("inserted child at {path}[{i}]"))
380        }
381        TreeOp::RemoveChild { path, index } => {
382            let node = NodePath::parse(path)?.resolve_mut(root)?;
383            let kids = node
384                .try_children_mut()
385                .ok_or_else(|| CoreError::Path(format!("{path} is not an element")))?;
386            if *index >= kids.len() {
387                return Err(CoreError::Path(format!(
388                    "remove index {index} out of range (len {})",
389                    kids.len()
390                )));
391            }
392            kids.remove(*index);
393            Ok(format!("removed child {index} of {path}"))
394        }
395        TreeOp::Replace { path, xml } => {
396            let parsed = NodePath::parse(path)?;
397            if parsed.steps.is_empty() {
398                *root = parse_fragment(xml)?;
399                return Ok("replaced root".into());
400            }
401            let replacement = parse_fragment(xml)?;
402            let parent_path = NodePath {
403                steps: parsed.steps[..parsed.steps.len() - 1].to_vec(),
404            };
405            let last = parsed.steps.last().cloned().unwrap();
406            let parent = parent_path.resolve_mut(root)?;
407            match last {
408                PathStep::Index(i) => {
409                    let kids = parent
410                        .try_children_mut()
411                        .ok_or_else(|| CoreError::Path("parent is not an element".into()))?;
412                    let slot = kids
413                        .get_mut(i)
414                        .ok_or_else(|| CoreError::Path(format!("index {i} missing")))?;
415                    *slot = replacement;
416                }
417                PathStep::Name { local, index } => {
418                    let slot = parent.child_named_mut(&local, index).ok_or_else(|| {
419                        CoreError::Path(format!("{local}[{index}] missing on parent"))
420                    })?;
421                    *slot = replacement;
422                }
423            }
424            Ok(format!("replaced {path}"))
425        }
426        TreeOp::Rename { path, name } => {
427            let node = NodePath::parse(path)?.resolve_mut(root)?;
428            if !node.is_element() {
429                return Err(CoreError::Path(format!("{path} is not an element")));
430            }
431            node.set_qname(name);
432            Ok(format!("renamed {path} to {name}"))
433        }
434    }
435}
436
437/// Parse a single-element XML fragment, or treat the string as text.
438pub fn parse_fragment(xml: &str) -> Result<XmlNode, CoreError> {
439    let trimmed = xml.trim();
440    if trimmed.starts_with('<') {
441        let wrapped = format!("<_frag>{trimmed}</_frag>");
442        let doc = crate::xml::parse(wrapped.as_bytes())?;
443        let kids = doc.root.children();
444        if kids.len() == 1 {
445            return Ok(kids[0].clone());
446        }
447        return Ok(doc.root);
448    }
449    Ok(XmlNode::Text(xml.to_string()))
450}
451
452/// Parse zero or more sibling fragments. Unlike [`parse_fragment`], a
453/// multi-element string does not wrap them in a synthetic `_frag` parent.
454pub fn parse_fragments(xml: &str) -> Result<Vec<XmlNode>, CoreError> {
455    let trimmed = xml.trim();
456    if trimmed.is_empty() {
457        return Ok(Vec::new());
458    }
459    if trimmed.starts_with('<') {
460        let wrapped = format!("<_frag>{trimmed}</_frag>");
461        let doc = crate::xml::parse(wrapped.as_bytes())?;
462        return Ok(doc.root.children().to_vec());
463    }
464    Ok(vec![XmlNode::Text(xml.to_string())])
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use crate::xml;
471
472    fn sample() -> XmlNode {
473        xml::parse(b"<root><p>one</p><p>two</p></root>")
474            .unwrap()
475            .root
476    }
477
478    #[test]
479    fn path_by_name() {
480        let root = sample();
481        let p = NodePath::parse("p[1]").unwrap();
482        assert_eq!(p.resolve(&root).unwrap().text_content(), "two");
483    }
484
485    #[test]
486    fn path_by_index() {
487        let root = sample();
488        let p = NodePath::parse("0").unwrap();
489        assert_eq!(p.resolve(&root).unwrap().local_name(), "p");
490    }
491
492    #[test]
493    fn set_text_op() {
494        let mut root = sample();
495        apply_ops(
496            &mut root,
497            &[TreeOp::SetText {
498                path: "p[0]".into(),
499                text: "changed".into(),
500            }],
501            true,
502        )
503        .unwrap();
504        assert_eq!(root.child_named("p", 0).unwrap().text_content(), "changed");
505    }
506
507    #[test]
508    fn insert_and_remove() {
509        let mut root = sample();
510        apply_ops(
511            &mut root,
512            &[TreeOp::InsertChild {
513                path: "".into(),
514                index: Some(1),
515                xml: "<p>mid</p>".into(),
516            }],
517            true,
518        )
519        .unwrap();
520        assert_eq!(root.find_all("p").len(), 3);
521        apply_ops(
522            &mut root,
523            &[TreeOp::RemoveChild {
524                path: "".into(),
525                index: 1,
526            }],
527            true,
528        )
529        .unwrap();
530        assert_eq!(root.find_all("p").len(), 2);
531    }
532
533    #[test]
534    fn set_attr_and_replace() {
535        let mut root = sample();
536        apply_ops(
537            &mut root,
538            &[
539                TreeOp::SetAttr {
540                    path: "p[0]".into(),
541                    name: "w:val".into(),
542                    value: "x".into(),
543                },
544                TreeOp::Replace {
545                    path: "p[1]".into(),
546                    xml: "<p>replaced</p>".into(),
547                },
548            ],
549            true,
550        )
551        .unwrap();
552        assert_eq!(root.child_named("p", 0).unwrap().get_attr("val"), Some("x"));
553        assert_eq!(root.child_named("p", 1).unwrap().text_content(), "replaced");
554    }
555
556    #[test]
557    fn missing_path_fails_strict() {
558        let mut root = sample();
559        let err = apply_ops(
560            &mut root,
561            &[TreeOp::SetText {
562                path: "p[9]".into(),
563                text: "x".into(),
564            }],
565            true,
566        );
567        assert!(err.is_err());
568    }
569
570    #[test]
571    fn rename_and_child_index() {
572        let mut root = sample();
573        let p0 = NodePath::parse("p[0]").unwrap();
574        assert_eq!(child_index(&root, &p0).unwrap(), 0);
575        apply_ops(
576            &mut root,
577            &[TreeOp::Rename {
578                path: "p[1]".into(),
579                name: "q".into(),
580            }],
581            true,
582        )
583        .unwrap();
584        assert_eq!(root.child_named("q", 0).unwrap().text_content(), "two");
585        assert_eq!(root.find_all("p").len(), 1);
586    }
587}