targeted-mutation 0.22.1

Targeted mutation testing for Rust: find the wrong implementations your tests let through
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
//! Deep-dive inspection (`cargo tmt explain`) and safe Rust test stub generation
//! (`--emit-todos`).

use std::fs::{self, OpenOptions};
use std::io::{self, IsTerminal as _, Read as _, Write as _};
use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result, bail};
use serde_json::Value;

use crate::report::{self, Finding, Report};

/// Upper bound when reading a JSON/JSONL report into `explain` (16 MiB).
const MAX_EXPLAIN_BYTES: u64 = 16 * 1024 * 1024;

/// A finding extracted from a single-package JSON, workspace JSON, or JSONL report.
#[derive(Clone, Debug, PartialEq)]
pub struct ExplainedFinding {
    pub package: Arc<str>,
    pub raw: Value,
}

impl ExplainedFinding {
    pub fn id(&self) -> &str {
        self.raw.get("id").and_then(Value::as_str).unwrap_or("")
    }

    pub fn kind(&self) -> &str {
        self.raw.get("kind").and_then(Value::as_str).unwrap_or("")
    }

    pub fn file(&self) -> &str {
        self.raw.get("file").and_then(Value::as_str).unwrap_or("")
    }

    pub fn line(&self) -> usize {
        self.raw.get("line").and_then(Value::as_u64).unwrap_or(0) as usize
    }

    pub fn column(&self) -> usize {
        self.raw.get("column").and_then(Value::as_u64).unwrap_or(0) as usize
    }

    pub fn site(&self) -> String {
        format!("{}:{}:{}", self.file(), self.line(), self.column())
    }

    pub fn line_site(&self) -> String {
        format!("{}:{}", self.file(), self.line())
    }

    pub fn item(&self) -> &str {
        self.raw.get("item").and_then(Value::as_str).unwrap_or("")
    }

    pub fn code(&self) -> &str {
        self.raw.get("code").and_then(Value::as_str).unwrap_or("")
    }

    /// Copy-pasteable `// tmt:ignore[...]` directive for this finding.
    pub fn ignore_comment(&self) -> String {
        if let Some(comment) = self
            .raw
            .get("likely_equivalent")
            .and_then(|v| v.get("ignore_comment"))
            .and_then(Value::as_str)
            && !comment.is_empty()
        {
            return comment.to_string();
        }
        let kind = match self.kind() {
            k @ ("input_gap" | "assertion_gap" | "survivor") => k,
            _ => "survivor",
        };
        let col = self.column();
        if col > 0 {
            format!("// tmt:ignore[{kind}@{col}] <reason>")
        } else {
            format!("// tmt:ignore[{kind}] <reason>")
        }
    }
}

/// Reads report JSON/JSONL from `from` or from piped stdin (rejecting TTY stdin,
/// symlinks/non-regular files without TOCTOU, and inputs larger than 16 MiB).
pub fn read_report_input(from: Option<&Path>) -> Result<String> {
    if let Some(path) = from {
        let mut options = OpenOptions::new();
        options.read(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt as _;

            #[cfg(any(
                target_os = "macos",
                target_os = "ios",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "openbsd",
                target_os = "dragonfly"
            ))]
            const O_NONBLOCK: i32 = 0x0004;
            #[cfg(any(
                target_os = "macos",
                target_os = "ios",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "openbsd",
                target_os = "dragonfly"
            ))]
            const O_NOFOLLOW: i32 = 0x0100;

            #[cfg(all(
                target_os = "linux",
                any(target_arch = "x86_64", target_arch = "x86", target_arch = "riscv64")
            ))]
            const O_NONBLOCK: i32 = 0o4000;
            #[cfg(all(
                target_os = "linux",
                any(target_arch = "x86_64", target_arch = "x86", target_arch = "riscv64")
            ))]
            const O_NOFOLLOW: i32 = 0o400000;

            #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
            const O_NONBLOCK: i32 = 0o4000;
            #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
            const O_NOFOLLOW: i32 = 0o100000;

            #[cfg(not(any(
                target_os = "macos",
                target_os = "ios",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "openbsd",
                target_os = "dragonfly",
                all(
                    target_os = "linux",
                    any(
                        target_arch = "x86_64",
                        target_arch = "x86",
                        target_arch = "aarch64",
                        target_arch = "riscv64"
                    )
                )
            )))]
            const O_NONBLOCK: i32 = 0;
            #[cfg(not(any(
                target_os = "macos",
                target_os = "ios",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "openbsd",
                target_os = "dragonfly",
                all(
                    target_os = "linux",
                    any(
                        target_arch = "x86_64",
                        target_arch = "x86",
                        target_arch = "aarch64",
                        target_arch = "riscv64"
                    )
                )
            )))]
            const O_NOFOLLOW: i32 = 0;

            let flags = O_NONBLOCK | O_NOFOLLOW;
            if flags != 0 {
                options.custom_flags(flags);
            } else {
                let meta = fs::symlink_metadata(path)
                    .with_context(|| format!("inspecting {}", path.display()))?;
                if !meta.is_file() {
                    bail!("{} is not a regular file", path.display());
                }
            }
        }
        #[cfg(not(unix))]
        {
            let meta = fs::symlink_metadata(path)
                .with_context(|| format!("inspecting {}", path.display()))?;
            if !meta.is_file() {
                bail!("{} is not a regular file", path.display());
            }
        }
        let file = options
            .open(path)
            .with_context(|| format!("reading {}", path.display()))?;
        let meta = file
            .metadata()
            .with_context(|| format!("inspecting {}", path.display()))?;
        if !meta.is_file() {
            bail!("{} is not a regular file", path.display());
        }
        read_bounded(file, &path.display().to_string())
    } else {
        let stdin = io::stdin();
        if stdin.is_terminal() {
            bail!(
                "no input file given and stdin is a terminal; pass --from FILE or pipe `cargo tmt --json`"
            );
        }
        read_bounded(stdin.lock(), "stdin")
    }
}

