patchloom 0.1.0

A Rust CLI for agent-grade repo operations
Documentation
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
use crate::cli::global::GlobalFlags;
use crate::diff::{DiffResult, format_diff_result, format_diff_result_colored, unified_diff};
use crate::exit;
use crate::ops::patch::{apply_hunks, parse_patch};
use crate::write::policy_from_flags;
use clap::Args;
use serde::Serialize;

#[derive(Debug, Args)]
#[command(after_help = "\
EXAMPLES:
  patchloom patch apply changes.patch
  patchloom patch apply changes.patch --apply
  patchloom patch check changes.patch")]
pub struct PatchArgs {
    #[command(subcommand)]
    pub action: PatchAction,
    #[command(flatten)]
    pub write: crate::cli::global::WriteFlags,
}

#[derive(Debug, clap::Subcommand)]
pub enum PatchAction {
    /// Check whether a patch applies cleanly.
    Check {
        // ref:patch-mode:file
        /// Path to a diff file.
        file: Option<String>,
        // ref:patch-mode:stdin
        /// Read diff from stdin.
        #[arg(long)]
        stdin: bool,
    },
    /// Apply a unified diff.
    Apply {
        // ref:patch-mode:file
        /// Path to a diff file.
        file: Option<String>,
        // ref:patch-mode:stdin
        /// Read diff from stdin.
        #[arg(long)]
        stdin: bool,
    },
}

// ── Read diff input ────────────────────────────────────────────────

/// Read diff text from the source indicated by the user.
/// Error from reading diff input.
enum DiffReadError {
    /// No input source specified.
    NoSource,
    /// IO error reading the specified file.
    IoError(String, std::io::Error),
    /// IO error reading stdin.
    StdinError(std::io::Error),
}

fn read_diff_input(file: &Option<String>, stdin_flag: bool) -> Result<String, DiffReadError> {
    if let Some(path) = file {
        std::fs::read_to_string(path).map_err(|e| DiffReadError::IoError(path.clone(), e))
    } else if stdin_flag {
        std::io::read_to_string(std::io::stdin()).map_err(DiffReadError::StdinError)
    } else {
        Err(DiffReadError::NoSource)
    }
}

// ── JSON output types ───────────────────────────────────────────────

