dejadoc 0.3.0

Find duplicated Rust doctests across a workspace
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
//! Workspace and module-tree discovery.

use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use std::eprintln;
use std::format;
use std::path::PathBuf;

/// One compilable target to scan.
#[derive(Debug, Clone)]
pub(crate) struct Target {
    /// Crate name used as the item-path root.
    pub(crate) name: String,
    /// Absolute path of the target's source root file.
    pub(crate) src: PathBuf,
}

/// A resolved workspace root and the targets to scan.
#[derive(Debug, Clone)]
pub(crate) struct Workspace {
    /// Workspace root directory.
    pub(crate) root: PathBuf,
    /// Targets to scan, in metadata order.
    pub(crate) targets: Vec<Target>,
}

/// Resolve the workspace containing `root` and the targets to scan.
///
/// # Errors
///
/// Fails when `cargo metadata` cannot be run for `root`.
pub(crate) fn workspace(
    root: &std::path::Path,
    package: Option<&str>,
    all_targets: bool,
) -> crate::Result<Workspace> {
    let metadata = cargo_metadata::MetadataCommand::new()
        .current_dir(root)
        .no_deps()
        .exec()?;
    let mut targets = Vec::new();
    for package in metadata
        .packages
        .iter()
        .filter(|p| package.is_none_or(|want| p.name == want))
    {
        for target in &package.targets {
            if scan_target(&target.kind, all_targets) {
                targets.push(Target {
                    name: target.name.clone(),
                    src: target.src_path.clone().into(),
                });
            }
        }
    }
    Ok(Workspace {
        root: metadata.workspace_root.clone().into(),
        targets,
    })
}

/// Whether a cargo target is scanned, from its kind list.
fn scan_target(kinds: &[cargo_metadata::TargetKind], all_targets: bool) -> bool {
    use cargo_metadata::TargetKind as CargoTargetKind;

    if kinds
        .iter()
        .any(|k| matches!(k, CargoTargetKind::Lib | CargoTargetKind::ProcMacro))
    {
        return true;
    }
    all_targets
        && kinds
            .iter()
            .any(|k| matches!(k, CargoTargetKind::Bin | CargoTargetKind::Example))
}

/// Parse the target's module tree, each file with its parsed contents and
/// the module-path segments from the target root (empty for the root file).
///
/// # Errors
///
/// Fails when a module file cannot be canonicalized. Unreadable or
/// unparseable files are skipped with a warning.
pub(crate) fn module_tree(
    target: &Target,
) -> crate::Result<Vec<(PathBuf, syn::File, Vec<String>)>> {
    let mut out = Vec::new();
    let mut visited = BTreeSet::new();
    collect(&target.src, &[], true, &mut out, &mut visited)?;
    Ok(out)
}

/// `mod_rs` marks a crate root, a `mod.rs` or a `#[path]` file, whose children sit
/// beside it, every other file keeps them under a directory named after it.
fn collect(
    file: &std::path::Path,
    prefix: &[String],
    mod_rs: bool,
    out: &mut Vec<(PathBuf, syn::File, Vec<String>)>,
    visited: &mut BTreeSet<PathBuf>,
) -> crate::Result<()> {
    let canonical = std::fs::canonicalize(file)?;
    if !visited.insert(canonical) {
        return Ok(());
    }
    let text = match std::fs::read_to_string(file) {
        Ok(text) => text,
        Err(err) => {
            eprintln!("dejadoc: cannot read {}: {err}", file.display());
            return Ok(());
        }
    };
    let parsed = match syn::parse_file(&text) {
        Ok(parsed) => parsed,
        Err(err) => {
            eprintln!("dejadoc: cannot parse {}: {err}", file.display());
            return Ok(());
        }
    };
    let dir = file.parent().unwrap_or_else(|| std::path::Path::new("."));
    let base = match file.file_stem() {
        Some(stem) if !mod_rs => dir.join(stem),
        _ => dir.to_path_buf(),
    };
    let mut children = Vec::new();
    mod_decls(&parsed.items, dir, &base, prefix, &mut children);
    out.push((file.to_path_buf(), parsed, prefix.to_vec()));
    for (child, sub, mod_rs) in children {
        collect(&child, &sub, mod_rs, out, visited)?;
    }
    Ok(())
}

