1use super::EditError;
47use super::anchor::{shown, v2_candidates, v2_select, v2_select_all};
48use crate::comments::CommentRecord;
49use crate::ids::{
50 Location, ShortId, Step, Story, paragraph_place, parse_change_ids, parse_location,
51};
52use crate::inspect::{InspectError, Paragraph, Snapshot, snapshot, source_sha256};
53use crate::result::{CommitState, Context, Error, NextAction};
54
55const WINDOW: usize = 20;
58const MAX_SUGGESTED_TARGETS: usize = 5;
60const READ_SUGGESTION_HEAD: usize = 20;
62
63#[derive(Clone, Copy, Debug)]
67pub struct AnchorRefusal<'a> {
68 pub operation: Option<&'a str>,
70 pub target: &'a str,
73 pub anchor: &'a str,
75 pub path: Option<&'a str>,
78}
79
80impl<'a> AnchorRefusal<'a> {
81 pub fn new(target: &'a str, anchor: &'a str) -> Self {
83 Self {
84 operation: None,
85 target,
86 anchor,
87 path: None,
88 }
89 }
90
91 #[must_use]
93 pub fn with_operation(mut self, operation: &'a str) -> Self {
94 self.operation = Some(operation);
95 self
96 }
97
98 #[must_use]
100 pub fn with_path(mut self, path: &'a str) -> Self {
101 self.path = Some(path);
102 self
103 }
104}
105
106#[derive(Clone, Copy, Debug)]
109pub enum Working<'a> {
110 InSource,
114 Settled(&'a str),
119}
120
121pub fn v2_resolve(
140 source: &[u8],
141 working: Working<'_>,
142 refusal: &AnchorRefusal<'_>,
143 occurrence: Option<usize>,
144) -> Result<(usize, usize), Box<Error>> {
145 let snap = open(source, refusal)?;
146 let target = find_target(&snap, refusal.target);
147 let text = match (target, working) {
148 (Target::Missing, _) => return Err(Box::new(missing_target(&snap, refusal))),
149 (Target::SeveralChanges, _) => {
150 return Err(Box::new(several_changes(&snap, refusal)));
151 }
152 (Target::Here(text), Working::InSource) => text,
153 (Target::Here(_), Working::Settled(text)) => text,
154 };
155 let skip = skip_id(&snap, refusal.target);
156 match v2_select(text, refusal.anchor, occurrence) {
157 Ok(range) => Ok(range),
158 Err(edit) => Err(Box::new(refused(
159 &snap, text, &skip, refusal, &edit, occurrence, None,
160 ))),
161 }
162}
163
164pub fn v2_resolve_all(
177 source: &[u8],
178 working: Working<'_>,
179 refusal: &AnchorRefusal<'_>,
180 expected: usize,
181) -> Result<Vec<(usize, usize)>, Box<Error>> {
182 let snap = open(source, refusal)?;
183 let target = find_target(&snap, refusal.target);
184 let text = match (target, working) {
185 (Target::Missing, _) => return Err(Box::new(missing_target(&snap, refusal))),
186 (Target::SeveralChanges, _) => {
187 return Err(Box::new(several_changes(&snap, refusal)));
188 }
189 (Target::Here(text), Working::InSource) => text,
190 (Target::Here(_), Working::Settled(text)) => text,
191 };
192 let skip = skip_id(&snap, refusal.target);
193 match v2_select_all(text, refusal.anchor, expected) {
194 Ok(ranges) => Ok(ranges),
195 Err(edit) => Err(Box::new(refused(
196 &snap,
197 text,
198 &skip,
199 refusal,
200 &edit,
201 None,
202 Some(expected),
203 ))),
204 }
205}
206
207#[doc(hidden)]
210pub fn require_story(source: &[u8], story: &str) -> Result<(), Box<Error>> {
211 let refusal = AnchorRefusal::new(story, "").with_operation("/operations/0");
212 let snap = open(source, &refusal)?;
213 if story == "body" || snap.stories.iter().any(|s| s.id == story) {
214 return Ok(());
215 }
216 let mut error = missing_target(&snap, &refusal);
217 let available = std::iter::once("body")
218 .chain(snap.stories.iter().map(|s| s.id.as_str()))
219 .collect::<Vec<_>>()
220 .join(", ");
221 error.message = format!("unknown story {story:?}; the source has stories: {available}");
222 Err(Box::new(error))
223}
224
225fn open(source: &[u8], refusal: &AnchorRefusal<'_>) -> Result<Snapshot, Box<Error>> {
230 snapshot(source).map_err(|error| {
231 let code = match &error {
232 InspectError::Admission(refused) => refused.code(),
233 _ => "INVALID_DOCUMENT",
234 };
235 Box::new(
236 base(&source_sha256(source), refusal, code).with_message(format!(
237 "the source could not be read ({error}); no anchor was searched"
238 )),
239 )
240 })
241}
242
243enum Target<'s> {
245 Here(&'s str),
247 SeveralChanges,
250 Missing,
252}
253
254fn find_target<'s>(snap: &'s Snapshot, target: &str) -> Target<'s> {
257 match parse_location(target) {
258 Err(_) => Target::Missing,
259 Ok(Location::Paragraph(id)) => {
260 if let Some((story, n)) = paragraph_place(&id) {
261 let list: &[Paragraph] = if story == "body" {
262 &snap.paragraphs
263 } else if let Some(found) = snap.stories.iter().find(|s| s.id == story) {
264 &found.paragraphs
265 } else {
266 return Target::Missing;
267 };
268 return match list.get(n) {
269 Some(paragraph) => Target::Here(¶graph.text),
270 None => Target::Missing,
271 };
272 }
273 match cell_paragraph(snap, &id) {
274 Some((_, text)) => Target::Here(text),
275 None => Target::Missing,
276 }
277 }
278 Ok(Location::Comment(n)) => match comment(snap, n) {
279 Some(found) => Target::Here(&found.text),
280 None => Target::Missing,
281 },
282 Ok(Location::CommentText(n)) => match comment(snap, n) {
283 Some(found) => Target::Here(&found.anchor_text),
284 None => Target::Missing,
285 },
286 Ok(Location::Changes(ids)) => {
287 let spelled: Vec<String> = ids.iter().map(|change| change.short()).collect();
291 let mark = |short: &str| {
292 snap.changes.iter().find_map(|change| {
293 if change.members.is_empty() {
294 (change.id == short).then_some(change.text.as_str())
295 } else {
296 change
297 .members
298 .iter()
299 .find(|member| member.id == short)
300 .map(|member| member.text.as_str())
301 }
302 })
303 };
304 if !spelled.iter().all(|short| mark(short).is_some()) {
305 return Target::Missing;
306 }
307 match spelled.as_slice() {
308 [one] => mark(one).map_or(Target::Missing, Target::Here),
309 _ => Target::SeveralChanges,
310 }
311 }
312 }
313}
314
315fn comment(snap: &Snapshot, n: u32) -> Option<&CommentRecord> {
317 snap.comments.iter().find(|comment| comment.id == n)
318}
319
320fn cell_paragraph<'s>(snap: &'s Snapshot, id: &str) -> Option<(String, &'s str)> {
325 let Ok(ShortId::Block {
326 story: Story::Body,
327 path,
328 }) = id.parse::<ShortId>()
329 else {
330 return None;
331 };
332 let [Step::Table(t), Step::Row(row), Step::Cell(cell), rest @ ..] = path.as_slice() else {
333 return None;
334 };
335 let index = match rest {
336 [] => 0,
337 [Step::Paragraph(k)] => *k,
338 _ => return None,
339 };
340 let table = snap.tables.iter().find(|table| table.index == *t)?;
341 let held = table.rows.get(*row)?.get(*cell)?;
342 let short = held.paragraph_ids.get(index)?;
343 let (_, n) = paragraph_place(short)?;
344 let paragraph = snap.paragraphs.get(n)?;
345 Some((paragraph.id.clone(), ¶graph.text))
346}
347
348fn skip_id(snap: &Snapshot, target: &str) -> String {
352 if let Ok(Location::Paragraph(id)) = parse_location(target)
353 && paragraph_place(&id).is_none()
354 && let Some((paragraph, _)) = cell_paragraph(snap, &id)
355 {
356 return paragraph;
357 }
358 target.to_string()
359}
360
361fn missing_target(snap: &Snapshot, refusal: &AnchorRefusal<'_>) -> Error {
365 let mut error = base(&snap.source_sha256, refusal, "ANCHOR_NOT_FOUND")
366 .with_matches(0)
367 .with_message(missing_target_message(snap, refusal.target));
368 error.push_next_action(read_head(refusal));
369 error
370}
371
372fn missing_target_message(snap: &Snapshot, target: &str) -> String {
378 let body = format!(
379 "the body has {}",
380 plural(snap.summary.paragraphs, "paragraph")
381 );
382 match parse_location(target) {
383 Ok(Location::Comment(_)) | Ok(Location::CommentText(_)) => format!(
384 "no comment {target} in the source; the source has {}",
385 plural(snap.summary.comments, "comment")
386 ),
387 Ok(Location::Changes(_)) => format!(
388 "no revision {target} in the source; the source has {}",
389 plural(snap.summary.revisions, "change")
390 ),
391 Ok(Location::Paragraph(id)) => match paragraph_place(&id) {
392 Some((story, _)) if story != "body" => {
393 match snap.stories.iter().find(|s| s.id == story) {
394 Some(found) => format!(
395 "no paragraph {target} in the source; the story {story} has {}",
396 plural(found.paragraphs.len(), "paragraph")
397 ),
398 None => format!(
399 "no paragraph {target} in the source; the source has no {story} story; {body}"
400 ),
401 }
402 }
403 Some(_) => format!("no paragraph {target} in the source; {body}"),
404 None => format!(
405 "no paragraph {target} in the source; the source has {}",
406 plural(snap.tables.len(), "table")
407 ),
408 },
409 Err(refused) => match &refused.hint {
410 Some(hint) => {
411 format!(
412 "no paragraph {target} in the source; the settled spelling is {hint}; {body}"
413 )
414 }
415 None => format!("no paragraph {target} in the source; {body}"),
416 },
417 }
418}
419
420fn several_changes(snap: &Snapshot, refusal: &AnchorRefusal<'_>) -> Error {
423 let one_by_one: Vec<String> = parse_change_ids(refusal.target)
424 .map(|ids| ids.iter().map(|change| change.short()).collect())
425 .unwrap_or_default();
426 let spelled = match one_by_one.as_slice() {
427 [rest @ .., last] if rest.len() < 3 => format!("{} or {last}", rest.join(" or ")),
428 _ => String::new(),
429 };
430 let mut error = base(&snap.source_sha256, refusal, "INVALID_EDIT").with_message(format!(
431 "{} names {} marks; an anchor targets one{}",
432 refusal.target,
433 one_by_one.len(),
434 if spelled.is_empty() {
435 String::new()
436 } else {
437 format!(" ({spelled})")
438 }
439 ));
440 error.push_next_action(read_target(refusal));
441 error
442}
443
444fn base(digest: &str, refusal: &AnchorRefusal<'_>, code: &str) -> Error {
447 let mut error = Error::new(code)
448 .with_source_digest(digest)
449 .with_target(refusal.target)
450 .with_retryable(false)
451 .with_commit_state(CommitState::NotCommitted);
452 if let Some(operation) = refusal.operation {
453 error = error.with_operation(operation);
454 }
455 error
456}
457
458fn refused(
463 snap: &Snapshot,
464 working: &str,
465 skip: &str,
466 refusal: &AnchorRefusal<'_>,
467 edit: &EditError,
468 occurrence: Option<usize>,
469 expected: Option<usize>,
470) -> Error {
471 let mut error = base(&snap.source_sha256, refusal, &edit.code);
472 if edit.code == "INVALID_EDIT" {
473 error = error.with_message(edit.message.clone());
474 error.push_next_action(read_target(refusal));
475 return error;
476 }
477 let candidates = v2_candidates(working, refusal.anchor);
478 let count = candidates.len();
479 error = error.with_matches(count);
480 error.near = edit.near.as_deref().cloned();
481 let near_range = error
482 .near
483 .as_ref()
484 .and_then(|near| near.occurrences.first())
485 .map(|hit| (hit.offset, hit.offset + hit.text.len()));
486 error = error.with_context(match candidates.first().copied().or(near_range) {
487 Some((start, end)) => around(working, start, end),
488 None => Context::new(bounded_start(working), "", "")
489 .with_truncated(working.chars().count() > WINDOW),
490 });
491 let shown_anchor = quoted_anchor(refusal.anchor);
492 let mut message = match (count, occurrence, expected) {
493 (0, _, _) => format!(
494 "{shown_anchor} occurs 0 times in {}; {} starts {}",
495 refusal.target,
496 refusal.target,
497 shown(&bounded_start(working))
498 ),
499 (_, _, _) if edit.code == "OVERLAPPING_EDITS" => format!(
502 "{shown_anchor} occurs {count} times in {} and those ranges overlap, so none of them is replaced",
503 refusal.target
504 ),
505 (_, _, Some(wanted)) => format!(
506 "{shown_anchor} occurs {count} times in {}, not the expected {wanted}",
507 refusal.target
508 ),
509 (_, None, _) => format!(
510 "{shown_anchor} occurs {count} times in {}; set \"occurrence\" to 1..={count}",
511 refusal.target
512 ),
513 (_, Some(k), _) if k > count => format!(
514 "{shown_anchor} occurs {count} times in {}; occurrence {k} is outside occurrence 1..={count}",
515 refusal.target
516 ),
517 (_, Some(_), None) => format!("{shown_anchor} occurs {count} times in {}", refusal.target),
522 };
523 error.push_next_action(read_target(refusal));
524 if count == 0 {
525 let suggestions = suggestions_elsewhere(snap, skip, refusal.anchor);
527 if !suggestions.list.is_empty() {
528 message.push_str("; it occurs elsewhere: ");
529 message.push_str(
530 &suggestions
531 .list
532 .iter()
533 .map(|(id, hits)| format!("{id} ({hits})"))
534 .collect::<Vec<_>>()
535 .join(", "),
536 );
537 if suggestions.more > 0 {
538 message.push_str(&format!(", … (+{} more paragraphs)", suggestions.more));
539 }
540 for (id, hits) in &suggestions.list {
541 error.push_next_action(suggest_read(refusal, id, *hits));
542 }
543 }
544 }
545 error.with_message(message)
546}
547
548fn suggestions_elsewhere(snap: &Snapshot, skip: &str, anchor: &str) -> Suggestions {
552 let mut list = Vec::new();
553 let mut more = 0;
554 for paragraph in snap.paragraphs.iter().chain(
555 snap.stories
556 .iter()
557 .flat_map(|story| story.paragraphs.iter()),
558 ) {
559 if paragraph.id == skip {
560 continue;
561 }
562 let hits = v2_candidates(¶graph.text, anchor).len();
563 if hits == 0 {
564 continue;
565 }
566 if list.len() == MAX_SUGGESTED_TARGETS {
567 more += 1;
568 } else {
569 list.push((paragraph.id.clone(), hits));
570 }
571 }
572 Suggestions { list, more }
573}
574
575struct Suggestions {
577 list: Vec<(String, usize)>,
579 more: usize,
581}
582
583fn bounded_start(working: &str) -> String {
585 working.chars().take(WINDOW).collect()
586}
587
588fn quoted_anchor(anchor: &str) -> String {
592 let count = anchor.chars().count();
593 if count <= WINDOW {
594 return shown(anchor);
595 }
596 let head: String = anchor.chars().take(WINDOW).collect();
597 format!(
598 "{}\u{2026} (+{} more characters)",
599 shown(&head),
600 count - WINDOW
601 )
602}
603
604fn around(working: &str, start: usize, end: usize) -> Context {
608 let matched = &working[start..end];
609 let matched_cut = matched.chars().count() > WINDOW;
610 let matched: String = matched.chars().take(WINDOW).collect();
611 let before: String = working[..start].chars().rev().take(WINDOW).collect();
612 let before: String = before.chars().rev().collect();
613 let after: String = working[end..].chars().take(WINDOW).collect();
614 Context::new(before, matched, after).with_truncated(
615 matched_cut
616 || working[..start].chars().count() > WINDOW
617 || working[end..].chars().count() > WINDOW,
618 )
619}
620
621fn plural(n: usize, word: &str) -> String {
623 format!("{n} {word}{}", if n == 1 { "" } else { "s" })
624}
625
626fn read_action(refusal: &AnchorRefusal<'_>, options: [String; 2]) -> NextAction {
631 let mut argv = vec!["jubarte".to_string(), "read".to_string()];
632 match refusal.path {
633 Some(path) if path.starts_with('-') => {
634 argv.extend(options);
635 argv.extend(["--".to_string(), path.to_string()]);
636 NextAction::new(argv)
637 }
638 Some(path) => {
639 argv.push(path.to_string());
640 argv.extend(options);
641 NextAction::new(argv)
642 }
643 None => {
644 argv.extend(options);
645 NextAction::new(argv).with_prerequisites(vec![
646 "the source file path (the refusal binds its digest)".to_string(),
647 ])
648 }
649 }
650}
651
652fn read_target(refusal: &AnchorRefusal<'_>) -> NextAction {
654 read_action(refusal, ["-p".to_string(), refusal.target.to_string()])
655 .with_purpose(format!("read the actual text of {}", refusal.target))
656}
657
658fn read_head(refusal: &AnchorRefusal<'_>) -> NextAction {
660 read_action(
661 refusal,
662 ["--head".to_string(), READ_SUGGESTION_HEAD.to_string()],
663 )
664 .with_purpose("list the paragraphs that exist, bounded".to_string())
665}
666
667fn suggest_read(refusal: &AnchorRefusal<'_>, id: &str, hits: usize) -> NextAction {
670 let mut action = read_action(refusal, ["-p".to_string(), id.to_string()]);
671 let mut prerequisites = action.prerequisites.take().unwrap_or_default();
672 prerequisites.push("re-targeting is the caller's decision".to_string());
673 action
674 .with_purpose(format!(
675 "suggestion only: the anchor occurs {hits} times in {id}; a supplied target is never retargeted"
676 ))
677 .with_prerequisites(prerequisites)
678}
679
680#[cfg(test)]
681#[cfg_attr(all(coverage_nightly, test), coverage(off))]
682mod tests {
683 use super::*;
684
685 #[test]
686 fn a_miss_shows_the_bounded_start_of_the_target() {
687 assert_eq!(bounded_start("0123456789"), "0123456789");
688 let long = "x".repeat(WINDOW + 5);
689 assert_eq!(bounded_start(&long).chars().count(), WINDOW);
690 }
691
692 #[test]
693 fn a_match_context_is_banded_on_both_sides() {
694 let text = format!("{}y{}z", "a".repeat(WINDOW + 3), "b".repeat(WINDOW + 7));
695 let start = WINDOW + 3;
696 let end = start + 1;
697 let context = around(&text, start, end);
698 assert_eq!(context.matched, "y");
699 assert_eq!(context.before.chars().count(), WINDOW);
700 assert_eq!(context.after.chars().count(), WINDOW);
701 assert!(context.truncated);
702 let context = around("abcYdef", 3, 4);
703 assert_eq!(
704 (
705 context.before.as_str(),
706 context.matched.as_str(),
707 context.after.as_str()
708 ),
709 ("abc", "Y", "def")
710 );
711 assert!(!context.truncated);
712 }
713
714 #[test]
715 fn a_pasted_clause_anchor_is_quoted_bounded() {
716 let short = "needle";
717 assert_eq!(quoted_anchor(short), shown(short));
718 let clause = "c".repeat(3 * WINDOW);
719 let quoted = quoted_anchor(&clause);
720 assert!(!quoted.contains(&clause), "{quoted}");
721 assert_eq!(
722 quoted,
723 format!(
724 "{}\u{2026} (+{} more characters)",
725 shown(&"c".repeat(WINDOW)),
726 2 * WINDOW
727 )
728 );
729 let text = clause.clone();
731 let context = around(&text, 0, text.len());
732 assert_eq!(context.matched, "c".repeat(WINDOW));
733 assert!(context.truncated);
734 }
735
736 #[test]
737 fn counts_are_pluralized() {
738 assert_eq!(plural(1, "paragraph"), "1 paragraph");
739 assert_eq!(plural(2, "revision"), "2 revisions");
740 }
741}