#[derive(Debug, Serialize)]
struct PatchCheckResult {
    path: String,
    status: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

#[derive(Debug, Serialize)]
struct PatchCheckOutput {
    ok: bool,
    files: Vec<PatchCheckResult>,
}

fn emit_error(global: &GlobalFlags, error: &str) -> anyhow::Result<()> {
    if global.emit_json(&serde_json::json!({
        "ok": false,
        "error": error,
    }))? {
        return Ok(());
    }

    eprintln!("{error}");
    Ok(())
}

// ── Public entry point ──────────────────────────────────────────────

pub fn run(args: PatchArgs, global: &GlobalFlags) -> anyhow::Result<u8> {
    let (file, stdin_flag) = match &args.action {
        PatchAction::Check { file, stdin } => (file.clone(), *stdin),
        PatchAction::Apply { file, stdin } => (file.clone(), *stdin),
    };

    // Read diff input.
    let diff_text = match read_diff_input(&file, stdin_flag) {
        Ok(text) => text,
        Err(DiffReadError::NoSource) => {
            emit_error(global, "patch: must specify --file <path> or --stdin")?;
            return Ok(exit::PARSE_ERROR);
        }
        Err(DiffReadError::IoError(path, e)) => {
            let msg = format!("patch: failed to read '{path}': {e}");
            emit_error(global, &msg)?;
            return Ok(exit::PARSE_ERROR);
        }
        Err(DiffReadError::StdinError(e)) => {
            let msg = format!("patch: failed to read stdin: {e}");
            emit_error(global, &msg)?;
            return Ok(exit::PARSE_ERROR);
        }
    };

    // Parse the unified diff.
    let patch_files = match parse_patch(&diff_text) {
        Ok(pf) => pf,
        Err(msg) => {
            let msg = format!("patch: parse error: {msg}");
            emit_error(global, &msg)?;
            return Ok(exit::PARSE_ERROR);
        }
    };

    let root = global.resolve_cwd()?;

    match args.action {
        PatchAction::Check { .. } => {
            let mut all_clean = true;
            let mut results: Vec<PatchCheckResult> = Vec::new();
            for pf in &patch_files {
                let file_path = root.join(&pf.path);
                let original = match std::fs::read_to_string(&file_path) {
                    Ok(s) => s,
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                        let msg = format!("file not found: {}", file_path.display());
                        results.push(PatchCheckResult {
                            path: pf.path.clone(),
                            status: "missing",
                            error: Some(msg.clone()),
                        });
                        if !global.json && !global.jsonl && !global.quiet {
                            eprintln!("patch check: {} -- MISSING: {}", pf.path, msg);
                        }
                        all_clean = false;
                        continue;
                    }
                    Err(e) => {
                        let msg = format!("failed to read {}: {}", file_path.display(), e);
                        results.push(PatchCheckResult {
                            path: pf.path.clone(),
                            status: "error",
                            error: Some(msg.clone()),
                        });
                        if !global.json && !global.jsonl && !global.quiet {
                            eprintln!("patch check: {} -- READ ERROR: {}", pf.path, msg);
                        }
                        all_clean = false;
                        continue;
                    }
                };
                match apply_hunks(&original, &pf.hunks) {
                    Ok(_) => {
                        results.push(PatchCheckResult {
                            path: pf.path.clone(),
                            status: "clean",
                            error: None,
                        });
                        if !global.json && !global.jsonl && !global.quiet {
                            eprintln!("patch check: {} -- clean", pf.path);
                        }
                    }
                    Err(msg) => {
                        results.push(PatchCheckResult {
                            path: pf.path.clone(),
                            status: "stale",
                            error: Some(msg.clone()),
                        });
                        if !global.json && !global.jsonl && !global.quiet {
                            eprintln!("patch check: {} -- STALE: {}", pf.path, msg);
                        }
                        all_clean = false;
                    }
                }
            }
            if global.json {
                let output = PatchCheckOutput {
                    ok: all_clean,
                    files: results,
                };
                println!("{}", serde_json::to_string_pretty(&output)?);
            } else if global.jsonl {
                for r in &results {
                    println!("{}", serde_json::to_string(r)?);
                }
            }
            if all_clean {
                Ok(exit::SUCCESS)
            } else {
                Ok(exit::AMBIGUOUS)
            }
        }
        PatchAction::Apply { .. } => {
            let mut diffs = Vec::new();
            let mut file_changes: Vec<(std::path::PathBuf, String)> = Vec::new();

            for pf in &patch_files {
                let file_path = root.join(&pf.path);
                let original = match std::fs::read_to_string(&file_path) {
                    Ok(s) => s,
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
                    Err(e) => {
                        let msg = format!(
                            "patch apply: {} -- READ ERROR: failed to read {}: {}",
                            pf.path,
                            file_path.display(),
                            e
                        );
                        emit_error(global, &msg)?;
                        return Ok(exit::AMBIGUOUS);
                    }
                };
                let patched = match apply_hunks(&original, &pf.hunks) {
                    Ok(p) => p,
                    Err(msg) => {
                        let msg = format!("patch apply: {} -- STALE: {}", pf.path, msg);
                        emit_error(global, &msg)?;
                        return Ok(exit::AMBIGUOUS);
                    }
                };

                diffs.push(unified_diff(&pf.path, &original, &patched));
                file_changes.push((file_path, patched));
            }

            // --check mode: report whether changes would be made, exit 2.
            if global.check {
                let has_changes = diffs.iter().any(|d| d.has_changes);
                if has_changes {
                    if !global.quiet {
                        let changed = diffs.iter().filter(|d| d.has_changes).count();
                        println!("{changed} file(s) would change");
                    }
                    return Ok(exit::CHANGES_DETECTED);
                }
                return Ok(exit::SUCCESS);
            }

            // --apply mode: write files to disk.
            if global.apply {
                let policies: Vec<_> = file_changes
                    .iter()
                    .map(|(p, _)| policy_from_flags(global, Some(p.as_path())))
                    .collect();
                let writes: Vec<_> = file_changes
                    .iter()
                    .zip(&policies)
                    .map(|((p, c), pol)| (p.as_path(), c.as_str(), pol))
                    .collect();
                crate::backup::backup_write_files(&root, &writes)?;
                for (file_path, _) in &file_changes {
                    if !global.quiet {
                        eprintln!("patch apply: {} -- written", file_path.display());
                    }
                }
                if global.diff {
                    let changed = diffs.iter().filter(|d| d.has_changes).count();
                    let result = DiffResult {
                        diffs,
                        total_files_changed: changed,
                    };
                    print!("{}", format_diff_result(&result));
                }
                return Ok(exit::SUCCESS);
            }

            // Default / --diff mode: show unified diffs without writing.
            let changed = diffs.iter().filter(|d| d.has_changes).count();
            let result = DiffResult {
                diffs,
                total_files_changed: changed,
            };
            print!(
                "{}",
                format_diff_result_colored(&result, global.should_color())
            );
            if global.show_status() {
                eprintln!("{} file(s) changed", result.total_files_changed);
            }

            // --confirm: prompt after showing diff, then apply if confirmed.
            if global.should_apply() {
                let policies: Vec<_> = file_changes
                    .iter()
                    .map(|(p, _)| policy_from_flags(global, Some(p.as_path())))
                    .collect();
                let writes: Vec<_> = file_changes
                    .iter()
                    .zip(&policies)
                    .map(|((p, c), pol)| (p.as_path(), c.as_str(), pol))
                    .collect();
                crate::backup::backup_write_files(&root, &writes)?;
            }

            Ok(exit::SUCCESS)
        }
    }
}

