cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
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
//! Ingest layer: discovers workspace crates, source files, and entry points via `cargo metadata`.

use std::path::{Path, PathBuf};

use cargo_metadata::{MetadataCommand, TargetKind};
use serde::Serialize;

/// A crate discovered in the workspace.
#[derive(Debug)]
pub struct CrateInfo {
    pub name: String,
    pub version: String,
    pub manifest_path: PathBuf,
    pub root: PathBuf,
    pub source_files: Vec<SourceFile>,
    pub entry_points: Vec<EntryPoint>,
    pub dependencies: Vec<DeclaredDependency>,
}

/// A dependency's declared kind in `Cargo.toml` (see todo.md §3.B, §14.2 P1
/// "misplaced-dependency-kind").
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DependencyKind {
    Normal,
    Development,
    Build,
}

impl DependencyKind {
    /// `cargo_metadata::DependencyKind::Unknown` is folded into `Normal`:
    /// cargo_metadata's own docs mark `Unknown` as a forward-compat catch-all
    /// for dependency kinds this parser version doesn't recognize yet, not a
    /// real third kind judge needs to special-case.
    fn from_cargo_kind(kind: cargo_metadata::DependencyKind) -> Self {
        match kind {
            cargo_metadata::DependencyKind::Development => Self::Development,
            cargo_metadata::DependencyKind::Build => Self::Build,
            cargo_metadata::DependencyKind::Normal | cargo_metadata::DependencyKind::Unknown => {
                Self::Normal
            }
        }
    }

    /// The short, lowercase label used in `cargo judge deps --why`'s TTY
    /// output (see `judge::rules::deps::why`, GitHub issue #22) — mirrors
    /// [`EntryPointKind::label`]'s precedent rather than a bare `{:?}`.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Development => "dev",
            Self::Build => "build",
        }
    }
}

/// A dependency declared in a crate's `Cargo.toml` (see todo.md §3.B, §14.2
/// P1). Judge's own type — [`cargo_metadata::Dependency`] is not leaked
/// through the public API, matching how [`TargetKind`] and [`EntryPointKind`]
/// are already kept internal.
#[derive(Debug, Clone)]
pub struct DeclaredDependency {
    /// The crate's real name (registry/path name), as declared — may contain
    /// `-`. This is *not* necessarily the identifier used in code; see
    /// `code_identifier`.
    pub name: String,
    pub kind: DependencyKind,
    /// The identifier this dependency is referenced by in code: the local
    /// rename (`package = "..."` alias) if set, else `name` with `-`
    /// replaced by `_` per Rust identifier rules.
    pub code_identifier: String,
    /// The `cfg(...)` platform string, if this is a target-specific
    /// dependency.
    pub target: Option<String>,
    pub features: Vec<String>,
    /// The dependency's version requirement, as declared (e.g. `"^1.0"`).
    /// Used by `phantom-version` (see todo.md §14.2 G5) to check whether any
    /// published, non-yanked version on crates.io satisfies it.
    pub version_req: String,
}

/// Where a source file came from (see todo.md §3.A "Generated-Code-Policy").
/// Generated code stays part of the graph (so its edges don't cause false
/// dead-code findings) but is excluded from local quality findings
/// (complexity, duplication) by default.
///
/// `BuildOutput` needs `OUT_DIR`/`include!` evidence, which the doc places in
/// the Deep Tier — Fast Tier only distinguishes `Authored` from `Generated`
/// via header markers below and never assigns `BuildOutput`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceKind {
    Authored,
    Generated,
    BuildOutput,
}

impl SourceKind {
    /// Whether local quality findings (complexity, duplication, …) should be
    /// reported for a file of this kind by default.
    pub const fn is_locally_reportable(self) -> bool {
        matches!(self, Self::Authored)
    }

    /// The stable, lowercase label used in JSON output — shared by
    /// [`crate::impact`] and [`crate::refactor_map`], which both surface a
    /// source file's kind in their reports.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Authored => "authored",
            Self::Generated => "generated",
            Self::BuildOutput => "build_output",
        }
    }
}

/// Header markers that flag a file as generated, checked against the first
/// [`HEADER_SCAN_LINES`] lines (see todo.md §3.A).
const GENERATED_MARKERS: &[&str] = &[
    "@generated",
    "DO NOT EDIT",
    "Code generated by",
    "automatically generated",
    "This file was automatically generated",
];
const HEADER_SCAN_LINES: usize = 10;

fn classify_source_kind(source: &str) -> SourceKind {
    let is_generated = source
        .lines()
        .take(HEADER_SCAN_LINES)
        .any(|line| GENERATED_MARKERS.iter().any(|marker| line.contains(marker)));
    if is_generated {
        SourceKind::Generated
    } else {
        SourceKind::Authored
    }
}