fn read_bounded<R: io::Read>(reader: R, label: &str) -> Result<String> {
    let mut text = String::new();
    reader
        .take(MAX_EXPLAIN_BYTES + 1)
        .read_to_string(&mut text)
        .with_context(|| format!("reading {label}"))?;
    let text_len = text.len() as u64;
    if text_len > MAX_EXPLAIN_BYTES {
        bail!("{label} exceeds maximum report size of {MAX_EXPLAIN_BYTES} bytes");
    }
    Ok(text)
}

fn collect_findings_from_report_value(mut val: Value, out: &mut Vec<ExplainedFinding>) {
    let Some(obj) = val.as_object_mut() else {
        return;
    };
    if let Some(Value::Array(packages)) = obj.remove("packages") {
        for pkg in packages {
            collect_findings_from_report_value(pkg, out);
        }
        return;
    }
    if let Some(mut inner) = obj.remove("report") {
        let fallback_pkg = obj
            .get("package")
            .and_then(Value::as_str)
            .unwrap_or_default();
        if let Some(inner_obj) = inner.as_object_mut() {
            let pkg: Arc<str> = Arc::from(
                inner_obj
                    .get("package")
                    .and_then(Value::as_str)
                    .unwrap_or(fallback_pkg),
            );
            if let Some(Value::Array(findings)) = inner_obj.remove("findings") {
                for f in findings {
                    out.push(ExplainedFinding {
                        package: Arc::clone(&pkg),
                        raw: f,
                    });
                }
            }
        }
        return;
    }
    let pkg: Arc<str> = Arc::from(
        obj.get("package")
            .and_then(Value::as_str)
            .unwrap_or_default(),
    );
    if let Some(Value::Array(findings)) = obj.remove("findings") {
        for f in findings {
            out.push(ExplainedFinding {
                package: Arc::clone(&pkg),
                raw: f,
            });
        }
    }
}

/// Parses single-package JSON, workspace JSON, or JSONL into a flat list of findings.
pub fn parse_findings(text: &str) -> Result<Vec<ExplainedFinding>> {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        bail!("report input is empty");
    }
    if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
        let mut out = Vec::new();
        collect_findings_from_report_value(value, &mut out);
        return Ok(out);
    }
    // Fall back to JSONL (one JSON object per non-empty line).
    let mut out = Vec::new();
    for (idx, line) in trimmed.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let value: Value = serde_json::from_str(line)
            .with_context(|| format!("invalid JSON on line {}", idx + 1))?;
        collect_findings_from_report_value(value, &mut out);
    }
    Ok(out)
}

fn distinct_finding_key(f: &ExplainedFinding) -> (&str, Option<&str>, &str, usize, usize) {
    let id = f.id();
    if id.is_empty() {
        (f.package.as_ref(), None, f.kind(), f.line(), f.column())
    } else {
        (f.package.as_ref(), Some(id), "", 0, 0)
    }
}

