patchloom 0.8.0

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
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
814
815
816
817
818
819
820
821
use super::*;
use std::fs;
use tempfile::TempDir;

fn make_args(old: &str, new: &str, paths: Vec<String>) -> ReplaceArgs {
    ReplaceArgs {
        old: old.to_string(),
        new: Some(new.to_string()),
        insert_before: None,
        insert_after: None,
        paths,
        literal: true,
        regex: false,
        if_exists: false,
        multiline: false,
        nth: None,
        case_insensitive: false,
        word_boundary: false,
        whole_line: false,
        range: None,
        write: Default::default(),
    }
}

mod basic {
    use super::*;

    #[test]
    fn literal_replace_works() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\nhello again\n").unwrap();

        let args = make_args(
            "hello",
            "hi",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(replacements[0].match_count, 2);
        assert_eq!(replacements[0].replaced, "hi world\nhi again\n");
    }

    #[test]
    fn regex_replace_works() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "foo123bar\nfoo456baz\n").unwrap();

        let args = ReplaceArgs {
            old: r"foo\d+".to_string(),
            new: Some("replaced".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: false,
            regex: true,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(replacements[0].match_count, 2);
        assert_eq!(replacements[0].replaced, "replacedbar\nreplacedbaz\n");
    }

    #[test]
    fn regex_capture_groups_in_replacement() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "version = \"1.2.3\"\n").unwrap();

        let args = ReplaceArgs {
            old: r#"version = "(\d+)\.(\d+)\.(\d+)""#.to_string(),
            new: Some(r#"version = "$1.$2.99""#.to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: false,
            regex: true,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(replacements.len(), 1);
        assert_eq!(
            replacements[0].replaced, "version = \"1.2.99\"\n",
            "capture groups $1/$2 should work in replacement text"
        );
    }

    #[test]
    fn diff_mode_produces_unified_diff() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "old line\n").unwrap();

        let args = make_args(
            "old",
            "new",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(replacements.len(), 1);

        // Verify the replacement content produces a valid diff.
        let diff = crate::diff::unified_diff(
            &replacements[0].display_path,
            &replacements[0].original,
            &replacements[0].replaced,
        );
        let diff_str = crate::diff::format_diff_result_colored(
            &crate::diff::DiffResult { diffs: vec![diff] },
            false,
        );
        assert!(diff_str.contains("--- a/"));
        assert!(diff_str.contains("+++ b/"));
        assert!(diff_str.contains("-old line"));
        assert!(diff_str.contains("+new line"));
    }

    #[test]
    fn apply_mode_writes_replacement() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        let args = make_args(
            "hello",
            "hi",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let mut global = GlobalFlags::test_default();
        global.apply = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let content = fs::read_to_string(&file).unwrap();
        assert_eq!(content, "hi world\n");
    }

    #[test]
    fn multi_file_replace() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("a.txt"), "hello from a\n").unwrap();
        fs::write(dir.path().join("b.txt"), "hello from b\n").unwrap();

        let args = make_args(
            "hello",
            "hi",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 2);
        let total: usize = replacements.iter().map(|r| r.match_count).sum();
        assert_eq!(total, 2);
    }

    #[test]
    fn if_exists_still_replaces_when_found() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        let args = ReplaceArgs {
            old: "hello".to_string(),
            new: Some("hi".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: true,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_default();
        global.apply = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let content = fs::read_to_string(&file).unwrap();
        assert_eq!(content, "hi world\n");
    }

    #[test]
    fn write_policy_ensure_final_newline_applied() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world").unwrap();

        let args = make_args(
            "hello",
            "hi",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let mut global = GlobalFlags::test_default();
        global.apply = true;
        global.ensure_final_newline = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let content = fs::read_to_string(&file).unwrap();
        assert_eq!(content, "hi world\n");
    }

    #[test]
    fn multiline_regex_spans_newlines() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "start\nmiddle\nend\n").unwrap();

        let args = ReplaceArgs {
            old: r"start.*end".to_string(),
            new: Some("replaced".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: false,
            regex: true,
            if_exists: false,
            multiline: true,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(replacements[0].match_count, 1);
        assert_eq!(replacements[0].replaced, "replaced\n");
    }

    #[test]
    fn check_mode_returns_changes_detected() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        let args = make_args(
            "hello",
            "hi",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let mut global = GlobalFlags::test_default();
        global.check = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);

        // File must not be modified in check mode.
        let content = fs::read_to_string(&file).unwrap();
        assert_eq!(content, "hello world\n");
    }

    #[test]
    fn whole_line_deletes_matching_lines() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.rs");
        fs::write(
            &file,
            "fn main() {\n    let _x = foo();\n    let y = bar();\n    let _z = baz();\n}\n",
        )
        .unwrap();

        let args = ReplaceArgs {
            old: "let _".to_string(),
            new: Some(String::new()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: true,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(replacements[0].match_count, 2);
        assert_eq!(
            replacements[0].replaced,
            "fn main() {\n    let y = bar();\n}\n"
        );
    }

    #[test]
    fn whole_line_regex_deletes_matching_lines() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.rs");
        fs::write(
            &file,
            "use std::io;\nuse std::fmt;\nuse crate::foo;\nuse crate::bar;\n",
        )
        .unwrap();

        let args = ReplaceArgs {
            old: r"use crate::".to_string(),
            new: Some(String::new()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: false,
            regex: true,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: true,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(replacements[0].match_count, 2);
        assert_eq!(replacements[0].replaced, "use std::io;\nuse std::fmt;\n");
    }

    #[test]
    fn whole_line_replaces_entire_line() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "alpha\nbeta match\ngamma\n").unwrap();

        let args = ReplaceArgs {
            old: "match".to_string(),
            new: Some("replaced line".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: true,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(replacements[0].replaced, "alpha\nreplaced line\ngamma\n");
    }

    #[test]
    fn whole_line_with_range_restricts_matches() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "aaa\nbbb\nccc\nbbb\neee\n").unwrap();

        let args = ReplaceArgs {
            old: "bbb".to_string(),
            new: Some(String::new()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: true,
            range: Some("1:3".to_string()),
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        // Only the bbb on line 2 should be deleted; the one on line 4 is outside range.
        assert_eq!(replacements[0].match_count, 1);
        assert_eq!(replacements[0].replaced, "aaa\nccc\nbbb\neee\n");
    }

    #[test]
    fn whole_line_nth_only_removes_nth_match() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "aaa\nbbb\nccc\nbbb\neee\n").unwrap();

        let args = ReplaceArgs {
            old: "bbb".to_string(),
            new: Some(String::new()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: Some(2),
            case_insensitive: false,
            word_boundary: false,
            whole_line: true,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(replacements[0].match_count, 1);
        // Second occurrence of bbb (line 4) is deleted.
        assert_eq!(replacements[0].replaced, "aaa\nbbb\nccc\neee\n");
    }

    #[test]
    fn word_boundary_prevents_partial_match() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.rs");
        fs::write(
            &file,
            "struct SetupFile {}\nstruct BenchSetupFile {}\nlet x: SetupFile = todo!();\n",
        )
        .unwrap();

        let args = ReplaceArgs {
            old: "SetupFile".to_string(),
            new: Some("NewFile".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: true,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(replacements[0].match_count, 2);
        assert_eq!(
            replacements[0].replaced,
            "struct NewFile {}\nstruct BenchSetupFile {}\nlet x: NewFile = todo!();\n",
            "word_boundary should rename standalone SetupFile but not inside BenchSetupFile"
        );
    }
}

mod edge_cases {
    use super::*;

    #[test]
    fn if_exists_returns_success_on_no_matches() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        let args = ReplaceArgs {
            old: "zzz_no_match_zzz".to_string(),
            new: Some("replacement".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: true,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }

    /// #1194: `--if-exists --json` must emit a JSON object even when there
    /// are no matches, not zero bytes.
    #[test]
    fn if_exists_json_emits_output_on_no_matches() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        let args = ReplaceArgs {
            old: "zzz_no_match_zzz".to_string(),
            new: Some("replacement".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: true,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let global = GlobalFlags {
            json: true,
            ..GlobalFlags::test_default()
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);
        // The JSON output is written to stdout via global.emit_json(),
        // which we trust here. The key assertion is that the code path
        // reaches emit_json (previously it returned before emitting).
    }

    #[test]
    fn binary_files_are_skipped() {
        let dir = TempDir::new().unwrap();
        let bin_file = dir.path().join("data.bin");
        // Write a file with NUL bytes (binary content).
        fs::write(&bin_file, b"hello\x00world").unwrap();

        let args = make_args(
            "hello",
            "replaced",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();
        assert!(
            replacements.is_empty(),
            "binary files should be skipped, got {} matches",
            replacements.len()
        );
    }

    #[test]
    fn multiline_false_does_not_span_newlines() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "start\nmiddle\nend\n").unwrap();

        let args = ReplaceArgs {
            old: r"start.*end".to_string(),
            new: Some("replaced".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: false,
            regex: true,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert!(
            replacements.is_empty(),
            "without multiline, dot should not match newlines"
        );
    }

    #[test]
    fn identity_replacement_treated_as_no_match() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        // Replacing "hello" with "hello" should produce no change.
        let args = make_args(
            "hello",
            "hello",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();
        assert!(
            replacements.is_empty(),
            "identity replacement must be filtered out"
        );
    }

    #[test]
    fn identity_replacement_check_returns_no_matches() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        let args = make_args(
            "hello",
            "hello",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let mut global = GlobalFlags::test_default();
        global.check = true;

        let code = run(args, &global).unwrap();
        assert_eq!(
            code,
            exit::NO_MATCHES,
            "--check with identity replacement must not report changes"
        );
    }

    #[test]
    fn word_boundary_with_metacharacters() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.rs");
        fs::write(&file, "type A = Option<SetupFile>;\n").unwrap();

        let args = ReplaceArgs {
            old: "SetupFile".to_string(),
            new: Some("NewFile".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: true,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        assert_eq!(
            replacements[0].replaced, "type A = Option<NewFile>;\n",
            "word_boundary should match at angle bracket boundaries"
        );
    }

    #[test]
    fn word_boundary_does_not_match_in_string() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.rs");
        // In a string, SetupFile is still at word boundaries (quotes are non-word chars)
        // so word_boundary alone won't skip strings -- that needs AST (#647).
        // But it WILL prevent matching inside compound identifiers.
        fs::write(
            &file,
            "let name = \"SetupFile\";\nlet x: SetupFileConfig = todo!();\n",
        )
        .unwrap();

        let args = ReplaceArgs {
            old: "SetupFile".to_string(),
            new: Some("NewFile".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: true,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &GlobalFlags::test_default()).unwrap();

        assert_eq!(replacements.len(), 1);
        // SetupFile in the string IS matched (word boundaries don't know about strings)
        // SetupFileConfig is NOT matched (no word boundary between SetupFile and Config)
        assert_eq!(
            replacements[0].replaced,
            "let name = \"NewFile\";\nlet x: SetupFileConfig = todo!();\n",
        );
    }
}

mod error_handling {
    use super::*;

    #[test]
    fn no_matches_returns_exit_3() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        let args = make_args(
            "zzz_no_match_zzz",
            "replacement",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let code = run(args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[test]
    fn nth_zero_is_rejected() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world\n").unwrap();

        let args = ReplaceArgs {
            old: "hello".to_string(),
            new: Some("hi".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: Some(0),
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: None,
            write: Default::default(),
        };
        let err = run(args, &GlobalFlags::test_default()).unwrap_err();
        assert!(err.to_string().contains("1-based"), "{err}");
    }

    #[test]
    fn range_requires_whole_line() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello\n").unwrap();

        let args = ReplaceArgs {
            old: "hello".to_string(),
            new: Some("hi".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: true,
            regex: false,
            if_exists: false,
            multiline: false,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: false,
            range: Some("1:5".to_string()),
            write: Default::default(),
        };
        let err = run(args, &GlobalFlags::test_default()).unwrap_err();
        assert!(
            err.to_string().contains("range requires whole_line"),
            "{err}"
        );
    }

    #[test]
    fn whole_line_and_multiline_conflict() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello\n").unwrap();

        let args = ReplaceArgs {
            old: "hello".to_string(),
            new: Some("hi".to_string()),
            insert_before: None,
            insert_after: None,
            paths: vec![dir.path().to_string_lossy().into_owned()],
            literal: false,
            regex: true,
            if_exists: false,
            multiline: true,
            nth: None,
            case_insensitive: false,
            word_boundary: false,
            whole_line: true,
            range: None,
            write: Default::default(),
        };
        let err = run(args, &GlobalFlags::test_default()).unwrap_err();
        assert!(
            err.to_string()
                .contains("whole_line and multiline cannot be combined"),
            "{err}"
        );
    }
}