/// A single `.rs` file discovered in a crate, classified by [`SourceKind`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceFile {
    pub path: PathBuf,
    pub kind: SourceKind,
}

/// A single entry point recognized by judge's entry-point model (see todo.md §3.A).
#[derive(Debug)]
pub struct EntryPoint {
    pub kind: EntryPointKind,
    pub name: String,
    pub path: PathBuf,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntryPointKind {
    Bin,
    Lib,
    Example,
    Test,
    Bench,
    BuildScript,
}

impl EntryPointKind {
    pub const fn label(self) -> &'static str {
        match self {
            Self::Bin => "bin",
            Self::Lib => "lib",
            Self::Example => "example",
            Self::Test => "test",
            Self::Bench => "bench",
            Self::BuildScript => "build-script",
        }
    }

    fn from_cargo_kind(kind: &TargetKind) -> Option<Self> {
        match kind {
            TargetKind::Bin => Some(Self::Bin),
            TargetKind::Lib
            | TargetKind::RLib
            | TargetKind::DyLib
            | TargetKind::CDyLib
            | TargetKind::StaticLib
            | TargetKind::ProcMacro => Some(Self::Lib),
            TargetKind::Example => Some(Self::Example),
            TargetKind::Test => Some(Self::Test),
            TargetKind::Bench => Some(Self::Bench),
            TargetKind::CustomBuild => Some(Self::BuildScript),
            _ => None,
        }
    }
}

/// A discovered workspace: all local crates.
#[derive(Debug)]
pub struct Workspace {
    pub root: PathBuf,
    pub crates: Vec<CrateInfo>,
}

#[derive(Debug)]
pub enum IngestError {
    Metadata(cargo_metadata::Error),
    Io(std::io::Error),
}

impl std::fmt::Display for IngestError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Metadata(err) => write!(f, "failed to read cargo metadata: {err}"),
            Self::Io(err) => write!(f, "failed to walk source files: {err}"),
        }
    }
}

impl std::error::Error for IngestError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Metadata(err) => Some(err),
            Self::Io(err) => Some(err),
        }
    }
}

impl From<cargo_metadata::Error> for IngestError {
    fn from(err: cargo_metadata::Error) -> Self {
        Self::Metadata(err)
    }
}

impl From<std::io::Error> for IngestError {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}

/// Loads the workspace rooted at `manifest_path` (or the current directory's
/// `Cargo.toml` if `None`) by shelling out to `cargo metadata`.
pub fn load(manifest_path: Option<&Path>) -> Result<Workspace, IngestError> {
    let mut cmd = MetadataCommand::new();
    if let Some(path) = manifest_path {
        cmd.manifest_path(path);
    }
    let metadata = cmd.no_deps().exec()?;

    // Roots of every known package: all workspace members plus every declared
    // path dependency (path dependencies that are not workspace members do
    // not appear in `metadata.packages` under `--no-deps`, but their resolved
    // absolute `path` does). When walking one package's directory tree these
    // roots act as exclusion boundaries, so a package nested inside another
    // package's directory (vendored path dependency, nested workspace member)
    // is never attributed to the enclosing package.
    let mut package_roots: Vec<PathBuf> = Vec::new();
    for package in &metadata.packages {
        if let Some(root) = package.manifest_path.parent() {
            package_roots.push(root.to_path_buf().into());
        }
        for dep in &package.dependencies {
            if let Some(path) = &dep.path {
                package_roots.push(path.clone().into());
            }
        }
    }
    package_roots.sort();
    package_roots.dedup();

    let mut crates = Vec::new();
    for package in &metadata.packages {
        let manifest_path: PathBuf = package.manifest_path.clone().into();
        let root = manifest_path
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("."));
        let source_files = collect_source_files(&root, &package_roots)?;
        let entry_points = package
            .targets
            .iter()
            .flat_map(|target| {
                target.kind.iter().filter_map(move |kind| {
                    EntryPointKind::from_cargo_kind(kind).map(|kind| EntryPoint {
                        kind,
                        name: target.name.clone(),
                        path: target.src_path.clone().into(),
                    })
                })
            })
            .collect();
        let dependencies = package
            .dependencies
            .iter()
            .map(|dep| {
                let code_identifier = dep
                    .rename
                    .clone()
                    .unwrap_or_else(|| dep.name.replace('-', "_"));
                DeclaredDependency {
                    name: dep.name.clone(),
                    kind: DependencyKind::from_cargo_kind(dep.kind),
                    code_identifier,
                    target: dep.target.as_ref().map(ToString::to_string),
                    features: dep.features.clone(),
                    version_req: dep.req.to_string(),
                }
            })
            .collect();

        crates.push(CrateInfo {
            name: package.name.to_string(),
            version: package.version.to_string(),
            manifest_path,
            root,
            source_files,
            entry_points,
            dependencies,
        });
    }
    crates.sort_by(|a, b| a.name.cmp(&b.name));

    Ok(Workspace {
        root: metadata.workspace_root.into(),
        crates,
    })
}

