croft-software 0.2.232

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Applying a result's `fixes[]` (ยง3.55): every replacement of every
//! artifact change, computed against the text croft has for each file.
//!
//! Pure: the caller supplies each file's current text (an open buffer or the
//! file on disk) and applies the result, so a fix lands as one undoable edit
//! in the editor rather than a silent write to disk.

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};

/// One file's text after a fix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileEdit {
    pub path: PathBuf,
    pub before: String,
    pub after: String,
}

/// Compute every file a fix changes. Fails, changing nothing, when a file
/// cannot be found or read, a region does not resolve, replacements overlap,
/// or a replacement inserts binary content. It also fails when a region
/// shows the file is not the text the analyzer saw (#1094): it points past
/// the end of the text, or its `snippet` is not what sits there now.
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"))?;
            // A snippet's line endings may be the analyzer's, not the
            // file's (or the buffer's, which joins lines with `\n`).
            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)
}

/// A result's fixes: its `fixes[]`, then a unified diff in its property bag
/// (`properties.diff`, #577), which some analyzers attach instead.
pub fn fix_count(result: &SarifResult) -> usize {
    result.fixes.len() + usize::from(property_diff(result).is_some())
}

/// Fix `index`'s description, for the Fix tab.
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("@@"))
}

/// Compute fix `index` of `result` ([`fix_count`] orders them).
///
/// `changed` says a file changed since the analysis: it has unsaved edits,
/// or it was saved since ([`saved_after`]). A `fixes[]` fix
/// for such a file is refused (#1094), since its regions are line and
/// column numbers into the text the analyzer saw, and on other text they
/// replace the wrong code. A `properties.diff` fix needs no such guard: it
/// lands only where its context and removed lines still match.
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")),
    }
}

/// Whether `path` was saved since the analysis behind `run` read it, so the
/// log's line and column numbers for it may no longer point at what the
/// analyzer saw (#1094): after the log at `log` was written, or after the
/// run started when its invocations say when (`startTimeUtc`), since a slow
/// analysis reads a file long before it writes the log. `false` when no time
/// can be read.
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)
}

/// A SARIF date-time (ยง3.9: RFC 3339 in UTC, `2026-10-08T16:53:58.123Z`).
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;
    }
    // Days since 1970-01-01, by Howard Hinnant's days_from_civil.
    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))
}

/// Why a fix for a file that moved on since the analysis is refused.
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")
}

/// One file's part of a unified diff.
#[derive(Debug, Clone, PartialEq, Eq)]
struct FilePatch {
    path: String,
    hunks: Vec<PatchHunk>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PatchHunk {
    /// 1-based line the hunk starts at in the old file.
    old_start: usize,
    /// Context and removed lines, as the old file has them.
    old: Vec<String>,
    /// Context and added lines, as the new file has them.
    new: Vec<String>,
}

/// The files and hunks of a unified diff (`git diff` or `diff -u`). A path
/// loses git's `a/`/`b/` prefix; `/dev/null` (a created or deleted file)
/// is refused, as is a hunk whose line counts do not add up.
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());
                }
                // An empty context line whose leading space was trimmed.
                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)
}

/// How far from its stated line a hunk may have moved and still apply.
const DIFF_FUZZ_LINES: usize = 50;

/// Apply a unified diff (ยง3.55's alternative some analyzers put in
/// `properties.diff`) to the files it names, each resolved like an artifact
/// location. Every hunk's context and removed lines must match the file
/// exactly, at its stated line or the nearest place within
/// [`DIFF_FUZZ_LINES`]; otherwise nothing is changed.
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();
        // Later hunks first, so earlier line numbers stay put.
        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)
}

/// A short line diff of what a fix does, for the Fix tab.
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");
        // Two lines were added above since the scan: the hunk moved.
        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")
        );
        // The file changed since the scan, but a diff checks its own context,
        // so it is not refused for that (#1094).
        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()
        );

        // A file that no longer matches is refused, changing nothing.
        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());
        // A result whose property is not a patch offers no fix.
        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() {
        // An open, unsaved buffer is what the fix applies to.
        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");
    }

    /// #1094: a region past the end of its line is the file having changed
    /// since the scan. Pulling it back would land the fix on other code
    /// (`    y = 1` became `    y = 1x is None`), so it is refused.
    #[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"
        );
    }

    /// #1094: a region that fits but no longer holds the snippet the log
    /// recorded for it is refused too.
    #[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}");
        // The same region with the snippet that is there applies.
        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");
        // A CRLF snippet still matches a buffer, whose lines join with `\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");
    }

    /// #1094: a fix is refused, changing nothing, for a file the caller says
    /// changed since the log was written (unsaved edits, or a later save).
    #[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));
        // Saved while a run that started at 1500 s was still going: the log
        // came later, but the file is not what the analyzer read.
        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"]);
    }
}