/// The `mod name;` files at every nesting depth whose `cfg` holds, each with its module
/// path. `dir` is for explicit `#[path]`, `base` for implicit children, an inline module
/// adds its name to both and to the path.
fn mod_decls(
    items: &[syn::Item],
    dir: &std::path::Path,
    base: &std::path::Path,
    prefix: &[String],
    out: &mut Vec<(PathBuf, Vec<String>, bool)>,
) {
    use syn::Item;

    for item in items {
        let Item::Mod(moditem) = item else {
            continue;
        };
        if !crate::cfg::allows(&moditem.attrs) {
            continue;
        }
        // Raw identifiers keep their name in the module path.
        let name = moditem
            .ident
            .to_string()
            .trim_start_matches("r#")
            .to_string();
        let mut segments = prefix.to_vec();
        segments.push(name);
        let name = segments.last().unwrap();
        if let Some((_, children)) = &moditem.content {
            let inner = base.join(name);
            mod_decls(children, &inner, &inner, &segments, out);
            continue;
        }
        match resolve_mod_path(dir, base, name, &moditem.attrs) {
            Some((path, mod_rs)) if path.exists() => out.push((path, segments, mod_rs)),
            Some((path, _)) => eprintln!("dejadoc: missing module file {}", path.display()),
            None => {}
        }
    }
}

/// File for `mod name;` and whether it is a mod-rs file. A top-level `#[path]` first, then
/// the first `cfg_attr` path whose predicate holds, both against `dir`, then `name.rs` or
/// `name/mod.rs` under `base`.
fn resolve_mod_path(
    dir: &std::path::Path,
    base: &std::path::Path,
    name: &str,
    attrs: &[syn::Attribute],
) -> Option<(PathBuf, bool)> {
    use syn::{Expr, ExprLit, Lit, Meta};

    if let Some(attr) = attrs.iter().find(|a| a.path().is_ident("path")) {
        let Meta::NameValue(nv) = &attr.meta else {
            return None;
        };
        let Expr::Lit(ExprLit {
            lit: Lit::Str(s), ..
        }) = &nv.value
        else {
            return None;
        };
        return Some((dir.join(s.value()), true));
    }
    if let Some(path) = attrs.iter().find_map(cfg_attr_path) {
        return Some((dir.join(path), true));
    }
    let plain = base.join(format!("{name}.rs"));
    if plain.exists() {
        return Some((plain, false));
    }
    Some((base.join(name).join("mod.rs"), true))
}

