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
use crate::cli::global::GlobalFlags;
use crate::diff::{self, DiffResult, unified_diff};
use crate::exit;
use crate::ops::replace::{
    ReplaceModeError, compile_replace_regex, replace_content, replacement_text,
    validate_replace_mode,
};
use crate::write::policy_from_flags;
use clap::Args;
use serde::Serialize;
use std::path::Path;

#[derive(Debug, Args)]
#[command(after_help = "\
EXAMPLES:
  patchloom replace 'old_name' --to 'new_name' src/
  patchloom replace 'http://' --to 'https://' src/ --apply
  patchloom replace 'v1\\.0' --to 'v2.0' --regex README.md")]
pub struct ReplaceArgs {
    /// Pattern to find.
    pub from: String,
    /// Text to replace with.
    #[arg(long)]
    pub to: Option<String>,
    // ref:replace-mode:insert-before
    /// Insert text before each match instead of replacing.
    #[arg(long, conflicts_with = "insert_after")]
    pub insert_before: Option<String>,
    // ref:replace-mode:insert-after
    /// Insert text after each match instead of replacing.
    #[arg(long, conflicts_with = "insert_before")]
    pub insert_after: Option<String>,
    /// Paths to operate on.
    pub paths: Vec<String>,
    /// Treat pattern as a literal string (default).
    #[arg(long, short = 'F')]
    pub literal: bool,
    // ref:replace-mode:regex
    /// Treat pattern as a regex.
    #[arg(long)]
    pub regex: bool,
    // ref:replace-mode:if-exists
    /// Return success even if no matches found (idempotent mode).
    #[arg(long)]
    pub if_exists: bool,
    // ref:replace-mode:multiline
    /// Enable multiline matching (dot matches newlines in regex mode).
    #[arg(long, short = 'U')]
    pub multiline: bool,
    // ref:replace-mode:nth
    /// Replace only the Nth occurrence (1-based).
    #[arg(long)]
    pub nth: Option<usize>,
    // ref:replace-mode:case-insensitive
    /// Case-insensitive matching.
    #[arg(long, short = 'i')]
    pub case_insensitive: bool,
    #[command(flatten)]
    pub write: crate::cli::global::WriteFlags,
}

#[derive(Debug, Clone, Serialize)]
struct ReplaceFileResult {
    path: String,
    match_count: usize,
}

#[derive(Debug, Serialize)]
struct ReplaceOutput {
    ok: bool,
    match_count: usize,
    file_count: usize,
    files: Vec<ReplaceFileResult>,
    #[serde(skip_serializing_if = "Option::is_none")]
    diff: Option<String>,
}

/// Result of processing a single file.
struct FileReplacement {
    path: String,
    /// Relative path for display in diffs and JSON output.
    display_path: String,
    original: String,
    replaced: String,
    match_count: usize,
}

/// Build policy+write tuples and write atomically with backup.
fn apply_replacements(
    replacements: &[FileReplacement],
    global: &GlobalFlags,
    cwd: &Path,
) -> anyhow::Result<()> {
    let policies: Vec<_> = replacements
        .iter()
        .map(|r| policy_from_flags(global, Some(Path::new(&r.path))))
        .collect();
    let writes: Vec<_> = replacements
        .iter()
        .zip(&policies)
        .map(|(r, p)| (Path::new(r.path.as_str()), r.replaced.as_str(), p))
        .collect();
    crate::backup::backup_write_files(cwd, &writes)
}

fn build_replacement(args: &ReplaceArgs) -> String {
    replacement_text(
        &args.from,
        &args.to,
        &args.insert_before,
        &args.insert_after,
        args.regex || args.case_insensitive,
    )
}