/// Resolves `query` against `findings` with strict precedence:
/// 1. Exact `finding.id` match (returns all findings sharing that ID, e.g. multi-variant rounding/clamp sites)
/// 2. Exact `file:line:column` site match (ambiguous if multiple distinct findings share the site)
/// 3. Exact `file:line` match (ambiguous if multiple distinct findings share the line)
/// 4. Unique `finding.id` prefix match (ambiguous if multiple distinct findings match)
pub fn resolve_findings<'a>(
    findings: &'a [ExplainedFinding],
    query: &str,
) -> Result<Vec<&'a ExplainedFinding>> {
    let query = query.trim();
    if query.is_empty() {
        bail!("finding id or site must not be empty");
    }

    let exact_id: Vec<&ExplainedFinding> = findings.iter().filter(|f| f.id() == query).collect();
    if !exact_id.is_empty() {
        return Ok(exact_id);
    }

    let exact_site: Vec<&ExplainedFinding> =
        findings.iter().filter(|f| f.site() == query).collect();
    if !exact_site.is_empty() {
        let distinct_keys: std::collections::BTreeSet<_> =
            exact_site.iter().map(|f| distinct_finding_key(f)).collect();
        if distinct_keys.len() == 1 {
            return Ok(exact_site);
        }
        return Err(ambiguous_error(query, &exact_site));
    }

    let exact_line: Vec<&ExplainedFinding> =
        findings.iter().filter(|f| f.line_site() == query).collect();
    if !exact_line.is_empty() {
        let distinct_keys: std::collections::BTreeSet<_> =
            exact_line.iter().map(|f| distinct_finding_key(f)).collect();
        if distinct_keys.len() == 1 {
            return Ok(exact_line);
        }
        return Err(ambiguous_error(query, &exact_line));
    }

    let prefix_id: Vec<&ExplainedFinding> = findings
        .iter()
        .filter(|f| !f.id().is_empty() && f.id().starts_with(query))
        .collect();
    if !prefix_id.is_empty() {
        let distinct_keys: std::collections::BTreeSet<_> =
            prefix_id.iter().map(|f| distinct_finding_key(f)).collect();
        if distinct_keys.len() == 1 {
            return Ok(prefix_id);
        }
        return Err(ambiguous_error(query, &prefix_id));
    }

    bail!(
        "no finding matching `{}` ({} finding(s) in report)",
        report::sanitize_inline(query),
        findings.len()
    )
}

/// Convenience wrapper returning a single resolved finding (first when multiple findings
/// share the same ID).
pub fn resolve_finding<'a>(
    findings: &'a [ExplainedFinding],
    query: &str,
) -> Result<&'a ExplainedFinding> {
    resolve_findings(findings, query).map(|mut list| list.remove(0))
}

fn ambiguous_error(query: &str, matches: &[&ExplainedFinding]) -> anyhow::Error {
    let mut msg = format!(
        "ambiguous selector `{}` matched {} findings:\n",
        report::sanitize_inline(query),
        matches.len()
    );
    for item in matches.iter().take(10) {
        let pkg = if item.package.is_empty() {
            String::new()
        } else {
            format!("[{}] ", report::sanitize_inline(&item.package))
        };
        msg.push_str(&format!(
            "  - {pkg}{} [{}]  {}\n",
            report::sanitize_inline(&item.site()),
            report::sanitize_inline(item.kind()),
            report::sanitize_inline(item.id())
        ));
    }
    if matches.len() > 10 {
        msg.push_str(&format!("  ... and {} more\n", matches.len() - 10));
    }
    anyhow::anyhow!(msg.trim_end().to_string())
}

