use super::EditError;
use super::anchor::{shown, v2_candidates, v2_select, v2_select_all};
use crate::comments::CommentRecord;
use crate::ids::{
Location, ShortId, Step, Story, paragraph_place, parse_change_ids, parse_location,
};
use crate::inspect::{InspectError, Paragraph, Snapshot, snapshot, source_sha256};
use crate::result::{CommitState, Context, Error, NextAction};
const WINDOW: usize = 20;
const MAX_SUGGESTED_TARGETS: usize = 5;
const READ_SUGGESTION_HEAD: usize = 20;
#[derive(Clone, Copy, Debug)]
pub struct AnchorRefusal<'a> {
pub operation: Option<&'a str>,
pub target: &'a str,
pub anchor: &'a str,
pub path: Option<&'a str>,
}
impl<'a> AnchorRefusal<'a> {
pub fn new(target: &'a str, anchor: &'a str) -> Self {
Self {
operation: None,
target,
anchor,
path: None,
}
}
#[must_use]
pub fn with_operation(mut self, operation: &'a str) -> Self {
self.operation = Some(operation);
self
}
#[must_use]
pub fn with_path(mut self, path: &'a str) -> Self {
self.path = Some(path);
self
}
}
#[derive(Clone, Copy, Debug)]
pub enum Working<'a> {
InSource,
Settled(&'a str),
}
pub fn v2_resolve(
source: &[u8],
working: Working<'_>,
refusal: &AnchorRefusal<'_>,
occurrence: Option<usize>,
) -> Result<(usize, usize), Box<Error>> {
let snap = open(source, refusal)?;
let target = find_target(&snap, refusal.target);
let text = match (target, working) {
(Target::Missing, _) => return Err(Box::new(missing_target(&snap, refusal))),
(Target::SeveralChanges, _) => {
return Err(Box::new(several_changes(&snap, refusal)));
}
(Target::Here(text), Working::InSource) => text,
(Target::Here(_), Working::Settled(text)) => text,
};
let skip = skip_id(&snap, refusal.target);
match v2_select(text, refusal.anchor, occurrence) {
Ok(range) => Ok(range),
Err(edit) => Err(Box::new(refused(
&snap, text, &skip, refusal, &edit, occurrence, None,
))),
}
}
pub fn v2_resolve_all(
source: &[u8],
working: Working<'_>,
refusal: &AnchorRefusal<'_>,
expected: usize,
) -> Result<Vec<(usize, usize)>, Box<Error>> {
let snap = open(source, refusal)?;
let target = find_target(&snap, refusal.target);
let text = match (target, working) {
(Target::Missing, _) => return Err(Box::new(missing_target(&snap, refusal))),
(Target::SeveralChanges, _) => {
return Err(Box::new(several_changes(&snap, refusal)));
}
(Target::Here(text), Working::InSource) => text,
(Target::Here(_), Working::Settled(text)) => text,
};
let skip = skip_id(&snap, refusal.target);
match v2_select_all(text, refusal.anchor, expected) {
Ok(ranges) => Ok(ranges),
Err(edit) => Err(Box::new(refused(
&snap,
text,
&skip,
refusal,
&edit,
None,
Some(expected),
))),
}
}
#[doc(hidden)]
pub fn require_story(source: &[u8], story: &str) -> Result<(), Box<Error>> {
let refusal = AnchorRefusal::new(story, "").with_operation("/operations/0");
let snap = open(source, &refusal)?;
if story == "body" || snap.stories.iter().any(|s| s.id == story) {
return Ok(());
}
let mut error = missing_target(&snap, &refusal);
let available = std::iter::once("body")
.chain(snap.stories.iter().map(|s| s.id.as_str()))
.collect::<Vec<_>>()
.join(", ");
error.message = format!("unknown story {story:?}; the source has stories: {available}");
Err(Box::new(error))
}
fn open(source: &[u8], refusal: &AnchorRefusal<'_>) -> Result<Snapshot, Box<Error>> {
snapshot(source).map_err(|error| {
let code = match &error {
InspectError::Admission(refused) => refused.code(),
_ => "INVALID_DOCUMENT",
};
Box::new(
base(&source_sha256(source), refusal, code).with_message(format!(
"the source could not be read ({error}); no anchor was searched"
)),
)
})
}
enum Target<'s> {
Here(&'s str),
SeveralChanges,
Missing,
}
fn find_target<'s>(snap: &'s Snapshot, target: &str) -> Target<'s> {
match parse_location(target) {
Err(_) => Target::Missing,
Ok(Location::Paragraph(id)) => {
if let Some((story, n)) = paragraph_place(&id) {
let list: &[Paragraph] = if story == "body" {
&snap.paragraphs
} else if let Some(found) = snap.stories.iter().find(|s| s.id == story) {
&found.paragraphs
} else {
return Target::Missing;
};
return match list.get(n) {
Some(paragraph) => Target::Here(¶graph.text),
None => Target::Missing,
};
}
match cell_paragraph(snap, &id) {
Some((_, text)) => Target::Here(text),
None => Target::Missing,
}
}
Ok(Location::Comment(n)) => match comment(snap, n) {
Some(found) => Target::Here(&found.text),
None => Target::Missing,
},
Ok(Location::CommentText(n)) => match comment(snap, n) {
Some(found) => Target::Here(&found.anchor_text),
None => Target::Missing,
},
Ok(Location::Changes(ids)) => {
let spelled: Vec<String> = ids.iter().map(|change| change.short()).collect();
let mark = |short: &str| {
snap.changes.iter().find_map(|change| {
if change.members.is_empty() {
(change.id == short).then_some(change.text.as_str())
} else {
change
.members
.iter()
.find(|member| member.id == short)
.map(|member| member.text.as_str())
}
})
};
if !spelled.iter().all(|short| mark(short).is_some()) {
return Target::Missing;
}
match spelled.as_slice() {
[one] => mark(one).map_or(Target::Missing, Target::Here),
_ => Target::SeveralChanges,
}
}
}
}
fn comment(snap: &Snapshot, n: u32) -> Option<&CommentRecord> {
snap.comments.iter().find(|comment| comment.id == n)
}
fn cell_paragraph<'s>(snap: &'s Snapshot, id: &str) -> Option<(String, &'s str)> {
let Ok(ShortId::Block {
story: Story::Body,
path,
}) = id.parse::<ShortId>()
else {
return None;
};
let [Step::Table(t), Step::Row(row), Step::Cell(cell), rest @ ..] = path.as_slice() else {
return None;
};
let index = match rest {
[] => 0,
[Step::Paragraph(k)] => *k,
_ => return None,
};
let table = snap.tables.iter().find(|table| table.index == *t)?;
let held = table.rows.get(*row)?.get(*cell)?;
let short = held.paragraph_ids.get(index)?;
let (_, n) = paragraph_place(short)?;
let paragraph = snap.paragraphs.get(n)?;
Some((paragraph.id.clone(), ¶graph.text))
}
fn skip_id(snap: &Snapshot, target: &str) -> String {
if let Ok(Location::Paragraph(id)) = parse_location(target)
&& paragraph_place(&id).is_none()
&& let Some((paragraph, _)) = cell_paragraph(snap, &id)
{
return paragraph;
}
target.to_string()
}
fn missing_target(snap: &Snapshot, refusal: &AnchorRefusal<'_>) -> Error {
let mut error = base(&snap.source_sha256, refusal, "ANCHOR_NOT_FOUND")
.with_matches(0)
.with_message(missing_target_message(snap, refusal.target));
error.push_next_action(read_head(refusal));
error
}
fn missing_target_message(snap: &Snapshot, target: &str) -> String {
let body = format!(
"the body has {}",
plural(snap.summary.paragraphs, "paragraph")
);
match parse_location(target) {
Ok(Location::Comment(_)) | Ok(Location::CommentText(_)) => format!(
"no comment {target} in the source; the source has {}",
plural(snap.summary.comments, "comment")
),
Ok(Location::Changes(_)) => format!(
"no revision {target} in the source; the source has {}",
plural(snap.summary.revisions, "change")
),
Ok(Location::Paragraph(id)) => match paragraph_place(&id) {
Some((story, _)) if story != "body" => {
match snap.stories.iter().find(|s| s.id == story) {
Some(found) => format!(
"no paragraph {target} in the source; the story {story} has {}",
plural(found.paragraphs.len(), "paragraph")
),
None => format!(
"no paragraph {target} in the source; the source has no {story} story; {body}"
),
}
}
Some(_) => format!("no paragraph {target} in the source; {body}"),
None => format!(
"no paragraph {target} in the source; the source has {}",
plural(snap.tables.len(), "table")
),
},
Err(refused) => match &refused.hint {
Some(hint) => {
format!(
"no paragraph {target} in the source; the settled spelling is {hint}; {body}"
)
}
None => format!("no paragraph {target} in the source; {body}"),
},
}
}
fn several_changes(snap: &Snapshot, refusal: &AnchorRefusal<'_>) -> Error {
let one_by_one: Vec<String> = parse_change_ids(refusal.target)
.map(|ids| ids.iter().map(|change| change.short()).collect())
.unwrap_or_default();
let spelled = match one_by_one.as_slice() {
[rest @ .., last] if rest.len() < 3 => format!("{} or {last}", rest.join(" or ")),
_ => String::new(),
};
let mut error = base(&snap.source_sha256, refusal, "INVALID_EDIT").with_message(format!(
"{} names {} marks; an anchor targets one{}",
refusal.target,
one_by_one.len(),
if spelled.is_empty() {
String::new()
} else {
format!(" ({spelled})")
}
));
error.push_next_action(read_target(refusal));
error
}
fn base(digest: &str, refusal: &AnchorRefusal<'_>, code: &str) -> Error {
let mut error = Error::new(code)
.with_source_digest(digest)
.with_target(refusal.target)
.with_retryable(false)
.with_commit_state(CommitState::NotCommitted);
if let Some(operation) = refusal.operation {
error = error.with_operation(operation);
}
error
}
fn refused(
snap: &Snapshot,
working: &str,
skip: &str,
refusal: &AnchorRefusal<'_>,
edit: &EditError,
occurrence: Option<usize>,
expected: Option<usize>,
) -> Error {
let mut error = base(&snap.source_sha256, refusal, &edit.code);
if edit.code == "INVALID_EDIT" {
error = error.with_message(edit.message.clone());
error.push_next_action(read_target(refusal));
return error;
}
let candidates = v2_candidates(working, refusal.anchor);
let count = candidates.len();
error = error.with_matches(count);
error.near = edit.near.as_deref().cloned();
let near_range = error
.near
.as_ref()
.and_then(|near| near.occurrences.first())
.map(|hit| (hit.offset, hit.offset + hit.text.len()));
error = error.with_context(match candidates.first().copied().or(near_range) {
Some((start, end)) => around(working, start, end),
None => Context::new(bounded_start(working), "", "")
.with_truncated(working.chars().count() > WINDOW),
});
let shown_anchor = quoted_anchor(refusal.anchor);
let mut message = match (count, occurrence, expected) {
(0, _, _) => format!(
"{shown_anchor} occurs 0 times in {}; {} starts {}",
refusal.target,
refusal.target,
shown(&bounded_start(working))
),
(_, _, _) if edit.code == "OVERLAPPING_EDITS" => format!(
"{shown_anchor} occurs {count} times in {} and those ranges overlap, so none of them is replaced",
refusal.target
),
(_, _, Some(wanted)) => format!(
"{shown_anchor} occurs {count} times in {}, not the expected {wanted}",
refusal.target
),
(_, None, _) => format!(
"{shown_anchor} occurs {count} times in {}; set \"occurrence\" to 1..={count}",
refusal.target
),
(_, Some(k), _) if k > count => format!(
"{shown_anchor} occurs {count} times in {}; occurrence {k} is outside occurrence 1..={count}",
refusal.target
),
(_, Some(_), None) => format!("{shown_anchor} occurs {count} times in {}", refusal.target),
};
error.push_next_action(read_target(refusal));
if count == 0 {
let suggestions = suggestions_elsewhere(snap, skip, refusal.anchor);
if !suggestions.list.is_empty() {
message.push_str("; it occurs elsewhere: ");
message.push_str(
&suggestions
.list
.iter()
.map(|(id, hits)| format!("{id} ({hits})"))
.collect::<Vec<_>>()
.join(", "),
);
if suggestions.more > 0 {
message.push_str(&format!(", … (+{} more paragraphs)", suggestions.more));
}
for (id, hits) in &suggestions.list {
error.push_next_action(suggest_read(refusal, id, *hits));
}
}
}
error.with_message(message)
}
fn suggestions_elsewhere(snap: &Snapshot, skip: &str, anchor: &str) -> Suggestions {
let mut list = Vec::new();
let mut more = 0;
for paragraph in snap.paragraphs.iter().chain(
snap.stories
.iter()
.flat_map(|story| story.paragraphs.iter()),
) {
if paragraph.id == skip {
continue;
}
let hits = v2_candidates(¶graph.text, anchor).len();
if hits == 0 {
continue;
}
if list.len() == MAX_SUGGESTED_TARGETS {
more += 1;
} else {
list.push((paragraph.id.clone(), hits));
}
}
Suggestions { list, more }
}
struct Suggestions {
list: Vec<(String, usize)>,
more: usize,
}
fn bounded_start(working: &str) -> String {
working.chars().take(WINDOW).collect()
}
fn quoted_anchor(anchor: &str) -> String {
let count = anchor.chars().count();
if count <= WINDOW {
return shown(anchor);
}
let head: String = anchor.chars().take(WINDOW).collect();
format!(
"{}\u{2026} (+{} more characters)",
shown(&head),
count - WINDOW
)
}
fn around(working: &str, start: usize, end: usize) -> Context {
let matched = &working[start..end];
let matched_cut = matched.chars().count() > WINDOW;
let matched: String = matched.chars().take(WINDOW).collect();
let before: String = working[..start].chars().rev().take(WINDOW).collect();
let before: String = before.chars().rev().collect();
let after: String = working[end..].chars().take(WINDOW).collect();
Context::new(before, matched, after).with_truncated(
matched_cut
|| working[..start].chars().count() > WINDOW
|| working[end..].chars().count() > WINDOW,
)
}
fn plural(n: usize, word: &str) -> String {
format!("{n} {word}{}", if n == 1 { "" } else { "s" })
}
fn read_action(refusal: &AnchorRefusal<'_>, options: [String; 2]) -> NextAction {
let mut argv = vec!["jubarte".to_string(), "read".to_string()];
match refusal.path {
Some(path) if path.starts_with('-') => {
argv.extend(options);
argv.extend(["--".to_string(), path.to_string()]);
NextAction::new(argv)
}
Some(path) => {
argv.push(path.to_string());
argv.extend(options);
NextAction::new(argv)
}
None => {
argv.extend(options);
NextAction::new(argv).with_prerequisites(vec![
"the source file path (the refusal binds its digest)".to_string(),
])
}
}
}
fn read_target(refusal: &AnchorRefusal<'_>) -> NextAction {
read_action(refusal, ["-p".to_string(), refusal.target.to_string()])
.with_purpose(format!("read the actual text of {}", refusal.target))
}
fn read_head(refusal: &AnchorRefusal<'_>) -> NextAction {
read_action(
refusal,
["--head".to_string(), READ_SUGGESTION_HEAD.to_string()],
)
.with_purpose("list the paragraphs that exist, bounded".to_string())
}
fn suggest_read(refusal: &AnchorRefusal<'_>, id: &str, hits: usize) -> NextAction {
let mut action = read_action(refusal, ["-p".to_string(), id.to_string()]);
let mut prerequisites = action.prerequisites.take().unwrap_or_default();
prerequisites.push("re-targeting is the caller's decision".to_string());
action
.with_purpose(format!(
"suggestion only: the anchor occurs {hits} times in {id}; a supplied target is never retargeted"
))
.with_prerequisites(prerequisites)
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
#[test]
fn a_miss_shows_the_bounded_start_of_the_target() {
assert_eq!(bounded_start("0123456789"), "0123456789");
let long = "x".repeat(WINDOW + 5);
assert_eq!(bounded_start(&long).chars().count(), WINDOW);
}
#[test]
fn a_match_context_is_banded_on_both_sides() {
let text = format!("{}y{}z", "a".repeat(WINDOW + 3), "b".repeat(WINDOW + 7));
let start = WINDOW + 3;
let end = start + 1;
let context = around(&text, start, end);
assert_eq!(context.matched, "y");
assert_eq!(context.before.chars().count(), WINDOW);
assert_eq!(context.after.chars().count(), WINDOW);
assert!(context.truncated);
let context = around("abcYdef", 3, 4);
assert_eq!(
(
context.before.as_str(),
context.matched.as_str(),
context.after.as_str()
),
("abc", "Y", "def")
);
assert!(!context.truncated);
}
#[test]
fn a_pasted_clause_anchor_is_quoted_bounded() {
let short = "needle";
assert_eq!(quoted_anchor(short), shown(short));
let clause = "c".repeat(3 * WINDOW);
let quoted = quoted_anchor(&clause);
assert!(!quoted.contains(&clause), "{quoted}");
assert_eq!(
quoted,
format!(
"{}\u{2026} (+{} more characters)",
shown(&"c".repeat(WINDOW)),
2 * WINDOW
)
);
let text = clause.clone();
let context = around(&text, 0, text.len());
assert_eq!(context.matched, "c".repeat(WINDOW));
assert!(context.truncated);
}
#[test]
fn counts_are_pluralized() {
assert_eq!(plural(1, "paragraph"), "1 paragraph");
assert_eq!(plural(2, "revision"), "2 revisions");
}
}