/// Walk files and collect all replacements using parallel file processing.
fn collect_replacements(
    args: &ReplaceArgs,
    global: &GlobalFlags,
) -> anyhow::Result<Vec<FileReplacement>> {
    let cwd = global.resolve_cwd()?;
    let glob_matcher = crate::build_glob_matcher(global)?;
    let file_paths = crate::collect_file_paths_opts(&args.paths, global, false, Some(&cwd))?;
    let glob_roots = crate::collect_glob_roots(&args.paths, global, Some(&cwd))?;
    let replacement = build_replacement(args);
    let quiet = global.quiet;

    let compiled_re = compile_replace_regex(
        &args.from,
        args.regex,
        args.case_insensitive,
        args.multiline,
    )?;

    let from = &args.from;
    let nth = args.nth;

    let cwd_ref = &cwd;
    let mut replacements: Vec<FileReplacement> =
        crate::par_process_files(&file_paths, glob_matcher.as_ref(), &glob_roots, |path| {
            let content = crate::read_text_file(path, "replace", quiet)?;
            let (replaced, count) =
                replace_content(&content, from, &replacement, compiled_re.as_ref(), nth);
            if count > 0 {
                let replaced = replaced.into_owned();
                let display_path = crate::files::relative_display(path, cwd_ref)
                    .to_string_lossy()
                    .into_owned();
                Some(FileReplacement {
                    path: path.to_string_lossy().into_owned(),
                    display_path,
                    original: content,
                    replaced,
                    match_count: count,
                })
            } else {
                None
            }
        });

    // Drop files where the replacement produces identical content (e.g.
    // replacing "X" with "X").  The match count was non-zero, but there is
    // no actual change to write, diff, or report.
    replacements.retain(|r| r.original != r.replaced);

    replacements.sort_unstable_by(|a, b| a.path.cmp(&b.path));
    Ok(replacements)
}

fn make_file_results(replacements: &[FileReplacement]) -> Vec<ReplaceFileResult> {
    replacements
        .iter()
        .map(|r| ReplaceFileResult {
            path: r.display_path.clone(),
            match_count: r.match_count,
        })
        .collect()
}

fn make_diff_output(replacements: &[FileReplacement], color: bool) -> String {
    let diffs: Vec<_> = replacements
        .iter()
        .map(|r| unified_diff(&r.display_path, &r.original, &r.replaced))
        .collect();
    let total_files_changed = diffs.iter().filter(|d| d.has_changes).count();
    let diff_result = DiffResult {
        diffs,
        total_files_changed,
    };
    diff::format_diff_result_colored(&diff_result, color)
}