/// Renders a human-readable deep-dive explanation for a single finding.
pub fn render_explanation_text(finding: &ExplainedFinding) -> String {
    let mut out = String::new();
    let kind_label = match finding.kind() {
        "input_gap" => "INPUT GAP",
        "assertion_gap" => "ASSERTION GAP",
        "survivor" if finding.raw.get("change_since").is_some() => "UNTESTED CHANGE",
        "survivor" => "SURVIVOR",
        other => other,
    };
    out.push_str(&format!(
        "{}  {}\n",
        report::sanitize_inline(kind_label),
        report::sanitize_inline(&finding.site())
    ));
    if !finding.package.is_empty() {
        out.push_str(&format!(
            "  package: {}\n",
            report::sanitize_inline(&finding.package)
        ));
    }
    if !finding.id().is_empty() {
        out.push_str(&format!(
            "  id:      {}\n",
            report::sanitize_inline(finding.id())
        ));
    }
    if !finding.item().is_empty() {
        out.push_str(&format!(
            "  item:    {}\n",
            report::sanitize_inline(finding.item())
        ));
    }
    out.push_str(&format!(
        "  code:    {}\n",
        report::sanitize_inline(finding.code())
    ));

    if let Some(survivors) = finding.raw.get("survivors").and_then(Value::as_array) {
        let list: Vec<String> = survivors
            .iter()
            .filter_map(Value::as_str)
            .map(report::sanitize_inline)
            .collect();
        let total = finding
            .raw
            .get("survivor_count")
            .and_then(|v| v.as_u64().map(u128::from))
            .unwrap_or(list.len() as u128)
            .max(list.len() as u128);
        if !list.is_empty() {
            if total > list.len() as u128 {
                let more = total - list.len() as u128;
                out.push_str(&format!(
                    "  survivors ({total} total, showing {}):\n",
                    list.len()
                ));
                for s in list {
                    out.push_str(&format!("    - {s}\n"));
                }
                out.push_str(&format!("    - (+{more} more)\n"));
            } else {
                out.push_str(&format!("  survivors ({total}):\n"));
                for s in list {
                    out.push_str(&format!("    - {s}\n"));
                }
            }
        }
    }
    if let Some(observed) = finding.raw.get("observed").and_then(Value::as_str) {
        out.push_str(&format!(
            "  observed: {}\n",
            report::sanitize_inline(observed)
        ));
    }
    let has_likely_eq = finding
        .raw
        .get("likely_equivalent")
        .and_then(Value::as_object)
        .is_some();
    if !has_likely_eq
        && let Some(add_tests) = finding.raw.get("add_tests").and_then(Value::as_array)
    {
        for item in add_tests.iter().filter_map(Value::as_str) {
            out.push_str(&format!("  add test: {}\n", report::sanitize_inline(item)));
        }
    }
    if let Some(tests) = finding.raw.get("tests").and_then(Value::as_array) {
        let names: Vec<String> = tests
            .iter()
            .filter_map(Value::as_str)
            .map(report::sanitize_inline)
            .collect();
        if !names.is_empty() {
            out.push_str(&format!("  reaching tests: {}\n", names.join(", ")));
        }
    }
    if let Some(effects) = finding.raw.get("effects").and_then(Value::as_array) {
        for effect in effects.iter().filter_map(Value::as_str) {
            out.push_str(&format!("  effect:  {}\n", report::sanitize_inline(effect)));
        }
    }
    if let Some(advice) = finding.raw.get("advice").and_then(Value::as_str) {
        out.push_str(&format!("  advice:  {}\n", report::sanitize_inline(advice)));
    }
    if let Some(witness) = finding.raw.get("witness").and_then(Value::as_object) {
        let call = witness.get("call").and_then(Value::as_str).unwrap_or("");
        let orig = witness
            .get("original")
            .and_then(Value::as_str)
            .unwrap_or("");
        let mutant = witness.get("mutant").and_then(Value::as_str).unwrap_or("");
        let assertion = witness
            .get("assertion")
            .and_then(Value::as_str)
            .unwrap_or("");
        out.push_str(&format!(
            "  witness: `{}` (original: {}, mutant: {})\n",
            report::sanitize_inline(call),
            report::sanitize_inline(orig),
            report::sanitize_inline(mutant)
        ));
        if !assertion.is_empty() {
            out.push_str(&format!(
                "  assert:  {}\n",
                report::sanitize_inline(assertion)
            ));
        }
    }
    if let Some(eq) = finding
        .raw
        .get("likely_equivalent")
        .and_then(Value::as_object)
        && let Some(reason) = eq.get("reason").and_then(Value::as_str)
    {
        out.push_str(&format!(
            "  likely equivalent: {}\n",
            report::sanitize_inline(reason)
        ));
    }
    out.push_str(&format!(
        "  suppress: {}\n",
        report::sanitize_inline(&finding.ignore_comment())
    ));
    report::sanitize_terminal(&out)
}

/// Renders a single finding explanation as JSON (augmented with `package` and `ignore_comment`).
pub fn render_explanation_json(finding: &ExplainedFinding) -> String {
    let mut obj = finding.raw.clone();
    if let Some(map) = obj.as_object_mut() {
        if !finding.package.is_empty() {
            map.insert(
                "package".to_string(),
                Value::String(finding.package.to_string()),
            );
        }
        map.insert(
            "ignore_comment".to_string(),
            Value::String(finding.ignore_comment()),
        );
    }
    serde_json::to_string_pretty(&obj).expect("finding explanation serialises")
}

