use super::model::{Fix, Run, SarifResult};
use super::region::{Lines, byte_span, column_kind, newline_sequences, slice, text_range};
use super::resolve::Resolver;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileEdit {
pub path: PathBuf,
pub before: String,
pub after: String,
}
pub fn apply_fix(
run: &Run,
fix: &Fix,
resolver: &Resolver,
read: &mut dyn FnMut(&Path) -> Option<String>,
) -> Result<Vec<FileEdit>, String> {
let kind = column_kind(run);
let newlines = newline_sequences(run);
let mut out = Vec::new();
for change in &fix.artifact_changes {
let uri = change
.artifact_location
.uri
.clone()
.unwrap_or_else(|| String::from("(unnamed file)"));
let path = resolver
.resolve(run, &change.artifact_location, &|p| p.is_file())
.ok_or_else(|| format!("{uri} is not on this machine"))?;
let before = read(&path).ok_or_else(|| format!("{} could not be read", path.display()))?;
let lines = Lines::new(&before, &newlines);
let mut spans: Vec<(usize, usize, String)> = Vec::new();
for rep in &change.replacements {
let inserted = match &rep.inserted_content {
None => String::new(),
Some(c) => match (&c.text, &c.binary) {
(Some(t), _) => t.clone(),
(None, Some(_)) => {
return Err(format!(
"{uri}: a binary replacement cannot be applied as text"
));
}
(None, None) => String::new(),
},
};
let range = text_range(&rep.deleted_region, &lines, kind)
.ok_or_else(|| format!("{uri}: a replacement's region does not resolve"))?;
let unix = |s: &str| s.replace("\r\n", "\n");
let snippet = rep.deleted_region.snippet.as_ref();
if range.clamped
|| snippet
.and_then(|s| s.text.as_deref())
.is_some_and(|s| unix(slice(&lines, &range)) != unix(s))
{
return Err(changed_since_analysis(&path));
}
let (a, b) = byte_span(&lines, &range);
spans.push((a, b, inserted));
}
spans.sort_by_key(|s| (s.0, s.1));
if spans.windows(2).any(|w| w[1].0 < w[0].1) {
return Err(format!("{uri}: the fix's replacements overlap"));
}
let mut after = before.clone();
for (a, b, text) in spans.iter().rev() {
after.replace_range(*a..*b, text);
}
out.push(FileEdit {
path,
before,
after,
});
}
Ok(out)
}
pub fn fix_count(result: &SarifResult) -> usize {
result.fixes.len() + usize::from(property_diff(result).is_some())
}
pub fn fix_description(result: &SarifResult, index: usize) -> Option<String> {
match result.fixes.get(index) {
Some(f) => Some(
f.description
.as_ref()
.and_then(|m| m.text.clone())
.unwrap_or_else(|| String::from("(no description)")),
),
None if index == result.fixes.len() => {
property_diff(result).map(|_| String::from("the patch in properties.diff"))
}
None => None,
}
}
fn property_diff(result: &SarifResult) -> Option<&str> {
result
.properties
.get("diff")
.and_then(|d| d.as_str())
.filter(|d| d.contains("@@"))
}
pub fn fix_for(
run: &Run,
result: &SarifResult,
index: usize,
resolver: &Resolver,
read: &mut dyn FnMut(&Path) -> Option<String>,
changed: &dyn Fn(&Path) -> bool,
) -> Result<Vec<FileEdit>, String> {
if let Some(fix) = result.fixes.get(index) {
let edits = apply_fix(run, fix, resolver, read)?;
if let Some(stale) = edits.iter().find(|e| changed(&e.path)) {
return Err(changed_since_analysis(&stale.path));
}
return Ok(edits);
}
match property_diff(result) {
Some(diff) if index == result.fixes.len() => apply_diff(run, diff, resolver, read),
_ => Err(String::from("no such fix")),
}
}
pub fn saved_after(path: &Path, log: &Path, run: &Run) -> bool {
let mtime = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
let started = run
.invocations
.iter()
.filter_map(|i| i.start_time_utc.as_deref().and_then(parse_utc))
.min();
let since = [mtime(log), started].into_iter().flatten().min();
matches!((mtime(path), since), (Some(file), Some(since)) if file > since)
}
fn parse_utc(s: &str) -> Option<std::time::SystemTime> {
let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
let num = |p: &str| p.parse::<u64>().ok().filter(|_| digits(p));
let (date, time) = s.strip_suffix(['Z', 'z'])?.split_once(['T', 't'])?;
let (hms, frac) = time.split_once('.').unwrap_or((time, "0"));
let date: Vec<u64> = date.split('-').map(num).collect::<Option<_>>()?;
let hms: Vec<u64> = hms.split(':').map(num).collect::<Option<_>>()?;
let (&[y, m, d], &[h, min, sec]) = (date.as_slice(), hms.as_slice()) else {
return None;
};
if y < 1970
|| !(1..=12).contains(&m)
|| !(1..=31).contains(&d)
|| h > 23
|| min > 59
|| sec > 60
{
return None;
}
let y = if m <= 2 { y - 1 } else { y };
let (era, yoe) = (y / 400, y % 400);
let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;
let days = era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468;
if !digits(frac) {
return None;
}
let nanos: u32 = format!("{frac:0<9}").get(..9)?.parse().ok()?;
let secs = days * 86_400 + h * 3_600 + min * 60 + sec.min(59);
Some(std::time::UNIX_EPOCH + std::time::Duration::new(secs, nanos))
}
fn changed_since_analysis(path: &Path) -> String {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
format!("{name} changed since the analysis; re-run the analyzer")
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct FilePatch {
path: String,
hunks: Vec<PatchHunk>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct PatchHunk {
old_start: usize,
old: Vec<String>,
new: Vec<String>,
}
fn parse_unified(diff: &str) -> Result<Vec<FilePatch>, String> {
let mut files: Vec<FilePatch> = Vec::new();
let mut lines = diff.lines().peekable();
while let Some(line) = lines.next() {
if let Some(target) = line.strip_prefix("+++ ") {
let target = target.split('\t').next().unwrap_or(target).trim();
if target == "/dev/null" {
return Err(String::from(
"the patch deletes a file, which is not applied",
));
}
let path = target.strip_prefix("b/").unwrap_or(target).to_string();
files.push(FilePatch {
path,
hunks: Vec::new(),
});
continue;
}
let Some(header) = line.strip_prefix("@@ ") else {
continue;
};
let file = files
.last_mut()
.ok_or_else(|| String::from("a hunk comes before any file header"))?;
let bad = || format!("unreadable hunk header: {line}");
let old_spec = header.split_whitespace().next().ok_or_else(bad)?;
let new_spec = header.split_whitespace().nth(1).ok_or_else(bad)?;
let counts = |spec: &str, sign: char| -> Option<(usize, usize)> {
let spec = spec.strip_prefix(sign)?;
let (start, len) = spec.split_once(',').unwrap_or((spec, "1"));
Some((start.parse().ok()?, len.parse().ok()?))
};
let (old_start, old_len) = counts(old_spec, '-').ok_or_else(bad)?;
let (_, new_len) = counts(new_spec, '+').ok_or_else(bad)?;
let mut hunk = PatchHunk {
old_start,
old: Vec::new(),
new: Vec::new(),
};
while hunk.old.len() < old_len || hunk.new.len() < new_len {
let Some(body) = lines.next() else { break };
match body.chars().next() {
Some('-') => hunk.old.push(body[1..].to_string()),
Some('+') => hunk.new.push(body[1..].to_string()),
Some('\\') => {}
Some(' ') => {
hunk.old.push(body[1..].to_string());
hunk.new.push(body[1..].to_string());
}
None => {
hunk.old.push(String::new());
hunk.new.push(String::new());
}
Some(_) => return Err(format!("unreadable hunk line: {body}")),
}
}
if hunk.old.len() != old_len || hunk.new.len() != new_len {
return Err(format!("a hunk's lines do not match its header: {line}"));
}
file.hunks.push(hunk);
}
if files.iter().all(|f| f.hunks.is_empty()) {
return Err(String::from("the patch changes nothing"));
}
Ok(files)
}
const DIFF_FUZZ_LINES: usize = 50;
pub fn apply_diff(
run: &Run,
diff: &str,
resolver: &Resolver,
read: &mut dyn FnMut(&Path) -> Option<String>,
) -> Result<Vec<FileEdit>, String> {
let mut out = Vec::new();
for patch in parse_unified(diff)? {
let loc = super::model::ArtifactLocation {
uri: Some(patch.path.clone()),
..Default::default()
};
let path = resolver
.resolve(run, &loc, &|p| p.is_file())
.ok_or_else(|| format!("{} is not on this machine", patch.path))?;
let before = read(&path).ok_or_else(|| format!("{} could not be read", path.display()))?;
let trailing_newline = before.ends_with('\n');
let mut lines: Vec<String> = before.lines().map(str::to_string).collect();
let mut hunks = patch.hunks.clone();
hunks.sort_by_key(|h| std::cmp::Reverse(h.old_start));
for h in &hunks {
let stated = h.old_start.saturating_sub(1);
let fits = |at: usize| {
at + h.old.len() <= lines.len()
&& lines[at..at + h.old.len()]
.iter()
.zip(&h.old)
.all(|(a, b)| a.trim_end_matches('\r') == b.trim_end_matches('\r'))
};
let at = (0..=DIFF_FUZZ_LINES)
.flat_map(|d| [stated.checked_add(d), stated.checked_sub(d)])
.flatten()
.find(|&at| fits(at))
.ok_or_else(|| {
format!(
"{}: the patch no longer matches the file near line {}",
patch.path, h.old_start
)
})?;
lines.splice(at..at + h.old.len(), h.new.iter().cloned());
}
let mut after = lines.join("\n");
if trailing_newline && !after.is_empty() {
after.push('\n');
}
out.push(FileEdit {
path,
before,
after,
});
}
Ok(out)
}
pub fn preview(edits: &[FileEdit]) -> Vec<String> {
use crate::diff::{DiffRow, build_diff_rows};
let mut out = Vec::new();
for e in edits {
out.push(
e.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| e.path.display().to_string()),
);
let old: Vec<String> = e.before.lines().map(str::to_string).collect();
let new: Vec<String> = e.after.lines().map(str::to_string).collect();
for row in build_diff_rows(&old, &new) {
match row {
DiffRow::Removed { left } => out.push(format!("- {}", old[left])),
DiffRow::Added { right } => out.push(format!("+ {}", new[right])),
DiffRow::Replaced { left, right } => {
out.push(format!("- {}", old[left]));
out.push(format!("+ {}", new[right]));
}
DiffRow::Equal { .. } => {}
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sarif::load::parse_log;
fn run_with_fix(fix_json: &str) -> (Run, Fix) {
let log = parse_log(&format!(
r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"t"}}}},"columnKind":"unicodeCodePoints",
"results":[{{"message":{{"text":"m"}},"fixes":[{fix_json}]}}]}}]}}"#
))
.unwrap();
let run = log.runs.into_iter().next().unwrap();
let fix = run.results.as_ref().unwrap()[0].fixes[0].clone();
(run, fix)
}
fn resolver(root: &Path) -> Resolver {
Resolver {
roots: vec![root.to_path_buf()],
..Resolver::default()
}
}
const DIFF: &str = "diff --git a/src/a.rs b/src/a.rs\n--- a/src/a.rs\n+++ b/src/a.rs\n@@ -2,3 +2,3 @@ fn main() {\n let id = read();\n- let q = format!(\"{}\", id);\n+ let q = escape(&id);\n run(q);\n";
fn diff_result(diff: &str) -> (Run, SarifResult) {
let log = parse_log(&format!(
r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"t"}}}},
"results":[{{"message":{{"text":"m"}},"properties":{{"diff":{}}}}}]}}]}}"#,
serde_json::to_string(diff).unwrap()
))
.unwrap();
let run = log.runs.into_iter().next().unwrap();
let result = run.results.as_ref().unwrap()[0].clone();
(run, result)
}
#[test]
fn a_property_diff_is_a_fix_applied_where_its_context_matches() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
let file = tmp.path().join("src/a.rs");
std::fs::write(
&file,
"// new\n// new\nfn main() {\n let id = read();\n let q = format!(\"{}\", id);\n run(q);\n}\n",
)
.unwrap();
let (run, result) = diff_result(DIFF);
assert_eq!(fix_count(&result), 1);
assert_eq!(
fix_description(&result, 0).as_deref(),
Some("the patch in properties.diff")
);
let edits = fix_for(
&run,
&result,
0,
&resolver(tmp.path()),
&mut |p| std::fs::read_to_string(p).ok(),
&|_| true,
)
.unwrap();
assert_eq!(edits.len(), 1);
assert_eq!(edits[0].path, file);
assert_eq!(
edits[0].after,
"// new\n// new\nfn main() {\n let id = read();\n let q = escape(&id);\n run(q);\n}\n"
);
assert!(
fix_for(
&run,
&result,
1,
&resolver(tmp.path()),
&mut |_| None,
&|_| false
)
.is_err()
);
std::fs::write(&file, "fn main() {\n let q = other();\n}\n").unwrap();
let err = fix_for(
&run,
&result,
0,
&resolver(tmp.path()),
&mut |p| std::fs::read_to_string(p).ok(),
&|_| false,
)
.unwrap_err();
assert!(
err.contains("no longer matches the file near line 2"),
"{err}"
);
}
#[test]
fn a_unified_diff_is_parsed_file_by_file_and_checked() {
let two = format!("{DIFF}--- a/b.rs\n+++ b/b.rs\n@@ -1 +1,2 @@\n x\n+y\n");
let files = parse_unified(&two).unwrap();
assert_eq!(files.len(), 2);
assert_eq!(files[0].path, "src/a.rs");
assert_eq!(files[0].hunks[0].old_start, 2);
assert_eq!(files[0].hunks[0].old.len(), 3);
assert_eq!(files[1].path, "b.rs");
assert_eq!(files[1].hunks[0].new, ["x", "y"]);
assert!(parse_unified("--- a/x\n+++ /dev/null\n@@ -1 +0,0 @@\n-x\n").is_err());
assert!(
parse_unified("@@ -1 +1 @@\n-x\n+y\n").is_err(),
"no file header"
);
assert!(
parse_unified("--- a/x\n+++ b/x\n@@ -1,2 +1,2 @@\n-x\n+y\n").is_err(),
"short hunk"
);
assert!(parse_unified("just text").is_err());
let (_, result) = diff_result("not a diff");
assert_eq!(fix_count(&result), 0);
}
#[test]
fn replacements_apply_back_to_front_in_one_file() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "let q = format!(\"{}\", id);\nrun(q);\n").unwrap();
let (run, fix) = run_with_fix(
r#"{"description":{"text":"sanitize"},"artifactChanges":[{"artifactLocation":{"uri":"a.rs"},"replacements":[
{"deletedRegion":{"startLine":1,"startColumn":23,"endColumn":25},"insertedContent":{"text":"clean(id)"}},
{"deletedRegion":{"startLine":2,"startColumn":1,"endColumn":4},"insertedContent":{"text":"execute"}}
]}]}"#,
);
let edits = apply_fix(&run, &fix, &resolver(tmp.path()), &mut |p| {
std::fs::read_to_string(p).ok()
})
.unwrap();
assert_eq!(edits.len(), 1);
assert_eq!(edits[0].path, file);
assert_eq!(
edits[0].after,
"let q = format!(\"{}\", clean(id));\nexecute(q);\n"
);
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
edits[0].before,
"nothing written"
);
}
#[test]
fn a_deletion_has_no_inserted_content() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("b.py"), "import os\nimport sys\n").unwrap();
let (run, fix) = run_with_fix(
r#"{"artifactChanges":[{"artifactLocation":{"uri":"b.py"},"replacements":[
{"deletedRegion":{"startLine":1,"endLine":2,"endColumn":1}}]}]}"#,
);
let edits = apply_fix(&run, &fix, &resolver(tmp.path()), &mut |p| {
std::fs::read_to_string(p).ok()
})
.unwrap();
assert_eq!(edits[0].after, "import sys\n");
}
#[test]
fn the_callers_text_is_used_not_the_disk() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("c.txt"), "on disk\n").unwrap();
let (run, fix) = run_with_fix(
r#"{"artifactChanges":[{"artifactLocation":{"uri":"c.txt"},"replacements":[
{"deletedRegion":{"startLine":1,"startColumn":1,"endColumn":3},"insertedContent":{"text":"IN"}}]}]}"#,
);
let edits = apply_fix(&run, &fix, &resolver(tmp.path()), &mut |_| {
Some(String::from("in buffer\n"))
})
.unwrap();
assert_eq!(edits[0].after, "IN buffer\n");
}
#[test]
fn a_region_past_the_end_of_the_text_is_refused_not_clamped() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("util.py"),
"def unused(x):\n y = 1\n return x == None\n",
)
.unwrap();
let (run, fix) = run_with_fix(
r#"{"artifactChanges":[{"artifactLocation":{"uri":"util.py"},"replacements":[
{"deletedRegion":{"startLine":2,"startColumn":12,"endColumn":21},"insertedContent":{"text":"x is None"}}]}]}"#,
);
let err = apply_fix(&run, &fix, &resolver(tmp.path()), &mut |p| {
std::fs::read_to_string(p).ok()
})
.unwrap_err();
assert_eq!(
err,
"util.py changed since the analysis; re-run the analyzer"
);
}
#[test]
fn a_region_whose_snippet_is_not_there_is_refused() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("f.py"), " return 1\n").unwrap();
let fix_json = |snippet: &str| {
format!(
r#"{{"artifactChanges":[{{"artifactLocation":{{"uri":"f.py"}},"replacements":[
{{"deletedRegion":{{"startLine":1,"startColumn":5,"endColumn":13,"snippet":{{"text":"{snippet}"}}}},
"insertedContent":{{"text":"x is None"}}}}]}}]}}"#
)
};
let read = &mut |p: &Path| std::fs::read_to_string(p).ok();
let (run, fix) = run_with_fix(&fix_json("x == None"));
let err = apply_fix(&run, &fix, &resolver(tmp.path()), read).unwrap_err();
assert!(err.contains("changed since the analysis"), "{err}");
let (run, fix) = run_with_fix(&fix_json("return 1"));
let edits = apply_fix(&run, &fix, &resolver(tmp.path()), read).unwrap();
assert_eq!(edits[0].after, " x is None\n");
let (run, fix) = run_with_fix(
r#"{"artifactChanges":[{"artifactLocation":{"uri":"f.py"},"replacements":[
{"deletedRegion":{"startLine":1,"startColumn":1,"endLine":2,"endColumn":2,"snippet":{"text":"a\r\nb"}},
"insertedContent":{"text":"c"}}]}]}"#,
);
let edits = apply_fix(&run, &fix, &resolver(tmp.path()), &mut |_| {
Some(String::from("a\nb\n"))
})
.unwrap();
assert_eq!(edits[0].after, "c\n");
}
#[test]
fn a_fix_for_a_file_changed_since_the_log_is_refused() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("g.py"), "a = 1\n").unwrap();
let log = parse_log(
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"t"}},"results":[{"message":{"text":"m"},
"fixes":[{"artifactChanges":[{"artifactLocation":{"uri":"g.py"},"replacements":[
{"deletedRegion":{"startLine":1,"startColumn":1,"endColumn":2},"insertedContent":{"text":"b"}}]}]}]}]}]}"#,
)
.unwrap();
let run = log.runs.into_iter().next().unwrap();
let result = run.results.as_ref().unwrap()[0].clone();
let read = &mut |p: &Path| std::fs::read_to_string(p).ok();
let err = fix_for(&run, &result, 0, &resolver(tmp.path()), read, &|p| {
p.ends_with("g.py")
})
.unwrap_err();
assert_eq!(err, "g.py changed since the analysis; re-run the analyzer");
let edits = fix_for(&run, &result, 0, &resolver(tmp.path()), read, &|_| false).unwrap();
assert_eq!(edits[0].after, "b = 1\n");
}
#[test]
fn saved_after_compares_the_file_with_the_log() {
let tmp = tempfile::tempdir().unwrap();
let (file, log) = (tmp.path().join("a.py"), tmp.path().join("r.sarif"));
std::fs::write(&file, "x\n").unwrap();
std::fs::write(&log, "{}").unwrap();
let at = |p: &Path, secs: u64| {
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
std::fs::File::options()
.write(true)
.open(p)
.unwrap()
.set_modified(t)
.unwrap();
};
let run = |invocations: &str| {
let log = parse_log(&format!(
r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"t"}}}},"invocations":[{invocations}]}}]}}"#
))
.unwrap();
log.runs.into_iter().next().unwrap()
};
let untimed = run("");
at(&file, 1_000);
at(&log, 2_000);
assert!(!saved_after(&file, &log, &untimed), "scanned, then logged");
at(&file, 3_000);
assert!(saved_after(&file, &log, &untimed), "saved after the log");
assert!(!saved_after(&tmp.path().join("gone.py"), &log, &untimed));
at(&file, 1_800);
assert!(!saved_after(&file, &log, &untimed));
let started = run(
r#"{"executionSuccessful":true,"startTimeUtc":"1970-01-01T00:25:00Z"},
{"executionSuccessful":true,"startTimeUtc":"1970-01-01T00:30:00.250Z"}"#,
);
assert!(saved_after(&file, &log, &started));
at(&file, 1_400);
assert!(!saved_after(&file, &log, &started), "saved before it began");
}
#[test]
fn sarif_times_are_read_as_utc() {
let at = |secs: u64, nanos: u32| {
Some(std::time::UNIX_EPOCH + std::time::Duration::new(secs, nanos))
};
assert_eq!(parse_utc("1970-01-01T00:00:00Z"), at(0, 0));
assert_eq!(parse_utc("2000-03-01T00:00:00Z"), at(951_868_800, 0));
assert_eq!(parse_utc("2024-02-29T23:59:59Z"), at(1_709_251_199, 0));
assert_eq!(
parse_utc("2026-10-08T16:53:58.123Z"),
at(1_791_478_438, 123_000_000)
);
for bad in [
"2026-10-08T16:53:58",
"2026-10-08T16:53:58+04:00",
"2026-13-08T16:53:58Z",
"2026-10-08T16:53Z",
"2026-10-08T16:53:58.Z",
"yesterday",
] {
assert_eq!(parse_utc(bad), None, "{bad}");
}
}
#[test]
fn overlapping_replacements_and_missing_files_refuse() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("d.txt"), "abcdef\n").unwrap();
let (run, fix) = run_with_fix(
r#"{"artifactChanges":[{"artifactLocation":{"uri":"d.txt"},"replacements":[
{"deletedRegion":{"startLine":1,"startColumn":1,"endColumn":4},"insertedContent":{"text":"x"}},
{"deletedRegion":{"startLine":1,"startColumn":3,"endColumn":5},"insertedContent":{"text":"y"}}]}]}"#,
);
let err = apply_fix(&run, &fix, &resolver(tmp.path()), &mut |p| {
std::fs::read_to_string(p).ok()
})
.unwrap_err();
assert!(err.contains("overlap"), "{err}");
let (run, fix) = run_with_fix(
r#"{"artifactChanges":[{"artifactLocation":{"uri":"nowhere.txt"},"replacements":[
{"deletedRegion":{"startLine":1},"insertedContent":{"text":"x"}}]}]}"#,
);
let err = apply_fix(&run, &fix, &resolver(tmp.path()), &mut |p| {
std::fs::read_to_string(p).ok()
})
.unwrap_err();
assert!(err.contains("nowhere.txt"), "{err}");
}
#[test]
fn binary_insertions_are_refused() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("e.bin"), "x\n").unwrap();
let (run, fix) = run_with_fix(
r#"{"artifactChanges":[{"artifactLocation":{"uri":"e.bin"},"replacements":[
{"deletedRegion":{"startLine":1},"insertedContent":{"binary":"AAE="}}]}]}"#,
);
let err = apply_fix(&run, &fix, &resolver(tmp.path()), &mut |p| {
std::fs::read_to_string(p).ok()
})
.unwrap_err();
assert!(err.contains("binary"), "{err}");
}
#[test]
fn the_preview_shows_changed_lines_per_file() {
let edits = vec![FileEdit {
path: PathBuf::from("/ws/a.rs"),
before: "one\ntwo\nthree\n".into(),
after: "one\n2\nthree\n".into(),
}];
let p = preview(&edits);
assert_eq!(p, vec!["a.rs", "- two", "+ 2"]);
}
}