1use crate::cli::edit_actions::EditAction;
8use crate::edit::{
9 ExistingRevisions,
10 for_edit::{ForEditRequest, for_edit_quoting},
11 v2::{self, PlanV2, Target},
12};
13use crate::inspect::source_sha256;
14use crate::result::Error;
15
16fn refusal(code: &str, message: impl Into<String>) -> Box<Error> {
17 Box::new(Error::new(code).with_message(message))
18}
19fn edit_error(e: crate::edit::EditError) -> Box<Error> {
20 let mut error = Error::new(e.code).with_message(e.message);
21 error.operation = e.operation;
22 error.near = e.near.map(|near| *near);
23 Box::new(error)
24}
25fn pair(p: &crate::edit::for_edit::TargetPair) -> Target {
26 Target {
27 short_id: p.short_id.clone(),
28 long_id: p.long_id.clone(),
29 }
30}
31
32fn deleted_text_hint(
38 source: &[u8],
39 author: &str,
40 existing: crate::edit::ExistingRevisions,
41 target: &str,
42 find: &str,
43 decided: &[&str],
44) -> Option<String> {
45 let plan = crate::edit::EditPlan {
46 schema_version: crate::edit::SCHEMA_VERSION,
47 source_sha256: None,
48 author: author.to_string(),
49 date: None,
50 initials: None,
51 resolve_revisions: None,
52 removed_anchor_comments: crate::edit::RemovedAnchorComments::Remove,
53 existing_revisions: existing,
54 operations: Vec::new(),
55 update_fields: false,
56 rewrite_others_comments: false,
57 others: crate::edit::Others::Allow,
58 };
59 let tx = crate::edit::Transaction::start_quoting(source, &plan, crate::edit::PlanSyntax::Typed)
60 .ok()?;
61 let para = (0..tx.paragraph_nodes.len()).find(|¶| tx.paragraph_id(para) == target)?;
62 let holder = tx.removed_anchor_holder(para, find)?;
63 if decided.contains(&holder.as_str()) {
64 return None;
65 }
66 tx.removed_anchor_in(para, find)
67}
68
69pub fn compile(
76 source: &[u8],
77 action: &EditAction,
78 text: Option<&str>,
79) -> Result<PlanV2, Box<Error>> {
80 if let Some(text) = text {
81 v2::check_payload_text(
82 text,
83 action.payload().is_some_and(|p| p.text_file.is_some()),
84 )
85 .map_err(edit_error)?;
86 }
87 let inline = action
88 .inline()
89 .ok_or_else(|| refusal("USAGE", "apply does not compile an inline action"))?;
90 let existing = match inline.existing_revisions.as_str() {
91 "keep" => ExistingRevisions::Keep,
92 "accept" => ExistingRevisions::Accept,
93 "reject" => ExistingRevisions::Reject,
94 _ => ExistingRevisions::Refuse,
95 };
96 let (accept, reject) =
97 crate::edit::source_refs::decisions(source, &inline.accept_change, &inline.reject_change)
98 .map_err(edit_error)?;
99 let view = for_edit_quoting(
101 source,
102 &ForEditRequest {
103 all: true,
104 accept: accept
105 .iter()
106 .map(|target| target.short_id.clone())
107 .collect(),
108 reject: reject
109 .iter()
110 .map(|target| target.short_id.clone())
111 .collect(),
112 existing_revisions: existing,
113 track: inline.track == "on",
114 ..Default::default()
115 },
116 crate::edit::PlanSyntax::Typed,
117 )
118 .map_err(edit_error)?;
119 let at = match action {
120 EditAction::Replace { at, .. } => at.as_deref(),
121 EditAction::Rewrite { at, .. }
122 | EditAction::Insert { at, .. }
123 | EditAction::Delete { at, .. } => Some(at.as_str()),
124 _ => unreachable!(),
125 };
126 let mut candidates: Vec<_> = view
127 .paragraphs
128 .iter()
129 .filter(|row| at.is_none_or(|id| row.target.short_id == id || row.target.long_id == id))
130 .collect();
131 if at.is_some() && candidates.len() != 1 {
132 return Err(refusal(
133 "INVALID_TARGET",
134 format!(
135 "--at {} must identify exactly one original-source paragraph",
136 at.unwrap_or_default()
137 ),
138 ));
139 }
140 let mut operations = Vec::new();
141 let payload = text.unwrap_or_default().to_string();
142 let comment = action
143 .payload()
144 .and_then(|p| p.comment.as_ref())
145 .map(|text| v2::AttachedComment { text: text.clone() });
146 match action {
147 EditAction::Replace {
148 find,
149 at,
150 story,
151 occurrence,
152 all_matches,
153 expect_count,
154 ..
155 } => {
156 if find.is_empty() {
157 return Err(refusal("INVALID_EDIT", "--find must not be empty"));
158 }
159 if at.is_none() {
160 let story = story.as_deref().unwrap_or("body");
161 crate::edit::anchor_error::require_story(source, story)?;
162 candidates.retain(|r| r.story == story);
163 }
164 let mut hits = Vec::new();
165 for row in &candidates {
166 if let Some(working) = &row.working {
167 let working =
168 working.value.text.as_deref().ok_or_else(|| {
169 refusal("UNSUPPORTED_TEXT", "working text is incomplete")
170 })?;
171 for (local, _) in crate::edit::v2_candidates(working, find).iter().enumerate() {
172 hits.push((*row, local + 1));
173 }
174 }
175 }
176 let with_near = |mut error: Box<Error>| {
177 if hits.is_empty() && error.code == "ANCHOR_NOT_FOUND" {
178 let mut report = crate::edit::NearMatches {
179 total: 0,
180 occurrences: Vec::new(),
181 };
182 for row in &candidates {
183 if let Some(text) =
184 row.working.as_ref().and_then(|w| w.value.text.as_deref())
185 && let Some(near) = crate::edit::anchor::near_matches(text, find)
186 {
187 report.total += near.total;
188 let remaining = 5 - report.occurrences.len();
189 report.occurrences.extend(
190 near.occurrences.into_iter().take(remaining).map(|mut hit| {
191 hit.target = Some(row.target.short_id.clone());
192 hit
193 }),
194 );
195 }
196 }
197 if report.total > 0 {
198 error.near = Some(report);
199 }
200 }
201 error
202 };
203 if *all_matches {
204 if hits.len() != expect_count.unwrap_or_default() {
205 return Err(with_near(refusal(
206 if hits.is_empty() {
207 "ANCHOR_NOT_FOUND"
208 } else {
209 "AMBIGUOUS_ANCHOR"
210 },
211 format!(
212 "expected {} matches; found {}",
213 expect_count.unwrap_or_default(),
214 hits.len()
215 ),
216 )));
217 }
218 for row in &candidates {
219 if let Some(working) = &row.working {
220 let working = working.value.text.as_deref().unwrap_or_default();
221 let count = crate::edit::v2_candidates(working, find).len();
222 if count > 0 {
223 crate::edit::v2_select_all(working, find, count).map_err(edit_error)?;
224 }
225 }
226 }
227 } else {
228 if let Some(row) = candidates.first().filter(|_| at.is_some()) {
229 let working = row
230 .working
231 .as_ref()
232 .and_then(|w| w.value.text.as_deref())
233 .ok_or_else(|| {
234 refusal(
235 "UNSUPPORTED_TARGET_MAPPING",
236 "target has no one-to-one working paragraph",
237 )
238 })?;
239 if let Err(missed) = crate::edit::v2_resolve(
240 source,
241 crate::edit::Working::Settled(working),
242 &crate::edit::AnchorRefusal::new(&row.target.short_id, find)
243 .with_operation("/operations/0"),
244 *occurrence,
245 ) {
246 if missed.code == "ANCHOR_NOT_FOUND"
247 && let Some(hint) = deleted_text_hint(
248 source,
249 &inline.author,
250 existing,
251 &row.target.short_id,
252 find,
253 &accept
254 .iter()
255 .chain(&reject)
256 .map(|target| target.short_id.as_str())
257 .collect::<Vec<_>>(),
258 )
259 {
260 return Err(Box::new(
261 Error::new("UNSUPPORTED_STRUCTURE")
262 .with_message(hint)
263 .with_operation("/operations/0"),
264 ));
265 }
266 return Err(missed);
267 }
268 }
269 let index = match occurrence {
270 Some(n) => n - 1,
271 None if hits.len() == 1 => 0,
272 None => {
273 let mut message = format!("expected one exact match; found {}", hits.len());
274 if !hits.is_empty() {
275 let mut paragraphs: Vec<(&str, usize)> = Vec::new();
276 for (row, _) in &hits {
277 let id = row.target.short_id.as_str();
278 if let Some((_, count)) =
279 paragraphs.last_mut().filter(|(p, _)| *p == id)
280 {
281 *count += 1;
282 } else {
283 paragraphs.push((id, 1));
284 }
285 }
286 let shown = paragraphs
287 .into_iter()
288 .map(|(id, count)| {
289 if count == 1 {
290 id.to_string()
291 } else {
292 format!("{id} ({count})")
293 }
294 })
295 .collect::<Vec<_>>()
296 .join(", ");
297 message.push_str(&format!(
298 ": {shown}; pick one with --at pN or --occurrence 1..={}",
299 hits.len()
300 ));
301 }
302 return Err(with_near(refusal(
303 if hits.is_empty() {
304 "ANCHOR_NOT_FOUND"
305 } else {
306 "AMBIGUOUS_ANCHOR"
307 },
308 message,
309 )));
310 }
311 };
312 let hit = hits.get(index).copied().ok_or_else(|| {
313 with_near(refusal(
314 if hits.is_empty() {
315 "ANCHOR_NOT_FOUND"
316 } else {
317 "AMBIGUOUS_ANCHOR"
318 },
319 format!("occurrence is outside {} exact matches", hits.len()),
320 ))
321 })?;
322 hits = vec![hit];
323 }
324 for (row, n) in hits {
325 operations.push(v2::Operation::Replace {
326 target: pair(&row.target),
327 find: find.clone(),
328 text: payload.clone(),
329 occurrence: Some(n as u64),
330 attached_comment: comment.clone(),
331 });
332 }
333 }
334 _ => {
335 let row = candidates[0];
336 let target = pair(&row.target);
337 let operation = match action {
338 EditAction::Rewrite { .. } => v2::Operation::Rewrite {
339 target,
340 before_sha256: row
341 .working
342 .as_ref()
343 .and_then(|w| w.before_sha256.clone())
344 .ok_or_else(|| {
345 refusal(
346 "UNSUPPORTED_TARGET_MAPPING",
347 "rewrite requires exact one-to-one working correspondence",
348 )
349 })?,
350 text: payload,
351 attached_comment: comment,
352 },
353 EditAction::Delete {
354 find,
355 whole_block,
356 occurrence,
357 ..
358 } => {
359 if *whole_block {
360 v2::Operation::DeleteParagraph { target }
361 } else {
362 v2::Operation::Delete {
363 target,
364 find: find.clone().expect("parser requires find"),
365 occurrence: occurrence.map(|n| n as u64),
366 }
367 }
368 }
369 EditAction::Insert {
370 kind,
371 before_text,
372 after_text,
373 edge,
374 position,
375 occurrence,
376 ..
377 } => {
378 if kind == "paragraph" {
379 v2::Operation::InsertParagraph {
380 target,
381 position: if position.as_deref() == Some("before") {
382 crate::edit::Side::Before
383 } else {
384 crate::edit::Side::After
385 },
386 text: payload,
387 attached_comment: comment,
388 }
389 } else {
390 v2::Operation::Insert {
391 target,
392 before_text: before_text.clone(),
393 after_text: after_text.clone(),
394 edge: edge.as_ref().map(|s| {
395 if s == "start" {
396 crate::edit::Edge::Start
397 } else {
398 crate::edit::Edge::End
399 }
400 }),
401 occurrence: occurrence.map(|n| n as u64),
402 text: payload,
403 attached_comment: comment,
404 }
405 }
406 }
407 _ => unreachable!(),
408 };
409 operations.push(operation);
410 }
411 }
412 let targets = operations
413 .iter()
414 .map(|op| match op {
415 v2::Operation::Replace { target, .. }
416 | v2::Operation::Rewrite { target, .. }
417 | v2::Operation::Insert { target, .. }
418 | v2::Operation::InsertParagraph { target, .. }
419 | v2::Operation::Delete { target, .. }
420 | v2::Operation::DeleteParagraph { target } => target.clone(),
421 _ => unreachable!(),
422 })
423 .fold(Vec::new(), |mut targets, target| {
424 if !targets.contains(&target) {
425 targets.push(target);
426 }
427 targets
428 });
429 let plan = PlanV2 {
430 schema_version: 2,
431 source: v2::Source {
432 sha256: source_sha256(source),
433 },
434 policy: v2::Policy {
435 track: if inline.track == "on" {
436 v2::Track::On
437 } else {
438 v2::Track::Off
439 },
440 existing_revisions: existing,
441 text_view: v2::TextView::Final,
442 },
443 resolve_revisions: v2::RevisionDecisions { accept, reject },
444 removed_anchor_comments: Default::default(),
445 rewrite_others_comments: None,
446 others: None,
447 author: inline.author.clone(),
448 date: inline
449 .datetime
450 .clone()
451 .unwrap_or_else(crate::util::datetime::utc_now_iso8601),
452 scope: v2::Scope::Selected { targets },
453 operations,
454 source_context: None,
455 coverage: None,
456 };
457 plan.validate().map_err(edit_error)?;
458 Ok(plan)
459}
460
461#[cfg(test)]
462mod tests {
463 use super::*;
464 use crate::cli::{Cli, Command};
465 use crate::edit::{PrepareOptions, prepare_v2};
466 use crate::markdown::{DocxOptions, markdown_to_docx};
467
468 fn source(text: &str) -> Vec<u8> {
469 markdown_to_docx(text, &DocxOptions::default())
470 .unwrap()
471 .docx
472 }
473 fn action(args: &[&str]) -> EditAction {
474 let cli = Cli::try_parse_from(
475 [
476 vec!["jubarte", "edit"],
477 args.to_vec(),
478 vec![
479 "source.docx",
480 "--dry-run",
481 "--datetime",
482 "2026-10-17T00:00:00Z",
483 ],
484 ]
485 .concat(),
486 )
487 .unwrap();
488 let Some(Command::TypedEdit(typed)) = cli.command else {
489 panic!("typed route")
490 };
491 typed.action
492 }
493 fn final_text(source: &[u8], action: &EditAction, text: Option<&str>) -> String {
494 let plan = compile(source, action, text).unwrap();
495 let prepared = prepare_v2(source, &plan, &PrepareOptions::default()).unwrap();
496 crate::inspect::paragraphs(&prepared.primary)
497 .unwrap()
498 .iter()
499 .map(|p| p.text.as_str())
500 .collect::<Vec<_>>()
501 .join("\n")
502 }
503
504 #[test]
505 fn inline_literal_candidates_include_overlaps_and_freeze_all_matches() {
506 let bytes = source("aaa\n\nfee fee\n\nfee");
507 let replace = |extra: &[&str]| {
508 action(
509 &[
510 vec!["replace", "--find", "aa", "--text", "X", "--at", "p0"],
511 extra.to_vec(),
512 ]
513 .concat(),
514 )
515 };
516 let error = compile(&bytes, &replace(&[]), Some("X")).unwrap_err();
517 assert_eq!(error.code, "AMBIGUOUS_ANCHOR");
518 assert_eq!(error.matches, Some(2));
519 assert_eq!(
520 final_text(&bytes, &replace(&["--occurrence", "2"]), Some("X")),
521 "aX\nfee fee\nfee"
522 );
523 let error = compile(
524 &bytes,
525 &replace(&["--all-matches", "--expect-count", "2"]),
526 Some("X"),
527 )
528 .unwrap_err();
529 assert_eq!(error.code, "OVERLAPPING_EDITS");
530 let all = action(&[
531 "replace",
532 "--find",
533 "fee",
534 "--text",
535 "charge",
536 "--all-matches",
537 "--expect-count",
538 "3",
539 ]);
540 let plan = compile(&bytes, &all, Some("charge")).unwrap();
541 assert_eq!(plan.operations.len(), 3);
542 assert!(matches!(plan.scope,v2::Scope::Selected {ref targets} if targets.len() == 2));
543 assert_eq!(
544 final_text(&bytes, &all, Some("charge")),
545 "aaa\ncharge charge\ncharge"
546 );
547 let wrong_count = action(&[
548 "replace",
549 "--find",
550 "fee",
551 "--text",
552 "x",
553 "--all-matches",
554 "--expect-count",
555 "2",
556 ]);
557 assert_eq!(
558 compile(&bytes, &wrong_count, Some("x")).unwrap_err().code,
559 "AMBIGUOUS_ANCHOR"
560 );
561 }
562
563 #[test]
564 fn inline_missing_or_ambiguous_literals_never_choose_another_target() {
565 let bytes = source("one\n\nfee fee");
566 for (args, code) in [
567 (
568 vec!["replace", "--find", "missing", "--text", "x"],
569 "ANCHOR_NOT_FOUND",
570 ),
571 (
572 vec!["replace", "--find", "fee", "--text", "x"],
573 "AMBIGUOUS_ANCHOR",
574 ),
575 (
576 vec![
577 "replace",
578 "--find",
579 "fee",
580 "--occurrence",
581 "3",
582 "--text",
583 "x",
584 ],
585 "AMBIGUOUS_ANCHOR",
587 ),
588 (
589 vec!["replace", "--at", "p0", "--find", "fee", "--text", "x"],
590 "ANCHOR_NOT_FOUND",
591 ),
592 (
593 vec![
594 "replace", "--story", "header1", "--find", "fee", "--text", "x",
595 ],
596 "ANCHOR_NOT_FOUND",
597 ),
598 (
599 vec!["rewrite", "--at", "p99", "--text", "x"],
600 "INVALID_TARGET",
601 ),
602 (vec!["replace", "--find", "", "--text", "x"], "INVALID_EDIT"),
603 ] {
604 assert_eq!(
605 compile(&bytes, &action(&args), Some("x")).unwrap_err().code,
606 code,
607 "{args:?}"
608 );
609 }
610 let explicit_long = action(&[
611 "replace",
612 "--at",
613 "document.w:p.j:short.p1",
614 "--find",
615 "fee",
616 "--occurrence",
617 "2",
618 "--text",
619 "x",
620 ]);
621 assert_eq!(final_text(&bytes, &explicit_long, Some("x")), "one\nfee x");
622 }
623
624 #[test]
625 fn inline_insert_edges_and_paragraph_sides_use_explicit_kinds() {
626 let bytes = source("word");
627 for (args, text, want) in [
628 (
629 vec![
630 "insert", "--kind", "text", "--at", "p0", "--edge", "start", "--text", "A",
631 ],
632 "A",
633 "Aword",
634 ),
635 (
636 vec![
637 "insert", "--kind", "text", "--at", "p0", "--edge", "end", "--text", "Z",
638 ],
639 "Z",
640 "wordZ",
641 ),
642 (
643 vec![
644 "insert",
645 "--kind",
646 "text",
647 "--at",
648 "p0",
649 "--before-text",
650 "word",
651 "--text",
652 "A",
653 ],
654 "A",
655 "Aword",
656 ),
657 (
658 vec![
659 "insert",
660 "--kind",
661 "paragraph",
662 "--at",
663 "p0",
664 "--position",
665 "before",
666 "--text",
667 "A",
668 ],
669 "A",
670 "A\nword",
671 ),
672 (vec!["rewrite", "--at", "p0", "--text", ""], "", ""),
673 ] {
674 assert_eq!(
675 final_text(&bytes, &action(&args), Some(text)),
676 want,
677 "{args:?}"
678 );
679 }
680 let rewrite = action(&[
681 "rewrite",
682 "--at",
683 "p0",
684 "--text",
685 "new",
686 "--comment",
687 "Review",
688 ]);
689 let prepared = prepare_v2(
690 &bytes,
691 &compile(&bytes, &rewrite, Some("new")).unwrap(),
692 &PrepareOptions::default(),
693 )
694 .unwrap();
695 assert_eq!(
696 crate::comments::list_comments(&prepared.primary).unwrap()[0].text,
697 "Review"
698 );
699 }
700
701 #[test]
702 fn inline_decisions_freeze_original_ids_and_working_rewrite_hash() {
703 let bytes = source("Pay {++45++} days.\n\nOther {++Unrelated++} text.");
704 let changes = crate::changes::list_changes(&bytes).unwrap();
705 assert_eq!(changes.len(), 2);
706 let id = changes[0].id.as_str();
707 let rewrite = action(&[
708 "rewrite",
709 "--at",
710 "p0",
711 "--text",
712 "Pay 60 days.",
713 "--accept-change",
714 id,
715 "--accept-change",
716 id,
717 ]);
718 let plan = compile(&bytes, &rewrite, Some("Pay 60 days.")).unwrap();
719 assert_eq!(plan.resolve_revisions.accept.len(), 1);
720 let long = plan.resolve_revisions.accept[0].long_id.as_str();
721 let from_long = action(&[
722 "rewrite",
723 "--at",
724 "p0",
725 "--text",
726 "Pay 60 days.",
727 "--accept-change",
728 long,
729 ]);
730 assert_eq!(
731 compile(&bytes, &from_long, Some("Pay 60 days.")).unwrap(),
732 plan
733 );
734 let prepared = prepare_v2(&bytes, &plan, &PrepareOptions::default()).unwrap();
735 assert!(
736 crate::changes::list_changes(&prepared.primary)
737 .unwrap()
738 .iter()
739 .any(|c| c.id == changes[1].id)
740 );
741 let reject = action(&[
742 "rewrite",
743 "--at",
744 "p0",
745 "--text",
746 "Pay 60 days.",
747 "--reject-change",
748 id,
749 ]);
750 let rejected = compile(&bytes, &reject, Some("Pay 60 days.")).unwrap();
751 assert_eq!(rejected.resolve_revisions.reject.len(), 1);
752 let v2::Operation::Rewrite {
753 before_sha256: before,
754 ..
755 } = &rejected.operations[0]
756 else {
757 panic!("rewrite")
758 };
759 assert_eq!(before, &source_sha256(b"Pay days."));
760 let missing = action(&[
761 "rewrite",
762 "--at",
763 "p0",
764 "--text",
765 "x",
766 "--accept-change",
767 "r999",
768 ]);
769 assert_eq!(
770 compile(&bytes, &missing, Some("x")).unwrap_err().code,
771 "INVALID_TARGET"
772 );
773 let invalid = action(&[
774 "rewrite",
775 "--at",
776 "p0",
777 "--text",
778 "x",
779 "--accept-change",
780 "bogus",
781 ]);
782 assert_eq!(
783 compile(&bytes, &invalid, Some("x")).unwrap_err().code,
784 "INVALID_ID"
785 );
786 }
787}