/// Generates syntactically valid Rust `#[test] #[ignore]` stubs for all findings across `reports`.
/// Returns `None` when there are zero findings.
pub fn render_todo_stubs(reports: &[Report]) -> Option<String> {
    let total: usize = reports.iter().map(|r| r.findings.len()).sum();
    if total == 0 {
        return None;
    }
    let mut out = String::new();
    out.push_str("// Generated by `cargo tmt --emit-todos`.\n");
    out.push_str(
        "// Fill in each test body and remove `#[ignore = ...]` as you close each gap.\n\n",
    );
    let mut idx = 0usize;
    for rep in reports {
        for finding in &rep.findings {
            idx += 1;
            let at = finding.at();
            let stem = sanitize_ident(&at.file);
            let fn_name = format!("tmt_todo_{idx:03}_{stem}_l{}_c{}", at.line, at.column);
            let summary = format!(
                "tmt: {} at {}:{}:{}",
                finding.kind(),
                report::sanitize_inline(&at.file),
                at.line,
                at.column
            );
            out.push_str(&format!(
                "// Package: {} | Kind: {} | Location: {}:{}:{}\n",
                report::sanitize_inline(&rep.package),
                finding.kind(),
                report::sanitize_inline(&at.file),
                at.line,
                at.column,
            ));
            if !at.id.is_empty() {
                out.push_str(&format!("// ID: {}\n", report::sanitize_inline(&at.id)));
            }
            out.push_str(&format!("// Code: {}\n", report::sanitize_inline(&at.code)));
            if let Some(eq) = finding.likely_equivalent() {
                out.push_str(&format!(
                    "// Likely equivalent: {}\n// Suppress: {}\n",
                    report::sanitize_inline(&eq.reason),
                    report::sanitize_inline(&eq.ignore_comment),
                ));
            } else {
                match finding {
                    Finding::InputGap { add_tests, .. } => {
                        for hint in add_tests {
                            out.push_str(&format!(
                                "// Add test: {}\n",
                                report::sanitize_inline(hint)
                            ));
                        }
                    }
                    Finding::AssertionGap { tests, witness, .. } => {
                        if !tests.is_empty() {
                            out.push_str(&format!(
                                "// Reaching tests: {}\n",
                                tests
                                    .iter()
                                    .take(5)
                                    .map(|t| report::sanitize_inline(t))
                                    .collect::<Vec<_>>()
                                    .join(", ")
                            ));
                        }
                        if let Some(w) = witness {
                            out.push_str(&format!(
                                "// Suggested assertion: {}\n",
                                report::sanitize_inline(&w.assertion)
                            ));
                        }
                    }
                    Finding::Survivor {
                        advice, witness, ..
                    } => {
                        if let Some(w) = witness {
                            out.push_str(&format!(
                                "// Suggested assertion: {}\n",
                                report::sanitize_inline(&w.assertion)
                            ));
                        } else if let Some(a) = advice {
                            out.push_str(&format!("// Advice: {}\n", report::sanitize_inline(a)));
                        }
                    }
                }
            }
            out.push_str("#[test]\n");
            out.push_str(&format!("#[ignore = {:?}]\n", summary));
            out.push_str(&format!("fn {fn_name}() {{\n"));
            out.push_str(&format!("    todo!(\"{{}}\", {:?});\n", summary));
            out.push_str("}\n\n");
        }
    }
    Some(out)
}

/// Writes Rust `#[test] #[ignore]` stubs exclusively to a brand-new file (`O_CREAT | O_EXCL`).
///
/// - Refuses to overwrite any existing file, symlink, or directory.
/// - Skips file creation when there are zero findings, returning `Ok(0)`.
pub fn write_todo_stubs(path: &Path, reports: &[Report]) -> Result<usize> {
    let count: usize = reports.iter().map(|r| r.findings.len()).sum();
    let Some(content) = render_todo_stubs(reports) else {
        return Ok(0);
    };
    if fs::symlink_metadata(path).is_ok() {
        bail!(
            "refusing to overwrite existing path `{}` (choose a new file path for --emit-todos)",
            path.display()
        );
    }
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .with_context(|| format!("creating {}", path.display()))?;
    file.write_all(content.as_bytes())
        .with_context(|| format!("writing {}", path.display()))?;
    file.flush()
        .with_context(|| format!("flushing {}", path.display()))?;
    Ok(count)
}

fn sanitize_ident(path: &str) -> String {
    let trimmed = path.strip_suffix(".rs").unwrap_or(path);
    let mut out = String::new();
    let mut prev_underscore = false;
    for ch in trimmed.chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
            prev_underscore = false;
        } else if !prev_underscore && !out.is_empty() {
            out.push('_');
            prev_underscore = true;
        }
    }
    let trimmed = out.trim_matches('_');
    if trimmed.is_empty() {
        "file".to_string()
    } else if trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        format!("f_{trimmed}")
    } else {
        trimmed.to_string()
    }
}