/// The `path = "…"` value of a `cfg_attr` whose predicate holds.
fn cfg_attr_path(attr: &syn::Attribute) -> Option<String> {
    use syn::{Expr, ExprLit, Lit, Meta, Token, punctuated::Punctuated};

    if !attr.path().is_ident("cfg_attr") {
        return None;
    }
    let Meta::List(list) = &attr.meta else {
        return None;
    };
    let metas = list
        .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
        .ok()?;
    if !metas.first().is_some_and(crate::cfg::holds) {
        return None;
    }
    metas.iter().skip(1).find_map(|meta| match meta {
        Meta::NameValue(nv) if nv.path.is_ident("path") => match &nv.value {
            Expr::Lit(ExprLit {
                lit: Lit::Str(s), ..
            }) => Some(s.value()),
            _ => None,
        },
        _ => None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    fn target(src: &std::path::Path) -> Target {
        Target {
            name: "mycrate".into(),
            src: src.to_path_buf(),
        }
    }

    fn files(result: Vec<(PathBuf, syn::File, Vec<String>)>) -> Vec<PathBuf> {
        result.into_iter().map(|(p, _, _)| p).collect()
    }

    #[test]
    fn walks_declared_mod_files() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod a;\npub fn f() {}\n").unwrap();
        std::fs::write(dir.path().join("a.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        let got: Vec<String> = files(result)
            .into_iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert_eq!(got, vec!["lib.rs", "a.rs"]);
    }

    #[test]
    fn resolves_mod_dir_form() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod a;\n").unwrap();
        std::fs::create_dir_all(dir.path().join("a")).unwrap();
        std::fs::write(dir.path().join("a").join("mod.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(files(result).len(), 2);
    }
    fn names(result: Vec<(PathBuf, syn::File, Vec<String>)>) -> Vec<String> {
        files(result)
            .into_iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect()
    }

    #[test]
    fn cfg_attr_path_resolves_when_its_predicate_holds() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(
            &root,
            "#[cfg_attr(unix, path = \"other.rs\")]\npub mod renamed;\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("other.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(names(result), vec!["lib.rs", "other.rs"]);
    }

    #[test]
    fn cfg_attr_path_takes_the_holding_predicate_not_the_first_file() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(
            &root,
            "#[cfg_attr(windows, path = \"windows.rs\")]\n\
             #[cfg_attr(unix, path = \"unix.rs\")]\n\
             pub mod platform;\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("windows.rs"), "pub fn w() {}\n").unwrap();
        std::fs::write(dir.path().join("unix.rs"), "pub fn u() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(names(result), vec!["lib.rs", "unix.rs"]);
    }

    #[test]
    fn cfg_attr_path_with_a_failing_predicate_falls_back_to_the_plain_file() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(
            &root,
            "#[cfg_attr(windows, path = \"windows.rs\")]\npub mod platform;\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("windows.rs"), "pub fn w() {}\n").unwrap();
        std::fs::write(dir.path().join("platform.rs"), "pub fn p() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(names(result), vec!["lib.rs", "platform.rs"]);
    }

    #[test]
    fn cfg_attr_multi_token_predicate_resolves_path() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(
            &root,
            "#[cfg_attr(all(unix, not(windows)), path = \"other.rs\")]\npub mod renamed;\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("other.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(names(result), vec!["lib.rs", "other.rs"]);
    }

    #[test]
    fn cfg_attr_path_beside_other_attributes_resolves() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(
            &root,
            "#[cfg_attr(unix, doc = \"d.rs\", path = \"other.rs\")]\npub mod renamed;\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("other.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(names(result), vec!["lib.rs", "other.rs"]);
    }

    #[test]
    fn file_module_companion_directory() {
        // `de.rs` with a companion `de/` keeps its child modules in `de/`,
        // as in serde_derive.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod de;\n").unwrap();
        std::fs::write(dir.path().join("de.rs"), "pub mod child;\n").unwrap();
        std::fs::create_dir_all(dir.path().join("de")).unwrap();
        std::fs::write(dir.path().join("de").join("child.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        let names: Vec<String> = files(result)
            .into_iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, vec!["lib.rs", "de.rs", "child.rs"]);
    }

    #[test]
    fn path_attribute_overrides_name() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "#[path = \"other.rs\"]\npub mod renamed;\n").unwrap();
        std::fs::write(dir.path().join("other.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        let got: Vec<String> = files(result)
            .into_iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert_eq!(got, vec!["lib.rs", "other.rs"]);
    }

    #[test]
    fn raw_identifier_module_file() {
        // `mod r#extern;` resolves to `extern.rs`, not `r#extern.rs`.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod r#extern;\n").unwrap();
        std::fs::write(dir.path().join("extern.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(files(result).len(), 2);
    }

    #[test]
    fn path_attribute_uses_the_defining_directory() {
        // `#[path]` inside a file module is relative to the directory
        // containing that file, not its companion directory.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod a;\n").unwrap();
        std::fs::write(dir.path().join("a.rs"), "#[path = \"a/b.rs\"]\nmod b;\n").unwrap();
        std::fs::create_dir_all(dir.path().join("a")).unwrap();
        std::fs::write(dir.path().join("a").join("b.rs"), "pub fn g() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        let names: Vec<String> = files(result)
            .into_iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, vec!["lib.rs", "a.rs", "b.rs"]);
    }

    #[test]
    fn module_tree_reports_module_path_segments() {
        // File modules carry their module path, including raw-ident names
        // and companion-directory nesting.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod r#extern;\npub mod a;\n").unwrap();
        std::fs::write(dir.path().join("extern.rs"), "pub fn g() {}\n").unwrap();
        std::fs::write(dir.path().join("a.rs"), "pub mod b;\n").unwrap();
        std::fs::create_dir_all(dir.path().join("a")).unwrap();
        std::fs::write(dir.path().join("a").join("b.rs"), "pub fn h() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        let paths: Vec<String> = result
            .into_iter()
            .map(|(_, _, seg)| seg.join("::"))
            .collect();
        assert_eq!(paths, vec!["", "extern", "a", "a::b"]);
    }

    #[test]
    fn missing_mod_is_skipped_without_error() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod missing;\npub fn f() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(files(result).len(), 1);
    }

    #[test]
    fn cfg_test_mod_files_are_not_collected() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(
            &root,
            "#[cfg(test)]\nmod tests;\n#[cfg(test)]\nmod inner { mod deep; }\n#[cfg(not(test))]\npub mod kept;\n",
        )
        .unwrap();
        for name in ["tests.rs", "deep.rs", "kept.rs"] {
            std::fs::write(dir.path().join(name), "pub fn g() {}\n").unwrap();
        }
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(files(result).len(), 2);
    }

    #[test]
    fn mod_decl_inside_inline_mod_resolves_under_the_inline_directory() {
        // `lib.rs` with `mod a { mod c; }` loads `a/c.rs`, a stale `c.rs`
        // beside `lib.rs` is not part of the crate.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod a { pub mod c; }\n").unwrap();
        std::fs::create_dir_all(dir.path().join("a")).unwrap();
        std::fs::write(dir.path().join("a").join("c.rs"), "pub fn g() {}\n").unwrap();
        std::fs::write(dir.path().join("c.rs"), "pub fn stale() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        let got: Vec<(PathBuf, Vec<String>)> = result
            .into_iter()
            .map(|(p, _, segs)| (p.strip_prefix(dir.path()).unwrap().to_path_buf(), segs))
            .collect();
        assert_eq!(
            got,
            vec![
                (PathBuf::from("lib.rs"), vec![]),
                (
                    PathBuf::from("a/c.rs"),
                    vec!["a".to_string(), "c".to_string()]
                )
            ]
        );
    }

    #[test]
    fn mod_decl_inside_inline_mod_of_a_file_module_nests_under_its_directory() {
        // `x.rs` with `mod a { mod c; }` loads `x/a/c.rs`.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod x;\n").unwrap();
        std::fs::write(dir.path().join("x.rs"), "pub mod a { pub mod c; }\n").unwrap();
        std::fs::create_dir_all(dir.path().join("x").join("a")).unwrap();
        std::fs::write(
            dir.path().join("x").join("a").join("c.rs"),
            "pub fn g() {}\n",
        )
        .unwrap();
        let result = module_tree(&target(&root)).unwrap();
        let paths: Vec<PathBuf> = files(result)
            .into_iter()
            .map(|p| p.strip_prefix(dir.path()).unwrap().to_path_buf())
            .collect();
        assert_eq!(
            paths,
            vec![
                PathBuf::from("lib.rs"),
                PathBuf::from("x.rs"),
                PathBuf::from("x/a/c.rs")
            ]
        );
    }

    #[test]
    fn nested_inline_mods_stack_their_directories() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod a { pub mod b { pub mod c; } }\n").unwrap();
        std::fs::create_dir_all(dir.path().join("a").join("b")).unwrap();
        std::fs::write(
            dir.path().join("a").join("b").join("c.rs"),
            "pub fn g() {}\n",
        )
        .unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(files(result).len(), 2);
    }

    #[test]
    fn path_attribute_inside_inline_mod_resolves_under_the_inline_directory() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod a { #[path = \"other.rs\"] pub mod c; }\n").unwrap();
        std::fs::create_dir_all(dir.path().join("a")).unwrap();
        std::fs::write(dir.path().join("a").join("other.rs"), "pub fn g() {}\n").unwrap();
        std::fs::write(dir.path().join("other.rs"), "pub fn stale() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        let paths: Vec<PathBuf> = files(result)
            .into_iter()
            .map(|p| p.strip_prefix(dir.path()).unwrap().to_path_buf())
            .collect();
        assert_eq!(
            paths,
            vec![PathBuf::from("lib.rs"), PathBuf::from("a/other.rs")]
        );
    }

    fn rel(dir: &std::path::Path, result: Vec<(PathBuf, syn::File, Vec<String>)>) -> Vec<PathBuf> {
        files(result)
            .into_iter()
            .map(|p| p.strip_prefix(dir).unwrap().to_path_buf())
            .collect()
    }

    #[test]
    fn root_with_a_directory_named_after_it_keeps_children_beside_it() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod foo;\npub mod lib { pub mod child; }\n").unwrap();
        std::fs::write(dir.path().join("foo.rs"), "").unwrap();
        std::fs::create_dir_all(dir.path().join("lib")).unwrap();
        std::fs::write(dir.path().join("lib").join("child.rs"), "").unwrap();
        std::fs::write(dir.path().join("lib").join("foo.rs"), "pub fn stale() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(
            rel(dir.path(), result),
            vec![
                PathBuf::from("lib.rs"),
                PathBuf::from("foo.rs"),
                PathBuf::from("lib/child.rs")
            ]
        );
    }

    #[test]
    fn path_loaded_file_keeps_children_beside_it() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "#[path = \"other.rs\"]\npub mod m;\n").unwrap();
        std::fs::write(dir.path().join("other.rs"), "pub mod c;\n").unwrap();
        std::fs::write(dir.path().join("c.rs"), "").unwrap();
        std::fs::create_dir_all(dir.path().join("other")).unwrap();
        std::fs::write(dir.path().join("other").join("c.rs"), "pub fn stale() {}\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(
            rel(dir.path(), result),
            vec![
                PathBuf::from("lib.rs"),
                PathBuf::from("other.rs"),
                PathBuf::from("c.rs")
            ]
        );
    }

    #[test]
    fn mod_rs_file_keeps_children_beside_it() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod a;\n").unwrap();
        std::fs::create_dir_all(dir.path().join("a").join("mod")).unwrap();
        std::fs::write(dir.path().join("a").join("mod.rs"), "pub mod b;\n").unwrap();
        std::fs::write(dir.path().join("a").join("b.rs"), "").unwrap();
        std::fs::write(
            dir.path().join("a").join("mod").join("b.rs"),
            "pub fn stale() {}\n",
        )
        .unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(
            rel(dir.path(), result),
            vec![
                PathBuf::from("lib.rs"),
                PathBuf::from("a/mod.rs"),
                PathBuf::from("a/b.rs")
            ]
        );
    }

    #[test]
    fn module_cycles_terminate() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "pub mod a;\n").unwrap();
        std::fs::write(
            dir.path().join("a.rs"),
            "#[path = \"lib.rs\"]\npub mod back;\n",
        )
        .unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert_eq!(files(result).len(), 2);
    }

    #[test]
    fn unparseable_file_is_skipped_without_error() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("lib.rs");
        std::fs::write(&root, "@@@ not rust @@ @\n").unwrap();
        let result = module_tree(&target(&root)).unwrap();
        assert!(result.is_empty());
    }

    fn cargo_package(dir: &std::path::Path, name: &str, extra: &str) {
        let src = dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            format!(
                "[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n{extra}"
            ),
        )
        .unwrap();
        std::fs::write(src.join("lib.rs"), "pub fn f() {}\n").unwrap();
    }

    #[test]
    fn default_is_lib_targets_only() {
        let dir = tempfile::tempdir().unwrap();
        cargo_package(
            dir.path(),
            "ws",
            // [workspace] stops cargo adopting an ancestor manifest, so
            // the fixture resolves the same wherever the tempdir lives.
            "[[bin]]\nname = \"tool\"\npath = \"src/bin/tool.rs\"\n[workspace]\n",
        );
        let bin = dir.path().join("src").join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::write(bin.join("tool.rs"), "fn main() {}\n").unwrap();
        let ws = workspace(dir.path(), None, false).unwrap();
        assert_eq!(ws.targets.len(), 1);
        assert_eq!(ws.targets[0].name, "ws");
        assert!(ws.targets[0].src.ends_with("src/lib.rs"));
        assert_eq!(ws.root, dir.path().to_path_buf());
    }

    #[test]
    fn all_targets_includes_bins_and_examples() {
        let dir = tempfile::tempdir().unwrap();
        cargo_package(
            dir.path(),
            "ws",
            "[[bin]]\nname = \"tool\"\npath = \"src/bin/tool.rs\"\n[workspace]\n",
        );
        let bin = dir.path().join("src").join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::write(bin.join("tool.rs"), "fn main() {}\n").unwrap();
        let ex = dir.path().join("examples");
        std::fs::create_dir_all(&ex).unwrap();
        std::fs::write(ex.join("demo.rs"), "fn main() {}\n").unwrap();
        let ws = workspace(dir.path(), None, true).unwrap();
        let names: Vec<&str> = ws.targets.iter().map(|t| t.name.as_str()).collect();
        assert!(names.contains(&"ws"));
        assert!(names.contains(&"tool"));
        assert!(names.contains(&"demo"));
    }

    #[test]
    fn package_filter_selects_one_member() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"alpha\", \"beta\"]\nresolver = \"2\"\n",
        )
        .unwrap();
        cargo_package(dir.path().join("alpha").as_path(), "alpha", "");
        cargo_package(dir.path().join("beta").as_path(), "beta", "");
        let ws = workspace(dir.path(), Some("beta"), false).unwrap();
        assert_eq!(ws.targets.len(), 1);
        assert_eq!(ws.targets[0].name, "beta");
        let ws = workspace(dir.path(), Some("nope"), false).unwrap();
        assert!(ws.targets.is_empty());
    }
}