use std::borrow::Cow;
use std::fmt::{self, Write};
use std::ops::Range;
use std::time::{Duration, Instant};
use serde_json::{json, Value};
use similar::{udiff::unified_diff, Algorithm, DiffTag, TextDiff};
use tokio_util::sync::CancellationToken;
use crate::env::check_cancel_file;
use crate::error::{FileError, FileErrorCode};
pub const DIFF_TIME_BUDGET: Duration = Duration::from_millis(250);
pub(super) const MAX_DIFF_INPUT_BYTES: usize = 2 * 1024 * 1024;
const MAX_DIFF_OUTPUT_BYTES: usize = 256 * 1024;
pub(super) fn diff_skipped(reason: &str) -> Value {
json!({ "diff_skipped": reason })
}
pub(super) async fn mutation_diff_details(
path: String,
old: String,
new: String,
cancel: &CancellationToken,
) -> Value {
if cancel.is_cancelled() {
return diff_skipped("cancelled");
}
if old.len().saturating_add(new.len()) > MAX_DIFF_INPUT_BYTES {
return diff_skipped("content_too_large");
}
let worker_cancel = cancel.clone();
let mut worker = tokio::task::spawn_blocking(move || {
render_mutation_preview(&path, &old, &new, &worker_cancel)
});
tokio::select! {
biased;
_ = cancel.cancelled() => {
worker.abort();
diff_skipped("cancelled")
}
result = &mut worker => match result {
Ok(details) => details,
Err(error) => {
tracing::warn!(%error, "file mutation preview task failed");
diff_skipped("diff_task_failed")
}
},
}
}
fn render_mutation_preview(path: &str, old: &str, new: &str, cancel: &CancellationToken) -> Value {
if cancel.is_cancelled() {
return diff_skipped("cancelled");
}
let started = Instant::now();
let parts = TextDiff::configure()
.timeout(DIFF_TIME_BUDGET)
.diff_lines(old, new);
if started.elapsed() > DIFF_TIME_BUDGET {
return diff_skipped("timeout");
}
let mut added = 0;
let mut removed = 0;
for op in parts.ops() {
if op.tag() != DiffTag::Equal {
added += op.new_range().len();
removed += op.old_range().len();
}
}
let line_changes = json!({ "added": added, "removed": removed });
let mut output = PreviewBuffer {
text: String::new(),
remaining: MAX_DIFF_OUTPUT_BYTES,
started,
cancel,
failure: None,
};
let result = (|| -> Result<_, fmt::Error> {
write_display_diff(&mut output, &parts, 4)?;
let display = std::mem::take(&mut output.text);
let mut patch = parts.unified_diff();
patch.context_radius(4).header(path, path);
write!(output, "{patch}")?;
Ok((display, std::mem::take(&mut output.text)))
})();
match result {
Ok((diff, patch)) => json!({
"diff": diff,
"patch": patch,
"first_changed_line": first_changed_line(&parts),
"line_changes": line_changes,
}),
Err(_) => json!({
"diff_skipped": output.failure.unwrap_or("diff_task_failed"),
"line_changes": line_changes,
}),
}
}
struct PreviewBuffer<'a> {
text: String,
remaining: usize,
started: Instant,
cancel: &'a CancellationToken,
failure: Option<&'static str>,
}
impl fmt::Write for PreviewBuffer<'_> {
fn write_str(&mut self, text: &str) -> fmt::Result {
let failure = if self.cancel.is_cancelled() {
Some("cancelled")
} else if self.started.elapsed() > DIFF_TIME_BUDGET {
Some("timeout")
} else if text.len() > self.remaining {
Some("output_too_large")
} else {
None
};
if let Some(reason) = failure {
self.failure = Some(reason);
return Err(fmt::Error);
}
self.remaining -= text.len();
self.text.push_str(text);
Ok(())
}
}
pub struct BomResult<'a> {
pub bom: &'static str,
pub text: &'a str,
}
pub fn strip_bom(content: &str) -> BomResult<'_> {
const BOM: &str = "\u{FEFF}";
if let Some(rest) = content.strip_prefix(BOM) {
BomResult {
bom: BOM,
text: rest,
}
} else {
BomResult {
bom: "",
text: content,
}
}
}
pub fn detect_line_ending(content: &str) -> &'static str {
let first_crlf = content.find("\r\n");
let first_lf = content.find('\n');
match (first_crlf, first_lf) {
(None, None) => "\n",
(Some(_), None) => "\n",
(Some(crlf), Some(lf)) => {
if crlf <= lf {
"\r\n"
} else {
"\n"
}
}
(None, Some(_)) => "\n",
}
}
pub fn normalize_to_lf(text: &str) -> String {
if text.contains('\r') {
text.replace("\r\n", "\n").replace('\r', "\n")
} else {
text.to_owned()
}
}
pub fn restore_line_endings(text: &str, ending: &str) -> String {
if ending == "\r\n" {
text.replace('\n', "\r\n")
} else {
text.to_string()
}
}
pub fn normalize_for_fuzzy_match(text: &str) -> String {
use unicode_normalization::UnicodeNormalization;
let nfkc: String = text.nfkc().collect();
let mut out = String::with_capacity(nfkc.len());
for (index, line) in nfkc.split('\n').enumerate() {
if index != 0 {
out.push('\n');
}
for c in line.trim_end().chars() {
match c {
'\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => out.push('\''),
'\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => out.push('"'),
'\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}'
| '\u{2212}' => out.push('-'),
'\u{00A0}' | '\u{2002}' | '\u{2003}' | '\u{2004}' | '\u{2005}' | '\u{2006}'
| '\u{2007}' | '\u{2008}' | '\u{2009}' | '\u{200A}' | '\u{202F}' | '\u{205F}'
| '\u{3000}' => out.push(' '),
other => out.push(other),
}
}
}
out
}
#[derive(Clone)]
pub struct FuzzyMatchResult {
pub found: bool,
pub index: usize,
pub match_length: usize,
pub used_fuzzy_match: bool,
pub content_for_replacement: String,
}
pub fn fuzzy_find_text(content: &str, old_text: &str) -> FuzzyMatchResult {
if let Some(idx) = content.find(old_text) {
return FuzzyMatchResult {
found: true,
index: idx,
match_length: old_text.len(),
used_fuzzy_match: false,
content_for_replacement: content.to_string(),
};
}
let fuzzy_old = normalize_for_fuzzy_match(old_text);
if !fuzzy_old.trim().is_empty() {
let fuzzy_content = normalize_for_fuzzy_match(content);
if let Some(idx) = fuzzy_content.find(&fuzzy_old) {
return FuzzyMatchResult {
found: true,
index: idx,
match_length: fuzzy_old.len(),
used_fuzzy_match: true,
content_for_replacement: fuzzy_content,
};
}
}
FuzzyMatchResult {
found: false,
index: usize::MAX,
match_length: 0,
used_fuzzy_match: false,
content_for_replacement: content.to_string(),
}
}
pub fn count_occurrences(content: &str, old_text: &str) -> usize {
let fc = normalize_for_fuzzy_match(content);
let fo = normalize_for_fuzzy_match(old_text);
if fo.is_empty() {
return 0;
}
fc.matches(&fo).count()
}
#[derive(Clone)]
pub struct ReplaceEdit {
pub old_text: String,
pub new_text: String,
}
struct MatchedEdit<'a> {
edit_index: usize,
match_index: usize,
match_length: usize,
new_text: &'a str,
}
struct NormalizedEdit {
old_text: String,
fuzzy_old_text: String,
new_text: String,
exact_match: Option<usize>,
}
#[derive(Debug)]
pub struct ApplyResult {
pub base_content: String,
pub new_content: String,
pub used_fuzzy_match: bool,
}
pub fn apply_edits_to_normalized_content(
normalized_content: &str,
edits: &[ReplaceEdit],
path: &str,
) -> Result<ApplyResult, FileError> {
apply_edits_with_cancel(normalized_content, edits, path, None)
}
pub(super) fn apply_edits_with_cancel(
normalized_content: &str,
edits: &[ReplaceEdit],
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<ApplyResult, FileError> {
let total = edits.len();
let mut normalized_edits = Vec::with_capacity(total);
for (i, edit) in edits.iter().enumerate() {
check_cancel_file(cancel, Some(path))?;
let old_text = normalize_to_lf(&edit.old_text);
if old_text.is_empty() {
return Err(FileError::new(
FileErrorCode::Invalid,
empty_old_text_error(path, i, total),
)
.with_path(path));
}
normalized_edits.push(NormalizedEdit {
fuzzy_old_text: normalize_for_fuzzy_match(&old_text),
exact_match: normalized_content.find(&old_text),
old_text,
new_text: normalize_to_lf(&edit.new_text),
});
}
check_cancel_file(cancel, Some(path))?;
let fuzzy_content = normalize_for_fuzzy_match(normalized_content);
let mut used_fuzzy_match = false;
for edit in &normalized_edits {
check_cancel_file(cancel, Some(path))?;
if edit.exact_match.is_none()
&& !edit.fuzzy_old_text.trim().is_empty()
&& fuzzy_content.contains(&edit.fuzzy_old_text)
{
used_fuzzy_match = true;
break;
}
}
let replacement_base = if used_fuzzy_match {
fuzzy_content.as_str()
} else {
normalized_content
};
let duplicate_base = if used_fuzzy_match {
Cow::Owned(normalize_for_fuzzy_match(replacement_base))
} else {
Cow::Borrowed(fuzzy_content.as_str())
};
let mut matched_edits = Vec::with_capacity(total);
for (i, edit) in normalized_edits.iter().enumerate() {
check_cancel_file(cancel, Some(path))?;
let exact = if used_fuzzy_match {
replacement_base.find(&edit.old_text)
} else {
edit.exact_match
};
let matched = exact.map(|idx| (idx, edit.old_text.len())).or_else(|| {
if used_fuzzy_match && !edit.fuzzy_old_text.trim().is_empty() {
replacement_base
.find(&edit.fuzzy_old_text)
.map(|idx| (idx, edit.fuzzy_old_text.len()))
} else {
None
}
});
let Some((match_index, match_length)) = matched else {
return Err(
FileError::new(FileErrorCode::NotFound, not_found_error(path, i, total))
.with_path(path),
);
};
if !edit.fuzzy_old_text.is_empty() {
let occurrences = duplicate_base.matches(&edit.fuzzy_old_text).count();
if occurrences > 1 {
return Err(FileError::new(
FileErrorCode::Invalid,
format!(
"{}{}",
duplicate_error(path, i, total, occurrences),
duplicate_match_context(
normalized_content,
&fuzzy_content,
&edit.fuzzy_old_text,
),
),
)
.with_path(path));
}
}
matched_edits.push(MatchedEdit {
edit_index: i,
match_index,
match_length,
new_text: &edit.new_text,
});
}
matched_edits.sort_unstable_by_key(|m| (m.match_index, m.edit_index));
for pair in matched_edits.windows(2) {
let prev = &pair[0];
let cur = &pair[1];
if prev.match_index + prev.match_length > cur.match_index {
return Err(FileError::new(
FileErrorCode::Invalid,
format!(
"edits[{}] and edits[{}] overlap in {}. Merge them into one edit or target disjoint regions.",
prev.edit_index, cur.edit_index, path
),
)
.with_path(path));
}
}
check_cancel_file(cancel, Some(path))?;
let new_content = if used_fuzzy_match {
apply_replacements_preserving_unchanged_lines(
normalized_content,
replacement_base,
&matched_edits,
)?
} else {
let mut out = String::with_capacity(normalized_content.len());
append_replacements(
&mut out,
normalized_content,
0..normalized_content.len(),
&matched_edits,
);
out
};
check_cancel_file(cancel, Some(path))?;
if normalized_content == new_content {
return Err(
FileError::new(FileErrorCode::Invalid, no_change_error(path, total)).with_path(path),
);
}
Ok(ApplyResult {
base_content: normalized_content.to_owned(),
new_content,
used_fuzzy_match,
})
}
fn append_replacements(
out: &mut String,
content: &str,
span: Range<usize>,
replacements: &[MatchedEdit<'_>],
) {
let mut cursor = span.start;
for replacement in replacements {
out.push_str(&content[cursor..replacement.match_index]);
out.push_str(replacement.new_text);
cursor = replacement.match_index + replacement.match_length;
}
out.push_str(&content[cursor..span.end]);
}
fn apply_replacements_preserving_unchanged_lines(
original_content: &str,
base_content: &str,
replacements: &[MatchedEdit<'_>],
) -> Result<String, FileError> {
let original_lines: Vec<_> = original_content.split_inclusive('\n').collect();
let mut base_lines = get_line_spans(base_content);
if base_content.ends_with('\n') && !original_content.ends_with('\n') {
base_lines.push((base_content.len(), base_content.len()));
}
if original_lines.len() != base_lines.len() {
return Err(FileError::new(
FileErrorCode::Invalid,
"Cannot preserve unchanged lines because the base content has a different line count.",
));
}
let mut groups: Vec<(Range<usize>, Range<usize>)> = Vec::new();
for (i, replacement) in replacements.iter().enumerate() {
let lines = get_replacement_line_range(
&base_lines,
replacement.match_index,
replacement.match_index + replacement.match_length,
);
if let Some((group_lines, group_edits)) = groups.last_mut() {
if lines.start < group_lines.end {
group_lines.end = group_lines.end.max(lines.end);
group_edits.end = i + 1;
continue;
}
}
groups.push((lines, i..i + 1));
}
let mut out = String::with_capacity(original_content.len());
let mut original_line_idx = 0;
for (lines, edits) in groups {
for line in &original_lines[original_line_idx..lines.start] {
out.push_str(line);
}
append_replacements(
&mut out,
base_content,
base_lines[lines.start].0..base_lines[lines.end - 1].1,
&replacements[edits],
);
original_line_idx = lines.end;
}
for line in &original_lines[original_line_idx..] {
out.push_str(line);
}
Ok(out)
}
fn get_line_spans(content: &str) -> Vec<(usize, usize)> {
let mut spans = Vec::new();
let mut start = 0;
for line in content.split_inclusive('\n') {
let end = start + line.len();
spans.push((start, end));
start = end;
}
spans
}
fn get_replacement_line_range(
lines: &[(usize, usize)],
start_offset: usize,
end_offset: usize,
) -> Range<usize> {
let start = lines.partition_point(|&(_, end)| end <= start_offset);
let end = lines.partition_point(|&(_, end)| end < end_offset) + 1;
start..end
}
pub struct DiffResult {
pub diff: String,
pub first_changed_line: Option<usize>,
}
pub fn generate_diff_string(
old_content: &str,
new_content: &str,
context_lines: usize,
) -> DiffResult {
let parts = TextDiff::from_lines(old_content, new_content);
build_diff_result(&parts, context_lines)
}
pub fn generate_diff_string_budgeted(
old_content: &str,
new_content: &str,
context_lines: usize,
budget: Duration,
) -> Option<DiffResult> {
let started = Instant::now();
let parts = TextDiff::configure()
.timeout(budget)
.diff_lines(old_content, new_content);
if started.elapsed() > budget {
return None;
}
Some(build_diff_result(&parts, context_lines))
}
fn build_diff_result(parts: &TextDiff<'_, '_, '_, str>, context_lines: usize) -> DiffResult {
let mut diff = String::new();
write_display_diff(&mut diff, parts, context_lines).expect("writing to a String cannot fail");
DiffResult {
diff,
first_changed_line: first_changed_line(parts),
}
}
fn first_changed_line(parts: &TextDiff<'_, '_, '_, str>) -> Option<usize> {
parts
.ops()
.iter()
.find(|op| op.tag() != DiffTag::Equal)
.map(|op| op.new_range().start + 1)
}
fn write_display_diff(
out: &mut impl fmt::Write,
parts: &TextDiff<'_, '_, '_, str>,
context_lines: usize,
) -> fmt::Result {
let old = parts.old_slices();
let new = parts.new_slices();
let gutter_lines = |lines: &[&str]| {
lines.len() + usize::from(lines.last().is_some_and(|line| line.ends_with('\n')))
};
let width = gutter_lines(old).max(gutter_lines(new)).to_string().len();
let mut separator = "";
let ops = parts.ops();
for (index, op) in ops.iter().enumerate() {
let old_range = op.old_range();
let new_range = op.new_range();
if op.tag() == DiffTag::Equal {
let after_change = index > 0 && ops[index - 1].tag() != DiffTag::Equal;
let before_change = ops
.get(index + 1)
.is_some_and(|next| next.tag() != DiffTag::Equal);
if !after_change && !before_change {
continue;
}
let lines = &old[old_range.clone()];
let head = if after_change {
context_lines.min(lines.len())
} else {
0
};
let tail = if before_change {
context_lines.min(lines.len() - head)
} else {
0
};
write_diff_rows(
out,
&mut separator,
' ',
old_range.start,
&lines[..head],
width,
)?;
let skip_until = lines.len() - tail;
if head < skip_until {
write!(out, "{separator} {:>width$} ...", "")?;
separator = "\n";
}
write_diff_rows(
out,
&mut separator,
' ',
old_range.start + skip_until,
&lines[skip_until..],
width,
)?;
} else {
write_diff_rows(
out,
&mut separator,
'-',
old_range.start,
&old[old_range],
width,
)?;
write_diff_rows(
out,
&mut separator,
'+',
new_range.start,
&new[new_range],
width,
)?;
}
}
Ok(())
}
fn write_diff_rows(
out: &mut impl fmt::Write,
separator: &mut &str,
sign: char,
offset: usize,
lines: &[&str],
width: usize,
) -> fmt::Result {
for (index, line) in lines.iter().enumerate() {
let number = offset + index + 1;
let body = line.trim_end_matches(['\r', '\n']);
write!(out, "{separator}{sign}{number:>width$} {body}")?;
*separator = "\n";
}
Ok(())
}
pub fn generate_unified_patch(path: &str, old_content: &str, new_content: &str) -> String {
unified_diff(
Algorithm::Myers,
old_content,
new_content,
4,
Some((path, path)),
)
}
pub fn generate_unified_patch_budgeted(
path: &str,
old_content: &str,
new_content: &str,
budget: Duration,
) -> Option<String> {
let started = Instant::now();
let parts = TextDiff::configure()
.timeout(budget)
.diff_lines(old_content, new_content);
if started.elapsed() > budget {
return None;
}
let mut diff = parts.unified_diff();
diff.context_radius(4).header(path, path);
Some(diff.to_string())
}
fn empty_old_text_error(path: &str, i: usize, total: usize) -> String {
if total == 1 {
format!("oldText must not be empty in {path}.")
} else {
format!("edits[{i}].oldText must not be empty in {path}.")
}
}
fn not_found_error(path: &str, i: usize, total: usize) -> String {
if total == 1 {
format!("Could not find the exact text in {path}. The old text must match exactly including all whitespace and newlines.")
} else {
format!("Could not find edits[{i}] in {path}. The old text must match exactly including all whitespace and newlines.")
}
}
fn duplicate_error(path: &str, i: usize, total: usize, occurrences: usize) -> String {
if total == 1 {
format!("Found {occurrences} occurrences of the text in {path}. The text must be unique — include more surrounding context to disambiguate.")
} else {
format!("Found {occurrences} occurrences of edits[{i}] in {path}. The text must be unique — include more surrounding context to disambiguate.")
}
}
fn duplicate_match_context(content: &str, normalized: &str, needle: &str) -> String {
const MAX_MATCHES: usize = 5;
const MAX_LINE_CHARS: usize = 200;
let mut line_starts = vec![0];
line_starts.extend(normalized.match_indices('\n').map(|(index, _)| index + 1));
let original_lines: Vec<&str> = content.split('\n').collect();
let mut out = String::from(
"\nMatching locations (line labels are diagnostic; do not include them in oldText):\n",
);
for (number, (offset, _)) in normalized.match_indices(needle).enumerate() {
if number == MAX_MATCHES {
out.push_str("[More matches omitted; use read to inspect the intended region.]\n");
break;
}
let line = line_starts.partition_point(|start| *start <= offset) - 1;
out.push_str(&format!("Match {} at line {}:\n", number + 1, line + 1));
let start = line.saturating_sub(1);
let end = (line + 2).min(original_lines.len());
for (index, text) in original_lines.iter().enumerate().take(end).skip(start) {
let snippet: String = text.chars().take(MAX_LINE_CHARS).collect();
let suffix = if text.chars().nth(MAX_LINE_CHARS).is_some() {
" [line truncated]"
} else {
""
};
out.push_str(&format!("{}: {snippet}{suffix}\n", index + 1));
}
}
out.push_str("Read the intended region and include enough surrounding text to make oldText unique before retrying.");
out
}
fn no_change_error(path: &str, total: usize) -> String {
if total == 1 {
format!("No changes made to {path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.")
} else {
format!("No changes made to {path}. The replacements produced identical content.")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_to_lf_collapses_crlf_and_cr() {
assert_eq!(normalize_to_lf("a\r\nb\rc\n"), "a\nb\nc\n");
}
#[test]
fn detect_line_ending_prefers_crlf_when_first() {
assert_eq!(detect_line_ending("a\r\nb\nc"), "\r\n");
assert_eq!(detect_line_ending("a\nb\r\nc"), "\n");
assert_eq!(detect_line_ending("noslash"), "\n");
}
#[test]
fn preview_writer_stops_without_appending_after_cancellation() {
let cancel = CancellationToken::new();
let mut output = PreviewBuffer {
text: String::new(),
remaining: 100,
started: Instant::now(),
cancel: &cancel,
failure: None,
};
output.write_str("existing").unwrap();
cancel.cancel();
assert!(output.write_str(" late").is_err());
assert_eq!(output.text, "existing");
assert_eq!(output.failure, Some("cancelled"));
}
#[test]
fn diff_string_shows_replaced_lines_old_then_new() {
let old = "keep\nold one\nold two\nkeep\n";
let new = "keep\nnew\nkeep\n";
let diff = generate_diff_string(old, new, 4).diff;
assert_eq!(diff, " 1 keep\n-2 old one\n-3 old two\n+2 new\n 4 keep");
}
#[test]
fn strip_bom_removes_prefix() {
let r = strip_bom("\u{FEFF}hello");
assert_eq!(r.bom, "\u{FEFF}");
assert_eq!(r.text, "hello");
let r2 = strip_bom("hello");
assert_eq!(r2.bom, "");
assert_eq!(r2.text, "hello");
}
#[test]
fn fuzzy_find_exact_then_smart_quotes() {
let content = "it's a test";
let m = fuzzy_find_text(content, "it's a test");
assert!(m.found);
assert!(!m.used_fuzzy_match);
let m2 = fuzzy_find_text(content, "it\u{2019}s a test");
assert!(m2.found);
assert!(m2.used_fuzzy_match);
}
#[test]
fn apply_edits_single_replacement() {
let content = "line1\nline2\nline3\n";
let edits = vec![ReplaceEdit {
old_text: "line2".to_string(),
new_text: "LINE2".to_string(),
}];
let r = apply_edits_to_normalized_content(content, &edits, "/x").unwrap();
assert!(r.new_content.contains("LINE2"));
assert!(!r.new_content.contains("line2"));
}
#[test]
fn apply_edits_not_found_errors() {
let content = "line1\nline2\n";
let edits = vec![ReplaceEdit {
old_text: "nope".to_string(),
new_text: "yep".to_string(),
}];
let r = apply_edits_to_normalized_content(content, &edits, "/x");
assert!(r.is_err());
assert_eq!(r.unwrap_err().code, crate::error::FileErrorCode::NotFound);
}
#[test]
fn apply_edits_duplicate_errors() {
let content = "dup\nmid\ndup\n";
let edits = vec![ReplaceEdit {
old_text: "dup".to_string(),
new_text: "x".to_string(),
}];
let r = apply_edits_to_normalized_content(content, &edits, "/x");
assert!(r.is_err());
let error = r.unwrap_err();
assert_eq!(error.code, crate::error::FileErrorCode::Invalid);
let message = error.to_string();
assert!(message.contains("Match 1 at line 1"));
assert!(message.contains("Match 2 at line 3"));
assert!(message.contains("2: mid"));
}
#[test]
fn duplicate_diagnostics_preserve_original_unicode_and_batch_index() {
let edits = vec![
ReplaceEdit {
old_text: "heading".into(),
new_text: "title".into(),
},
ReplaceEdit {
old_text: "it's".into(),
new_text: "changed".into(),
},
];
let error = apply_edits_to_normalized_content(
"heading\n第一处 it’s\n中间\n第二处 it's\n",
&edits,
"/x",
)
.unwrap_err()
.to_string();
assert!(error.contains("2 occurrences of edits[1]"));
assert!(error.contains("Match 1 at line 2"));
assert!(error.contains("Match 2 at line 4"));
assert!(error.contains("2: 第一处 it’s"));
}
#[test]
fn duplicate_diagnostics_bound_matches_and_long_unicode_lines() {
let content = format!("{} repeated\n", "界".repeat(1000)).repeat(20);
let normalized = normalize_for_fuzzy_match(&content);
let context = duplicate_match_context(&content, &normalized, "repeated");
assert!(context.contains("Match 5 at line 5"));
assert!(!context.contains("Match 6"));
assert!(context.contains("More matches omitted"));
assert!(context.contains("[line truncated]"));
assert!(context.len() < 12_000);
}
#[test]
fn apply_edits_overlap_errors() {
let content = "overlap region here\n";
let edits = vec![
ReplaceEdit {
old_text: "overlap region".to_string(),
new_text: "A".to_string(),
},
ReplaceEdit {
old_text: "region here".to_string(),
new_text: "B".to_string(),
},
];
let r = apply_edits_to_normalized_content(content, &edits, "/x");
assert!(r.is_err());
let msg = r.unwrap_err().to_string();
assert!(msg.contains("overlap"));
}
#[test]
fn apply_edits_no_change_errors() {
let content = "same\n";
let edits = vec![ReplaceEdit {
old_text: "same".to_string(),
new_text: "same".to_string(),
}];
let r = apply_edits_to_normalized_content(content, &edits, "/x");
assert!(r.is_err());
let msg = r.unwrap_err().to_string();
assert!(msg.contains("No changes"));
}
#[test]
fn generate_unified_patch_has_headers() {
let patch = generate_unified_patch("/x", "a\nb\n", "a\nB\n");
assert!(patch.contains("--- /x"));
assert!(patch.contains("+++ /x"));
assert!(patch.contains("-b"));
assert!(patch.contains("+B"));
}
}