1use serde::{Deserialize, Serialize};
16
17use crate::error::CoreError;
18use crate::formula::{self, Match};
19use crate::tree::{self, TreeOp, TreeOpReport};
20use crate::xml::XmlNode;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
24#[serde(rename_all = "lowercase")]
25pub enum PatchPos {
26 #[default]
28 Append,
29 Prepend,
31 Before,
33 After,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(tag = "op", rename_all = "lowercase")]
40pub enum PatchOp {
41 Add {
43 sel: String,
45 #[serde(default)]
47 pos: PatchPos,
48 #[serde(default, rename = "type")]
50 type_attr: Option<String>,
51 #[serde(default)]
53 xml: Option<String>,
54 #[serde(default)]
56 text: Option<String>,
57 },
58 Replace {
60 sel: String,
62 #[serde(default)]
64 xml: Option<String>,
65 #[serde(default)]
67 text: Option<String>,
68 },
69 Remove {
71 sel: String,
73 },
74}
75
76pub fn parse_ops(raw: &str) -> Result<Vec<PatchOp>, CoreError> {
78 let trimmed = raw.trim();
79 if trimmed.starts_with('<') {
80 parse_rfc_xml(trimmed)
81 } else {
82 serde_json::from_str(trimmed)
83 .map_err(|e| CoreError::patch(format!("invalid patch JSON: {e}")))
84 }
85}
86
87pub fn parse_rfc_xml(xml: &str) -> Result<Vec<PatchOp>, CoreError> {
89 let doc = crate::xml::parse(xml.as_bytes()).map_err(|e| CoreError::patch(e.to_string()))?;
90 let mut ops = Vec::new();
91 for child in doc.root.children() {
92 if !child.is_element() {
93 continue;
94 }
95 let sel = child
96 .get_attr("sel")
97 .ok_or_else(|| CoreError::patch(format!("<{}> missing sel", child.local_name())))?
98 .to_string();
99 match child.local_name() {
100 "add" => {
101 let pos = match child.get_attr("pos") {
102 Some("prepend") => PatchPos::Prepend,
103 Some("before") => PatchPos::Before,
104 Some("after") => PatchPos::After,
105 Some("append") | None => PatchPos::Append,
106 Some(other) => {
107 return Err(CoreError::patch(format!("unknown pos '{other}'")));
108 }
109 };
110 let type_attr = child.get_attr("type").map(str::to_string);
111 let (xml, text) = payload_from_node(child);
112 ops.push(PatchOp::Add {
113 sel,
114 pos,
115 type_attr,
116 xml,
117 text,
118 });
119 }
120 "replace" => {
121 let (xml, text) = payload_from_node(child);
122 ops.push(PatchOp::Replace { sel, xml, text });
123 }
124 "remove" => ops.push(PatchOp::Remove { sel }),
125 other => {
126 return Err(CoreError::patch(format!(
127 "unknown patch element <{other}>; expected add, replace, or remove"
128 )));
129 }
130 }
131 }
132 Ok(ops)
133}
134
135fn payload_from_node(node: &XmlNode) -> (Option<String>, Option<String>) {
136 let elements: Vec<&XmlNode> = node.children().iter().filter(|c| c.is_element()).collect();
137 if !elements.is_empty() {
138 let xml = elements
139 .iter()
140 .map(|e| e.to_xml_string())
141 .collect::<Vec<_>>()
142 .join("");
143 return (Some(xml), None);
144 }
145 let text = node.text_content();
146 if text.is_empty() {
147 (None, None)
148 } else {
149 (None, Some(text))
150 }
151}
152
153pub fn apply(
155 root: &mut XmlNode,
156 ops: &[PatchOp],
157 strict: bool,
158) -> Result<Vec<TreeOpReport>, CoreError> {
159 let planned = plan(root, ops)?;
160 tree::apply_ops(root, &planned, strict)
161}
162
163pub fn plan(root: &XmlNode, ops: &[PatchOp]) -> Result<Vec<TreeOp>, CoreError> {
166 let mut clone = root.clone();
167 let mut all = Vec::new();
168 for op in ops {
169 let compiled = compile_one(&clone, op)?;
170 tree::apply_ops(&mut clone, &compiled, true)?;
171 all.extend(compiled);
172 }
173 Ok(all)
174}
175
176fn compile_one(root: &XmlNode, op: &PatchOp) -> Result<Vec<TreeOp>, CoreError> {
177 match op {
178 PatchOp::Add {
179 sel,
180 pos,
181 type_attr,
182 xml,
183 text,
184 } => compile_add(
185 root,
186 sel,
187 *pos,
188 type_attr.as_deref(),
189 xml.as_deref(),
190 text.as_deref(),
191 ),
192 PatchOp::Replace { sel, xml, text } => {
193 compile_replace(root, sel, xml.as_deref(), text.as_deref())
194 }
195 PatchOp::Remove { sel } => compile_remove(root, sel),
196 }
197}
198
199fn unique_match(root: &XmlNode, sel: &str) -> Result<Match, CoreError> {
200 let matches = formula::select_str(root, sel)?;
201 match matches.len() {
202 1 => Ok(matches.into_iter().next().expect("len 1")),
203 0 => Err(CoreError::patch(format!("sel '{sel}' matched nothing"))),
204 n => Err(CoreError::patch(format!(
205 "sel '{sel}' matched {n} nodes; RFC 5261 requires exactly one"
206 ))),
207 }
208}
209
210fn compile_add(
211 root: &XmlNode,
212 sel: &str,
213 pos: PatchPos,
214 type_attr: Option<&str>,
215 xml: Option<&str>,
216 text: Option<&str>,
217) -> Result<Vec<TreeOp>, CoreError> {
218 let target = unique_match(root, sel)?;
219 if let Some(ty) = type_attr {
220 if let Some(name) = ty.strip_prefix('@') {
221 let value = text.unwrap_or("").to_string();
222 return Ok(vec![TreeOp::SetAttr {
223 path: target.node_path()?.to_op_path(),
224 name: name.to_string(),
225 value,
226 }]);
227 }
228 if ty.starts_with("namespace:") || ty.starts_with("namespace::") {
229 return Err(CoreError::patch(
230 "namespace-axis add is not supported; this crate matches local names",
231 ));
232 }
233 return Err(CoreError::patch(format!(
234 "unsupported add type '{ty}'; use @attr for attributes"
235 )));
236 }
237 if target.attr.is_some() {
238 return Err(CoreError::patch(
239 "add with an attribute sel needs type=\"@name\" on the parent, or use replace",
240 ));
241 }
242 let payload = payload_xml(xml, text)?;
243 insert_ops(root, &target, pos, &payload)
244}
245
246fn compile_replace(
247 root: &XmlNode,
248 sel: &str,
249 xml: Option<&str>,
250 text: Option<&str>,
251) -> Result<Vec<TreeOp>, CoreError> {
252 let target = unique_match(root, sel)?;
253 if let Some(attr) = target.attr.as_deref() {
254 let value = text
255 .map(str::to_string)
256 .or_else(|| xml.map(str::to_string))
257 .unwrap_or_default();
258 return Ok(vec![TreeOp::SetAttr {
259 path: target.node_path()?.to_op_path(),
260 name: attr.to_string(),
261 value,
262 }]);
263 }
264 if let Some(fragment) = xml {
265 return Ok(vec![TreeOp::Replace {
266 path: target.node_path()?.to_op_path(),
267 xml: fragment.to_string(),
268 }]);
269 }
270 Ok(vec![TreeOp::SetText {
271 path: target.node_path()?.to_op_path(),
272 text: text.unwrap_or("").to_string(),
273 }])
274}
275
276fn compile_remove(root: &XmlNode, sel: &str) -> Result<Vec<TreeOp>, CoreError> {
277 let target = unique_match(root, sel)?;
278 if let Some(attr) = target.attr.as_deref() {
279 return Ok(vec![TreeOp::RemoveAttr {
280 path: target.node_path()?.to_op_path(),
281 name: attr.to_string(),
282 }]);
283 }
284 let path = target.node_path()?;
285 if path.is_root() {
286 return Err(CoreError::patch("cannot remove the document element"));
287 }
288 let index = tree::child_index(root, &path)?;
289 let parent = path.parent().expect("not root");
290 Ok(vec![TreeOp::RemoveChild {
291 path: parent.to_op_path(),
292 index,
293 }])
294}
295
296fn payload_xml(xml: Option<&str>, text: Option<&str>) -> Result<String, CoreError> {
297 if let Some(x) = xml {
298 return Ok(x.to_string());
299 }
300 if let Some(t) = text {
301 return Ok(t.to_string());
302 }
303 Err(CoreError::patch("add/replace needs xml or text"))
304}
305
306fn insert_ops(
307 root: &XmlNode,
308 target: &Match,
309 pos: PatchPos,
310 payload: &str,
311) -> Result<Vec<TreeOp>, CoreError> {
312 let fragments = tree::parse_fragments(payload)?;
313 if fragments.is_empty() {
314 return Err(CoreError::patch("add payload is empty"));
315 }
316 let path = target.node_path()?;
317 let mut ops = Vec::new();
318 match pos {
319 PatchPos::Append => {
320 for frag in &fragments {
321 ops.push(TreeOp::InsertChild {
322 path: path.to_op_path(),
323 index: None,
324 xml: frag.to_xml_string(),
325 });
326 }
327 }
328 PatchPos::Prepend => {
329 for (i, frag) in fragments.iter().enumerate() {
330 ops.push(TreeOp::InsertChild {
331 path: path.to_op_path(),
332 index: Some(i),
333 xml: frag.to_xml_string(),
334 });
335 }
336 }
337 PatchPos::Before | PatchPos::After => {
338 if path.is_root() {
339 return Err(CoreError::patch(
340 "cannot insert before/after the document element",
341 ));
342 }
343 let mut index = tree::child_index(root, &path)?;
344 if pos == PatchPos::After {
345 index += 1;
346 }
347 let parent = path.parent().expect("not root").to_op_path();
348 for (i, frag) in fragments.iter().enumerate() {
349 ops.push(TreeOp::InsertChild {
350 path: parent.clone(),
351 index: Some(index + i),
352 xml: frag.to_xml_string(),
353 });
354 }
355 }
356 }
357 Ok(ops)
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363 use crate::formula::eval_str;
364 use crate::xml;
365
366 fn sample() -> XmlNode {
367 xml::parse(b"<root><p id=\"a\">one</p><p id=\"b\">two</p></root>")
368 .unwrap()
369 .root
370 }
371
372 #[test]
373 fn remove_unique_then_add() {
374 let mut root = sample();
375 apply(
376 &mut root,
377 &parse_ops(
378 r#"[{"op":"remove","sel":"//p[@id=\"a\"]"},{"op":"add","sel":"/","xml":"<p id=\"c\">three</p>"}]"#,
379 )
380 .unwrap(),
381 true,
382 )
383 .unwrap();
384 assert_eq!(eval_str(&root, "count(//p)").unwrap().as_number(), Some(2));
385 assert_eq!(
386 eval_str(&root, r#"text(//p[@id="c"])"#).unwrap().to_text(),
387 "three"
388 );
389 }
390
391 #[test]
392 fn rfc_xml_add_attr_and_replace() {
393 let mut root = sample();
394 let xml = r#"<diff>
395 <add sel="/p[0]" type="@n">9</add>
396 <replace sel="/p[1]"><p id="b">TWO</p></replace>
397 </diff>"#;
398 apply(&mut root, &parse_rfc_xml(xml).unwrap(), true).unwrap();
399 assert_eq!(root.child_named("p", 0).unwrap().get_attr("n"), Some("9"));
400 assert_eq!(root.child_named("p", 1).unwrap().text_content(), "TWO");
401 }
402
403 #[test]
404 fn unique_sel_is_required() {
405 let root = sample();
406 let err = plan(
407 &root,
408 &parse_ops(r#"[{"op":"remove","sel":"//p"}]"#).unwrap(),
409 );
410 assert!(err.unwrap_err().to_string().contains("matched 2"));
411 }
412
413 #[test]
414 fn insert_before_sibling() {
415 let mut root = sample();
416 apply(
417 &mut root,
418 &[PatchOp::Add {
419 sel: "/p[1]".into(),
420 pos: PatchPos::Before,
421 type_attr: None,
422 xml: Some("<p id=\"m\">mid</p>".into()),
423 text: None,
424 }],
425 true,
426 )
427 .unwrap();
428 assert_eq!(root.child_named("p", 1).unwrap().text_content(), "mid");
429 }
430
431 #[test]
432 fn remove_attribute_via_sel() {
433 let mut root = sample();
434 apply(
435 &mut root,
436 &[PatchOp::Remove {
437 sel: "/p[0]/@id".into(),
438 }],
439 true,
440 )
441 .unwrap();
442 assert!(root.child_named("p", 0).unwrap().get_attr("id").is_none());
443 }
444}