// ── Tests ───────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::global::GlobalFlags;
    use crate::ops::patch::{Hunk, PatchLine};
    use tempfile::TempDir;

    /// Helper: default `GlobalFlags` pointing at a directory.
    fn flags_for(dir: &std::path::Path) -> GlobalFlags {
        GlobalFlags {
            cwd: Some(dir.to_string_lossy().into_owned()),
            ..GlobalFlags::default()
        }
    }

    // ── parse_patch tests ───────────────────────────────────────────

    #[test]
    fn parse_simple_single_file_diff() {
        let diff = "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,3 @@
 line1
-old line
+new line
 line3
";
        let files = parse_patch(diff).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "hello.txt");
        assert_eq!(files[0].hunks.len(), 1);

        let h = &files[0].hunks[0];
        assert_eq!(h.old_start, 1);
        assert_eq!(h.old_count, 3);
        assert_eq!(h.new_start, 1);
        assert_eq!(h.new_count, 3);
        assert_eq!(h.lines.len(), 4);
        assert_eq!(h.lines[0], PatchLine::Context("line1".into()));
        assert_eq!(h.lines[1], PatchLine::Remove("old line".into()));
        assert_eq!(h.lines[2], PatchLine::Add("new line".into()));
        assert_eq!(h.lines[3], PatchLine::Context("line3".into()));
    }

    #[test]
    fn parse_multi_file_diff() {
        let diff = "\
--- a/file1.txt
+++ b/file1.txt
@@ -1,2 +1,2 @@
 aaa
-bbb
+ccc
--- a/file2.txt
+++ b/file2.txt
@@ -1,2 +1,2 @@
 xxx
-yyy
+zzz
";
        let files = parse_patch(diff).unwrap();
        assert_eq!(files.len(), 2);
        assert_eq!(files[0].path, "file1.txt");
        assert_eq!(files[1].path, "file2.txt");
        assert_eq!(files[0].hunks.len(), 1);
        assert_eq!(files[1].hunks.len(), 1);
    }

    // ── apply_hunks tests ───────────────────────────────────────────

    #[test]
    fn apply_simple_hunk_correctly() {
        let original = "line1\nold line\nline3\n";
        let hunks = vec![Hunk {
            old_start: 1,
            old_count: 3,
            new_start: 1,
            new_count: 3,
            lines: vec![
                PatchLine::Context("line1".into()),
                PatchLine::Remove("old line".into()),
                PatchLine::Add("new line".into()),
                PatchLine::Context("line3".into()),
            ],
        }];
        let result = apply_hunks(original, &hunks).unwrap();
        assert_eq!(result, "line1\nnew line\nline3\n");
    }

    #[test]
    fn stale_context_returns_error() {
        let original = "line1\ncompletely different\nline3\n";
        let hunks = vec![Hunk {
            old_start: 1,
            old_count: 3,
            new_start: 1,
            new_count: 3,
            lines: vec![
                PatchLine::Context("line1".into()),
                PatchLine::Remove("old line".into()),
                PatchLine::Add("new line".into()),
                PatchLine::Context("line3".into()),
            ],
        }];
        let result = apply_hunks(original, &hunks);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("stale context"));
    }

    #[test]
    fn apply_with_fuzz_offset() {
        // The hunk says old_start=2, but the matching context is actually at
        // line 4 (0-based: 3).  Within fuzz range of 3, so it should still
        // apply.
        let original = "extra1\nextra2\nline1\nold line\nline3\n";
        let hunks = vec![Hunk {
            old_start: 1,
            old_count: 3,
            new_start: 1,
            new_count: 3,
            lines: vec![
                PatchLine::Context("line1".into()),
                PatchLine::Remove("old line".into()),
                PatchLine::Add("new line".into()),
                PatchLine::Context("line3".into()),
            ],
        }];
        let result = apply_hunks(original, &hunks).unwrap();
        assert_eq!(result, "extra1\nextra2\nline1\nnew line\nline3\n");
    }

    // ── Integration: check subcommand ───────────────────────────────

    #[test]
    fn check_reports_clean_when_hunks_match() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        std::fs::write(&file, "line1\nold line\nline3\n").unwrap();

        let diff_path = tmp.path().join("change.patch");
        std::fs::write(
            &diff_path,
            "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,3 @@
 line1
-old line
+new line
 line3
",
        )
        .unwrap();

        let global = flags_for(tmp.path());
        let args = PatchArgs {
            action: PatchAction::Check {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }

    #[test]
    fn check_reports_stale_context_with_exit_5() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        std::fs::write(&file, "line1\ncompletely different\nline3\n").unwrap();

        let diff_path = tmp.path().join("stale.patch");
        std::fs::write(
            &diff_path,
            "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,3 @@
 line1
-old line
+new line
 line3
",
        )
        .unwrap();

        let global = flags_for(tmp.path());
        let args = PatchArgs {
            action: PatchAction::Check {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::AMBIGUOUS);
    }

    #[test]
    fn check_reports_missing_file() {
        let tmp = TempDir::new().unwrap();
        // Do NOT create hello.txt — it should be reported as missing.
        let diff_path = tmp.path().join("missing.patch");
        std::fs::write(
            &diff_path,
            "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,3 @@
 line1
-old line
+new line
 line3
",
        )
        .unwrap();

        let global = flags_for(tmp.path());
        let args = PatchArgs {
            action: PatchAction::Check {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::AMBIGUOUS, "missing file should fail check");
    }

    // ── Integration: apply subcommand ───────────────────────────────

    #[test]
    fn apply_check_rejects_directory_target() {
        let tmp = TempDir::new().unwrap();
        let dir_target = tmp.path().join("hello.txt");
        std::fs::create_dir(&dir_target).unwrap();

        let diff_path = tmp.path().join("dir.patch");
        std::fs::write(
            &diff_path,
            "\
--- a/hello.txt
+++ b/hello.txt
@@ -0,0 +1 @@
+new line
",
        )
        .unwrap();

        let mut global = flags_for(tmp.path());
        global.check = true;
        let args = PatchArgs {
            action: PatchAction::Apply {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::AMBIGUOUS);
        assert!(dir_target.is_dir());
    }

    #[test]
    fn apply_rejects_directory_target() {
        let tmp = TempDir::new().unwrap();
        let dir_target = tmp.path().join("hello.txt");
        std::fs::create_dir(&dir_target).unwrap();

        let diff_path = tmp.path().join("dir.patch");
        std::fs::write(
            &diff_path,
            "\
--- a/hello.txt
+++ b/hello.txt
@@ -0,0 +1 @@
+new line
",
        )
        .unwrap();

        let mut global = flags_for(tmp.path());
        global.apply = true;
        let args = PatchArgs {
            action: PatchAction::Apply {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::AMBIGUOUS);
        assert!(dir_target.is_dir());
    }

    #[test]
    fn apply_writes_patched_file() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        std::fs::write(&file, "line1\nold line\nline3\n").unwrap();

        let diff_path = tmp.path().join("change.patch");
        std::fs::write(
            &diff_path,
            "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,3 @@
 line1
-old line
+new line
 line3
",
        )
        .unwrap();

        let mut global = flags_for(tmp.path());
        global.apply = true;
        let args = PatchArgs {
            action: PatchAction::Apply {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let content = std::fs::read_to_string(&file).unwrap();
        assert_eq!(content, "line1\nnew line\nline3\n");
    }

    #[test]
    fn apply_dry_run_does_not_write() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        std::fs::write(&file, "line1\nold line\nline3\n").unwrap();

        let diff_path = tmp.path().join("change.patch");
        std::fs::write(
            &diff_path,
            "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,3 @@
 line1
-old line
+new line
 line3
",
        )
        .unwrap();

        // Without --apply, default is dry-run (show diff, don't write).
        let global = flags_for(tmp.path());
        let args = PatchArgs {
            action: PatchAction::Apply {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        // File should NOT have been modified.
        let content = std::fs::read_to_string(&file).unwrap();
        assert_eq!(
            content, "line1\nold line\nline3\n",
            "file should remain unchanged in dry-run mode"
        );
    }

    // ── Malformed diff ──────────────────────────────────────────────

    #[test]
    fn malformed_diff_returns_parse_error() {
        let tmp = TempDir::new().unwrap();
        let diff_path = tmp.path().join("bad.patch");
        std::fs::write(&diff_path, "this is not a diff at all\n").unwrap();

        let global = flags_for(tmp.path());
        let args = PatchArgs {
            action: PatchAction::Check {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::PARSE_ERROR);
    }

    #[test]
    fn no_input_source_returns_parse_error() {
        let tmp = TempDir::new().unwrap();
        let global = flags_for(tmp.path());
        let args = PatchArgs {
            action: PatchAction::Check {
                file: None,
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::PARSE_ERROR);
    }

    // ── Additional parser edge-case tests ───────────────────────────

    #[test]
    fn parse_diff_with_git_prefix_lines() {
        let diff = "\
diff --git a/foo.rs b/foo.rs
index abc1234..def5678 100644
--- a/foo.rs
+++ b/foo.rs
@@ -1,2 +1,2 @@
 fn main() {
-    println!(\"hello\");
+    println!(\"world\");
";
        let files = parse_patch(diff).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "foo.rs");
    }

    #[test]
    fn parse_hunk_without_comma_count() {
        // Single-line ranges like `@@ -1 +1 @@` (count defaults to 1).
        let diff = "\
--- a/one.txt
+++ b/one.txt
@@ -1 +1 @@
-old
+new
";
        let files = parse_patch(diff).unwrap();
        let h = &files[0].hunks[0];
        assert_eq!(h.old_count, 1);
        assert_eq!(h.new_count, 1);
    }

    #[test]
    fn apply_creates_backup_session() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        std::fs::write(&file, "line1\nold line\nline3\n").unwrap();

        let diff_path = tmp.path().join("change.patch");
        std::fs::write(
            &diff_path,
            "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,3 @@
 line1
-old line
+new line
 line3
",
        )
        .unwrap();

        let mut global = flags_for(tmp.path());
        global.apply = true;
        let args = PatchArgs {
            action: PatchAction::Apply {
                file: Some(diff_path.to_string_lossy().into_owned()),
                stdin: false,
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let backup_dir = tmp.path().join(".patchloom").join("backups");
        assert!(
            backup_dir.exists(),
            "backup directory should exist after patch --apply"
        );
        let sessions: Vec<_> = std::fs::read_dir(&backup_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert!(
            !sessions.is_empty(),
            "at least one backup session should be created"
        );
    }
}