/// Recursively collects `.rs` files under `root`, skipping `target/`
/// directories and the roots of other known packages (`package_roots`, which
/// may include `root` itself — the walk only ever compares subdirectories
/// against it), and classifies each by [`SourceKind`]. Excluding foreign
/// package roots keeps every file attributed to exactly one package: the one
/// with the most specific root.
fn collect_source_files(
    root: &Path,
    package_roots: &[PathBuf],
) -> std::io::Result<Vec<SourceFile>> {
    let mut paths = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let path = entry.path();
            if entry.file_type()?.is_dir() {
                let is_target_or_hidden = path.file_name().is_some_and(|name| {
                    name == "target" || name.to_str().is_some_and(|name| name.starts_with('.'))
                });
                if is_target_or_hidden || package_roots.contains(&path) {
                    continue;
                }
                stack.push(path);
            } else if path.extension().is_some_and(|ext| ext == "rs") {
                paths.push(path);
            }
        }
    }
    paths.sort();

    let files = paths
        .into_iter()
        .map(|path| {
            let kind = std::fs::read_to_string(&path)
                .map(|source| classify_source_kind(&source))
                .unwrap_or(SourceKind::Authored);
            SourceFile { path, kind }
        })
        .collect();
    Ok(files)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::TempDir;

    #[test]
    fn load_discovers_crate_source_files_and_entry_points() {
        let dir = TempDir::new("ingest-basic");
        std::fs::write(
            dir.join("Cargo.toml"),
            r#"
[package]
name = "fixture"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::create_dir_all(dir.join("src/bin")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(dir.join("src/bin/tool.rs"), "fn main() {}\n").unwrap();

        let manifest = dir.join("Cargo.toml");
        let workspace = load(Some(&manifest)).unwrap();

        assert_eq!(workspace.crates.len(), 1);
        let krate = &workspace.crates[0];
        assert_eq!(krate.name, "fixture");

        let mut files: Vec<_> = krate
            .source_files
            .iter()
            .map(|file| file.path.strip_prefix(&krate.root).unwrap().to_path_buf())
            .collect();
        files.sort();
        assert_eq!(
            files,
            vec![
                PathBuf::from("src/bin/tool.rs"),
                PathBuf::from("src/lib.rs")
            ]
        );

        let kinds: Vec<_> = krate.entry_points.iter().map(|entry| entry.kind).collect();
        assert!(kinds.contains(&EntryPointKind::Lib));
        assert!(kinds.contains(&EntryPointKind::Bin));
    }

    #[test]
    fn a_nested_path_dependency_is_not_attributed_to_the_root_crate() {
        let dir = TempDir::new("ingest-nested-path-dep");
        std::fs::write(
            dir.join("Cargo.toml"),
            r#"
[package]
name = "fixture"
version = "0.1.0"
edition = "2021"

[dependencies]
dep = { path = "vendored/dep" }
"#,
        )
        .unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::create_dir_all(dir.join("vendored/dep/src")).unwrap();
        std::fs::write(
            dir.join("vendored/dep/Cargo.toml"),
            r#"
[package]
name = "dep"
version = "0.1.0"
edition = "2021"

[workspace]
"#,
        )
        .unwrap();
        std::fs::write(dir.join("vendored/dep/src/lib.rs"), "pub fn dep() {}\n").unwrap();

        let manifest = dir.join("Cargo.toml");
        let workspace = load(Some(&manifest)).unwrap();

        // The path dependency is not a workspace member, so only the root
        // crate is analyzed — and the dependency's sources are not counted
        // as part of it.
        assert_eq!(workspace.crates.len(), 1);
        let krate = &workspace.crates[0];
        assert_eq!(krate.name, "fixture");
        let files: Vec<_> = krate
            .source_files
            .iter()
            .map(|file| file.path.strip_prefix(&krate.root).unwrap().to_path_buf())
            .collect();
        assert_eq!(files, vec![PathBuf::from("src/lib.rs")]);
    }

    #[test]
    fn a_workspace_member_nested_inside_another_member_owns_its_own_files() {
        let dir = TempDir::new("ingest-nested-member");
        std::fs::write(
            dir.join("Cargo.toml"),
            r#"
[workspace]
members = ["outer", "outer/inner"]
"#,
        )
        .unwrap();
        std::fs::create_dir_all(dir.join("outer/src")).unwrap();
        std::fs::write(
            dir.join("outer/Cargo.toml"),
            r#"
[package]
name = "outer"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::write(dir.join("outer/src/lib.rs"), "pub fn outer() {}\n").unwrap();
        std::fs::create_dir_all(dir.join("outer/inner/src")).unwrap();
        std::fs::write(
            dir.join("outer/inner/Cargo.toml"),
            r#"
[package]
name = "inner"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::write(dir.join("outer/inner/src/lib.rs"), "pub fn inner() {}\n").unwrap();

        let manifest = dir.join("Cargo.toml");
        let workspace = load(Some(&manifest)).unwrap();

        // Every file belongs to exactly one crate: the one with the most
        // specific root.
        assert_eq!(workspace.crates.len(), 2);
        let files_of = |name: &str| -> Vec<PathBuf> {
            let krate = workspace
                .crates
                .iter()
                .find(|krate| krate.name == name)
                .unwrap();
            krate
                .source_files
                .iter()
                .map(|file| file.path.strip_prefix(&krate.root).unwrap().to_path_buf())
                .collect()
        };
        assert_eq!(files_of("outer"), vec![PathBuf::from("src/lib.rs")]);
        assert_eq!(files_of("inner"), vec![PathBuf::from("src/lib.rs")]);
    }

    #[test]
    fn load_reports_metadata_error_for_a_missing_manifest() {
        let dir = TempDir::new("ingest-missing-manifest");
        let manifest = dir.join("Cargo.toml");

        let err = load(Some(&manifest)).unwrap_err();
        assert!(matches!(err, IngestError::Metadata(_)));
    }

    #[test]
    fn collect_source_files_skips_the_target_directory() {
        let dir = TempDir::new("ingest-skip-target");
        std::fs::create_dir_all(dir.join("target/debug")).unwrap();
        std::fs::write(dir.join("target/debug/generated.rs"), "// generated\n").unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();

        let files = collect_source_files(&dir, &[]).unwrap();

        assert_eq!(
            files,
            vec![SourceFile {
                path: dir.join("src/lib.rs"),
                kind: SourceKind::Authored,
            }]
        );
    }

    #[test]
    fn collect_source_files_skips_hidden_directories() {
        let dir = TempDir::new("ingest-skip-hidden");
        std::fs::create_dir_all(dir.join(".claude/worktrees/agent-x/src")).unwrap();
        std::fs::write(
            dir.join(".claude/worktrees/agent-x/src/lib.rs"),
            "pub fn hidden() {}\n",
        )
        .unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();

        let files = collect_source_files(&dir, &[]).unwrap();

        assert_eq!(
            files,
            vec![SourceFile {
                path: dir.join("src/lib.rs"),
                kind: SourceKind::Authored,
            }]
        );
    }

    #[test]
    fn a_header_marker_classifies_a_file_as_generated() {
        let dir = TempDir::new("ingest-generated");
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.join("src/schema.rs"),
            "// @generated by openapi-codegen. DO NOT EDIT.\npub struct Schema;\n",
        )
        .unwrap();

        let files = collect_source_files(&dir, &[]).unwrap();

        let kind_of = |name: &str| {
            files
                .iter()
                .find(|file| file.path.ends_with(name))
                .unwrap()
                .kind
        };
        assert_eq!(kind_of("lib.rs"), SourceKind::Authored);
        assert_eq!(kind_of("schema.rs"), SourceKind::Generated);
    }

    #[test]
    fn a_marker_outside_the_scanned_header_lines_is_not_detected() {
        let dir = TempDir::new("ingest-generated-late-marker");
        std::fs::create_dir_all(dir.join("src")).unwrap();
        let mut source = "\n".repeat(HEADER_SCAN_LINES);
        source.push_str("// @generated too late to count\n");
        std::fs::write(dir.join("src/lib.rs"), source).unwrap();

        let files = collect_source_files(&dir, &[]).unwrap();

        assert_eq!(files[0].kind, SourceKind::Authored);
    }

    #[test]
    fn ingest_error_source_preserves_the_underlying_error() {
        let err = IngestError::Io(std::io::Error::other("boom"));
        let source = std::error::Error::source(&err).expect("Io must carry a source");
        assert!(source.downcast_ref::<std::io::Error>().is_some());
        assert_eq!(err.to_string(), "failed to walk source files: boom");
    }
}