pub fn run(args: ReplaceArgs, global: &GlobalFlags) -> anyhow::Result<u8> {
    if args.from.is_empty() {
        anyhow::bail!("--from must not be empty");
    }
    if args.nth == Some(0) {
        anyhow::bail!("--nth is 1-based; use --nth 1 for the first occurrence");
    }

    match validate_replace_mode(
        args.to.is_some(),
        args.insert_before.is_some(),
        args.insert_after.is_some(),
    ) {
        Ok(()) => {}
        Err(ReplaceModeError::MissingMode) => {
            anyhow::bail!("one of --to, --insert-before, or --insert-after must be provided")
        }
        Err(ReplaceModeError::BothInsertModes) => {
            anyhow::bail!("--insert-before and --insert-after cannot be combined")
        }
        Err(ReplaceModeError::ToWithInsert) => {
            anyhow::bail!("--to cannot be combined with --insert-before or --insert-after")
        }
    }

    let cwd = global.resolve_cwd()?;
    let replacements = collect_replacements(&args, global)?;

    if replacements.is_empty() {
        if args.if_exists {
            return Ok(exit::SUCCESS);
        }
        if global.json {
            let output = ReplaceOutput {
                ok: true,
                match_count: 0,
                file_count: 0,
                files: vec![],
                diff: None,
            };
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
        if global.show_status() {
            let path_desc = if args.paths.is_empty() {
                ".".to_string()
            } else {
                args.paths.join(", ")
            };
            eprintln!("no matches for '{}' in {path_desc}", args.from);
            if !args.regex && crate::files::has_regex_metacharacters(&args.from) {
                eprintln!("hint: pattern contains regex characters, try --regex");
            }
            if !args.case_insensitive {
                eprintln!("hint: try -i for case-insensitive matching");
            }
        }
        return Ok(exit::NO_MATCHES);
    }

    let total_matches: usize = replacements.iter().map(|r| r.match_count).sum();
    let file_count = replacements.len();
    let files = make_file_results(&replacements);

    // --check mode: report summary, exit 2 if changes needed.
    if global.check {
        if global.json {
            let output = ReplaceOutput {
                ok: true,
                match_count: total_matches,
                file_count,
                files,
                diff: None,
            };
            println!("{}", serde_json::to_string_pretty(&output)?);
        } else if global.jsonl {
            for f in &files {
                println!("{}", serde_json::to_string(f)?);
            }
        } else if !global.quiet {
            println!("{total_matches} match(es) in {file_count} file(s)");
            for f in &files {
                println!("  {}: {} match(es)", f.path, f.match_count);
            }
        }
        return Ok(exit::CHANGES_DETECTED);
    }

    // --apply mode: write changes using atomic_write with write policy.
    if global.apply {
        apply_replacements(&replacements, global, &cwd)?;

        let color = global.should_color();
        if global.json {
            let diff_text = if global.diff {
                Some(make_diff_output(&replacements, false))
            } else {
                None
            };
            let output = ReplaceOutput {
                ok: true,
                match_count: total_matches,
                file_count,
                files,
                diff: diff_text,
            };
            println!("{}", serde_json::to_string_pretty(&output)?);
        } else if global.jsonl {
            for f in &files {
                println!("{}", serde_json::to_string(f)?);
            }
        } else if global.diff {
            print!("{}", make_diff_output(&replacements, color));
        } else if !global.quiet {
            println!("replaced {total_matches} match(es) in {file_count} file(s)");
            for f in &files {
                println!("  {}: {} match(es)", f.path, f.match_count);
            }
        }
        return Ok(exit::SUCCESS);
    }

    // Default / --diff mode: show unified diff of changes.
    let color = global.should_color();
    if global.json {
        let output = ReplaceOutput {
            ok: true,
            match_count: total_matches,
            file_count,
            files,
            diff: Some(make_diff_output(&replacements, false)),
        };
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else if global.jsonl {
        for f in &files {
            println!("{}", serde_json::to_string(f)?);
        }
    } else {
        print!("{}", make_diff_output(&replacements, color));
    }
    if global.show_status() {
        eprintln!("{file_count} file(s) changed, {total_matches} replacement(s)");
    }

    // --confirm: prompt after showing diff, then apply if confirmed.
    if global.should_apply() {
        apply_replacements(&replacements, global, &cwd)?;
        if global.show_status() {
            eprintln!("replaced {total_matches} match(es) in {file_count} file(s)");
        }
    }

    Ok(exit::SUCCESS)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn default_global() -> GlobalFlags {
        GlobalFlags::default()
    }

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

    #[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, &default_global()).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 {
            from: r"foo\d+".to_string(),
            to: 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,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &default_global()).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 {
            from: r#"version = "(\d+)\.(\d+)\.(\d+)""#.to_string(),
            to: 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,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &default_global()).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 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, &default_global()).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[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, &default_global()).unwrap();
        let diff_output = make_diff_output(&replacements, false);

        assert!(diff_output.contains("--- a/"));
        assert!(diff_output.contains("+++ b/"));
        assert!(diff_output.contains("-old line"));
        assert!(diff_output.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 = default_global();
        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, &default_global()).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_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 {
            from: "zzz_no_match_zzz".to_string(),
            to: 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,
            write: Default::default(),
        };
        let code = run(args, &default_global()).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }

    #[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 {
            from: "hello".to_string(),
            to: 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,
            write: Default::default(),
        };
        let mut global = default_global();
        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 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, &default_global()).unwrap();
        assert!(
            replacements.is_empty(),
            "binary files should be skipped, got {} matches",
            replacements.len()
        );
    }

    #[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 = default_global();
        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 {
            from: r"start.*end".to_string(),
            to: 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,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &default_global()).unwrap();

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

    #[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 {
            from: r"start.*end".to_string(),
            to: 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,
            write: Default::default(),
        };
        let replacements = collect_replacements(&args, &default_global()).unwrap();

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

    #[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 = default_global();
        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 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, &default_global()).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 = default_global();
        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 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 {
            from: "hello".to_string(),
            to: 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,
            write: Default::default(),
        };
        let err = run(args, &default_global()).unwrap_err();
        assert!(err.to_string().contains("1-based"), "{err}");
    }
}