cargo-coupling 0.3.7

A coupling analysis tool for Rust projects - measuring the 'right distance' in your code
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
//! Source file discovery for crate analysis.
//!
//! This module finds the source files of each crate via (a) directory walks of
//! cargo-metadata target roots and (b) module-tree resolution from crate roots
//! following `mod` declarations, including `#[path]` attributes, and derives
//! module names. Walk-based names take precedence for files both methods find.

use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::fs;
use std::path::{Component, Path, PathBuf};

use syn::{Expr, ExprLit, ItemMod, Lit, Meta};
use walkdir::WalkDir;

/// Convert file path to module path relative to the source root.
///
/// Examples:
/// - `src/level/enemy/spawner.rs` with root `src` → `level::enemy::spawner`
/// - `src/lib.rs` with root `src` → `` (empty, crate root)
/// - `src/main.rs` with root `src` → `` (empty, crate root)
/// - `src/level/mod.rs` with root `src` → `level`
/// - `src/utils.rs` with root `src` → `utils`
///
/// See: https://github.com/nwiizo/cargo-coupling/issues/14
pub(crate) fn file_path_to_module_path(file_path: &Path, src_root: &Path) -> String {
    // Get the relative path from src root
    let relative = file_path.strip_prefix(src_root).unwrap_or(file_path);

    let mut parts: Vec<String> = Vec::new();

    for component in relative.components() {
        if let Some(component_name) = component.as_os_str().to_str() {
            parts.push(component_name.to_string());
        }
    }

    // Handle the last component (filename)
    if let Some(last) = parts.last().cloned() {
        parts.pop();
        match last.as_str() {
            "lib.rs" | "main.rs" => {
                // Crate root - don't add anything
            }
            "mod.rs" => {
                // mod.rs represents its parent directory, already in parts
            }
            _ => {
                // Regular file - remove .rs extension and add to path
                if let Some(stem) = last.strip_suffix(".rs") {
                    parts.push(stem.to_string());
                } else {
                    parts.push(last);
                }
            }
        }
    }

    parts.join("::")
}

/// Normalize a path for exclude matching without resolving symlinks.
///
/// This keeps `./src`, `/tmp/foo`, and other caller-provided forms comparable
/// by making them absolute and removing `.` / `..` components lexically.
pub(crate) fn normalize_exclude_path(path: &Path) -> PathBuf {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .unwrap_or_else(|_| path.to_path_buf())
    };

    let mut normalized = PathBuf::new();
    for component in absolute.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            other => normalized.push(other.as_os_str()),
        }
    }

    normalized
}

/// Get an iterator over all Rust source files in `dir`, excluding hidden directories and `target/`.
///
/// Uses relative paths for filtering to avoid false positives when the project
/// is located in a path containing hidden directories (e.g., `/home/user/.local/projects/`).
/// See: https://github.com/nwiizo/cargo-coupling/issues/7
pub(crate) fn rs_files(dir: &Path) -> impl Iterator<Item = PathBuf> {
    WalkDir::new(dir)
        .follow_links(true)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(move |entry| {
            let file_path = entry.path();
            // Use relative path from the search root to check for hidden/target directories.
            // This prevents false positives when parent directories contain `.` or `target`.
            // Example: `/home/user/.config/myproject/src/lib.rs` should not be skipped
            // just because `.config` is in the parent path.
            let file_path = file_path.strip_prefix(dir).unwrap_or(file_path);

            !file_path.components().any(|c| {
                let s = c.as_os_str().to_string_lossy();
                is_skipped_component(&s)
            }) && file_path.extension() == Some(OsStr::new("rs"))
        })
        .map(|e| e.path().to_path_buf())
}

/// Get Rust source files under `dir`, pruning nested packages and conventional non-source roots.
pub(crate) fn rs_files_excluding_nested_packages(
    dir: &Path,
    manifest_path: &Path,
) -> impl Iterator<Item = PathBuf> {
    let manifest_path = normalize_exclude_path(manifest_path);
    WalkDir::new(dir)
        .follow_links(true)
        .into_iter()
        .filter_entry(move |entry| {
            should_descend_workspace_source(entry.path(), dir, &manifest_path)
        })
        .filter_map(|e| e.ok())
        .filter(move |entry| {
            let file_path = entry.path();
            let relative_path = file_path.strip_prefix(dir).unwrap_or(file_path);

            !relative_path.components().any(|c| {
                let s = c.as_os_str().to_string_lossy();
                is_skipped_component(&s)
            }) && file_path.extension() == Some(OsStr::new("rs"))
        })
        .map(|e| e.path().to_path_buf())
}

/// Return whether a workspace source walk may descend into `path` for this member.
pub(crate) fn should_descend_workspace_source(
    path: &Path,
    root: &Path,
    manifest_path: &Path,
) -> bool {
    let relative_path = path.strip_prefix(root).unwrap_or(path);
    if relative_path.components().any(|c| {
        let s = c.as_os_str().to_string_lossy();
        is_skipped_component(&s)
    }) {
        return false;
    }

    if is_manifest_level_non_source(path, manifest_path) {
        return false;
    }

    if path.is_dir() {
        let cargo_toml = path.join("Cargo.toml");
        if cargo_toml.exists() && normalize_exclude_path(&cargo_toml) != manifest_path {
            return false;
        }
    }

    true
}

fn is_skipped_component(name: &str) -> bool {
    name == "target" || name.starts_with('.')
}

fn is_manifest_level_non_source(path: &Path, manifest_path: &Path) -> bool {
    let Some(manifest_dir) = manifest_path.parent() else {
        return false;
    };
    let path = normalize_exclude_path(path);
    let manifest_dir = normalize_exclude_path(manifest_dir);

    path == manifest_dir.join("build.rs")
        || path == manifest_dir.join("tests")
        || path == manifest_dir.join("examples")
        || path == manifest_dir.join("benches")
}

#[derive(Debug, Clone)]
pub(crate) struct DiscoveredWorkspaceFile {
    /// Rust source file selected for analysis.
    pub(crate) file_path: PathBuf,
    /// Cargo package name that owns this analysis entry.
    pub(crate) crate_name: String,
    /// Root used to derive walk-based module names.
    pub(crate) source_root: PathBuf,
    /// Module name resolved from the Rust module tree, when walk naming is unavailable.
    pub(crate) module_name: Option<String>,
}

#[derive(Debug, Clone)]
pub(crate) struct ModuleTreeFile {
    /// Rust source file reached from a crate root.
    pub(crate) file_path: PathBuf,
    /// Module path resolved from `mod` declarations.
    pub(crate) module_name: String,
}

/// Files found through module-tree discovery and rejected boundary references.
#[derive(Debug, Clone, Default)]
pub(crate) struct ModuleTreeDiscovery {
    /// Files resolved inside the current package/workspace boundary.
    pub(crate) files: Vec<ModuleTreeFile>,
    /// Module references rejected for crossing package or workspace boundaries.
    pub(crate) boundary_skipped_files: usize,
}

/// Return a stable key for comparing file identities across lexical path forms.
pub(crate) fn canonical_file_key(path: &Path) -> PathBuf {
    fs::canonicalize(path).unwrap_or_else(|_| normalize_exclude_path(path))
}

/// Discover files reachable from a crate root through external `mod` declarations.
pub(crate) fn discover_module_tree(
    crate_root: &Path,
    workspace_root: &Path,
    manifest_path: &Path,
    visited: &mut HashSet<PathBuf>,
    source_contents: &mut HashMap<PathBuf, String>,
) -> ModuleTreeDiscovery {
    let mut context = ModuleTreeContext {
        workspace_root: canonical_file_key(workspace_root),
        manifest_path: canonical_file_key(manifest_path),
        visited,
        source_contents,
        discovery: ModuleTreeDiscovery::default(),
    };
    discover_module_tree_file(
        crate_root,
        String::new(),
        crate_root.parent().unwrap_or_else(|| Path::new("")),
        &mut context,
    );
    context.discovery
}

struct ModuleTreeContext<'a> {
    workspace_root: PathBuf,
    manifest_path: PathBuf,
    visited: &'a mut HashSet<PathBuf>,
    source_contents: &'a mut HashMap<PathBuf, String>,
    discovery: ModuleTreeDiscovery,
}

fn discover_module_tree_file(
    file_path: &Path,
    module_name: String,
    module_dir: &Path,
    context: &mut ModuleTreeContext<'_>,
) {
    if !file_path.exists() {
        return;
    }

    let file_key = canonical_file_key(file_path);
    if !context.visited.insert(file_key) {
        return;
    }

    context.discovery.files.push(ModuleTreeFile {
        file_path: file_path.to_path_buf(),
        module_name: module_name.clone(),
    });

    let content = match context.source_contents.get(&canonical_file_key(file_path)) {
        Some(content) => content.clone(),
        None => {
            let Ok(content) = fs::read_to_string(file_path) else {
                return;
            };
            context
                .source_contents
                .insert(canonical_file_key(file_path), content.clone());
            content
        }
    };
    let Ok(parsed) = syn::parse_file(&content) else {
        return;
    };

    discover_module_items(&parsed.items, module_dir, &module_name, context);
}

/// Discover external module declarations; inline `#[path]` base-dir overrides are not modeled.
fn discover_module_items(
    items: &[syn::Item],
    module_dir: &Path,
    parent_module: &str,
    context: &mut ModuleTreeContext<'_>,
) {
    for item in items {
        let syn::Item::Mod(item_mod) = item else {
            continue;
        };

        let child_name = item_mod.ident.to_string();
        let child_module = join_module_path(parent_module, &child_name);
        if let Some((_, inline_items)) = &item_mod.content {
            let inline_module_dir = module_dir.join(&child_name);
            discover_module_items(inline_items, &inline_module_dir, &child_module, context);
            continue;
        }

        match resolve_external_module_file(
            module_dir,
            item_mod,
            &context.workspace_root,
            &context.manifest_path,
        ) {
            ModuleFileResolution::Resolved(resolved_file) => {
                let child_module_dir = module_dir_for_resolved_module(&resolved_file);
                discover_module_tree_file(&resolved_file, child_module, &child_module_dir, context);
            }
            ModuleFileResolution::BoundarySkipped => {
                context.discovery.boundary_skipped_files += 1;
            }
            ModuleFileResolution::NotFound => {}
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum ModuleFileResolution {
    Resolved(PathBuf),
    BoundarySkipped,
    NotFound,
}

/// Resolve an external module file in rustc order: `#[path]`, `name.rs`, then `name/mod.rs`.
fn resolve_external_module_file(
    module_dir: &Path,
    item_mod: &ItemMod,
    workspace_root: &Path,
    manifest_path: &Path,
) -> ModuleFileResolution {
    if let Some(path_attr) = path_attribute_value(&item_mod.attrs) {
        return boundary_checked_module_file(
            module_dir.join(path_attr),
            workspace_root,
            manifest_path,
        );
    }

    let module_name = item_mod.ident.to_string();
    let flat = module_dir.join(format!("{module_name}.rs"));
    if flat.exists() {
        return boundary_checked_module_file(flat, workspace_root, manifest_path);
    }

    let nested = module_dir.join(&module_name).join("mod.rs");
    if nested.exists() {
        boundary_checked_module_file(nested, workspace_root, manifest_path)
    } else {
        ModuleFileResolution::NotFound
    }
}

fn boundary_checked_module_file(
    candidate: PathBuf,
    workspace_root: &Path,
    manifest_path: &Path,
) -> ModuleFileResolution {
    let Ok(canonical_candidate) = fs::canonicalize(&candidate) else {
        return ModuleFileResolution::NotFound;
    };

    if !canonical_candidate.starts_with(workspace_root)
        || crosses_package_boundary(&canonical_candidate, workspace_root, manifest_path)
    {
        return ModuleFileResolution::BoundarySkipped;
    }

    ModuleFileResolution::Resolved(canonical_candidate)
}

fn crosses_package_boundary(
    canonical_file: &Path,
    workspace_root: &Path,
    manifest_path: &Path,
) -> bool {
    let mut current = canonical_file.parent();
    while let Some(dir) = current {
        if dir == workspace_root {
            break;
        }

        let cargo_toml = dir.join("Cargo.toml");
        if cargo_toml.exists() && canonical_file_key(&cargo_toml) != manifest_path {
            return true;
        }

        current = dir.parent();
    }

    false
}

/// Extract the string value from a `#[path = "..."]` module attribute.
fn path_attribute_value(attrs: &[syn::Attribute]) -> Option<PathBuf> {
    attrs.iter().find_map(|attr| {
        if !attr.path().is_ident("path") {
            return None;
        }
        match &attr.meta {
            Meta::NameValue(name_value) => {
                if let Expr::Lit(ExprLit {
                    lit: Lit::Str(value),
                    ..
                }) = &name_value.value
                {
                    Some(PathBuf::from(value.value()))
                } else {
                    None
                }
            }
            _ => None,
        }
    })
}

/// Return the directory used to resolve children of a resolved module file.
fn module_dir_for_resolved_module(file_path: &Path) -> PathBuf {
    let parent = file_path.parent().unwrap_or_else(|| Path::new(""));
    if file_path.file_name() == Some(OsStr::new("mod.rs")) {
        parent.to_path_buf()
    } else {
        parent.join(
            file_path
                .file_stem()
                .and_then(|stem| stem.to_str())
                .unwrap_or_default(),
        )
    }
}

pub(crate) fn join_module_path(prefix: &str, rest: &str) -> String {
    if prefix.is_empty() {
        rest.to_string()
    } else if rest.is_empty() {
        prefix.to_string()
    } else {
        format!("{prefix}::{rest}")
    }
}

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

    /// Test that rs_files correctly handles paths with hidden parent directories.
    /// Regression test for https://github.com/nwiizo/cargo-coupling/issues/7
    #[test]
    fn test_rs_files_with_hidden_parent_directory() {
        use std::fs;
        use tempfile::TempDir;

        // Create a temporary directory structure that simulates a project
        // inside a hidden parent directory (e.g., /home/user/.local/projects/myproject)
        let temp = TempDir::new().unwrap();
        let hidden_parent = temp.path().join(".hidden-parent");
        let project_dir = hidden_parent.join("myproject").join("src");
        fs::create_dir_all(&project_dir).unwrap();

        // Create some Rust files
        fs::write(project_dir.join("lib.rs"), "pub fn hello() {}").unwrap();
        fs::write(project_dir.join("main.rs"), "fn main() {}").unwrap();

        // rs_files should find both files even though there's a hidden parent
        let files: Vec<_> = rs_files(&project_dir).collect();
        assert_eq!(
            files.len(),
            2,
            "Should find 2 .rs files in hidden parent path"
        );

        // Verify the files are the ones we created
        let file_names: Vec<_> = files
            .iter()
            .filter_map(|p| p.file_name())
            .filter_map(|n| n.to_str())
            .collect();
        assert!(file_names.contains(&"lib.rs"));
        assert!(file_names.contains(&"main.rs"));
    }

    /// Test that rs_files correctly excludes hidden directories within the project.
    #[test]
    fn test_rs_files_excludes_hidden_dirs_in_project() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().join("myproject").join("src");
        let hidden_dir = project_dir.join(".hidden");
        fs::create_dir_all(&hidden_dir).unwrap();

        // Create files in both regular and hidden directories
        fs::write(project_dir.join("lib.rs"), "pub fn hello() {}").unwrap();
        fs::write(hidden_dir.join("secret.rs"), "fn secret() {}").unwrap();

        // rs_files should only find lib.rs, not the file in .hidden
        let files: Vec<_> = rs_files(&project_dir).collect();
        assert_eq!(
            files.len(),
            1,
            "Should find only 1 .rs file (excluding .hidden/)"
        );

        let file_names: Vec<_> = files
            .iter()
            .filter_map(|p| p.file_name())
            .filter_map(|n| n.to_str())
            .collect();
        assert!(file_names.contains(&"lib.rs"));
        assert!(!file_names.contains(&"secret.rs"));
    }

    /// Test that rs_files correctly excludes the target directory.
    #[test]
    fn test_rs_files_excludes_target_directory() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().join("myproject");
        let src_dir = project_dir.join("src");
        let target_dir = project_dir.join("target").join("debug");
        fs::create_dir_all(&src_dir).unwrap();
        fs::create_dir_all(&target_dir).unwrap();

        // Create files in both src and target directories
        fs::write(src_dir.join("lib.rs"), "pub fn hello() {}").unwrap();
        fs::write(target_dir.join("generated.rs"), "// generated").unwrap();

        // rs_files should only find lib.rs, not the file in target/
        let files: Vec<_> = rs_files(&project_dir).collect();
        assert_eq!(
            files.len(),
            1,
            "Should find only 1 .rs file (excluding target/)"
        );

        let file_names: Vec<_> = files
            .iter()
            .filter_map(|p| p.file_name())
            .filter_map(|n| n.to_str())
            .collect();
        assert!(file_names.contains(&"lib.rs"));
        assert!(!file_names.contains(&"generated.rs"));
    }

    #[test]
    fn resolve_external_module_file_prefers_path_attribute() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let module_dir = temp.path().join("src");
        fs::create_dir_all(&module_dir).unwrap();
        fs::write(module_dir.join("custom.rs"), "pub fn custom() {}").unwrap();
        fs::write(module_dir.join("name.rs"), "pub fn flat() {}").unwrap();
        fs::create_dir_all(module_dir.join("name")).unwrap();
        fs::write(module_dir.join("name/mod.rs"), "pub fn nested() {}").unwrap();
        let item_mod: ItemMod = syn::parse_quote!(
            #[path = "custom.rs"]
            mod name;
        );

        let resolved = resolve_external_module_file(
            &module_dir,
            &item_mod,
            &canonical_file_key(temp.path()),
            &canonical_file_key(&temp.path().join("Cargo.toml")),
        );

        assert_eq!(
            resolved,
            ModuleFileResolution::Resolved(canonical_file_key(&module_dir.join("custom.rs")))
        );
    }

    #[test]
    fn resolve_external_module_file_uses_flat_before_nested() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let module_dir = temp.path().join("src");
        fs::create_dir_all(module_dir.join("name")).unwrap();
        fs::write(module_dir.join("name.rs"), "pub fn flat() {}").unwrap();
        fs::write(module_dir.join("name/mod.rs"), "pub fn nested() {}").unwrap();
        let item_mod: ItemMod = syn::parse_quote!(
            mod name;
        );

        let resolved = resolve_external_module_file(
            &module_dir,
            &item_mod,
            &canonical_file_key(temp.path()),
            &canonical_file_key(&temp.path().join("Cargo.toml")),
        );

        assert_eq!(
            resolved,
            ModuleFileResolution::Resolved(canonical_file_key(&module_dir.join("name.rs")))
        );
    }

    #[test]
    fn resolve_external_module_file_rejects_outside_workspace() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let workspace = temp.path().join("workspace");
        let module_dir = workspace.join("src");
        fs::create_dir_all(&module_dir).unwrap();
        fs::write(temp.path().join("outside.rs"), "pub fn outside() {}").unwrap();
        let item_mod: ItemMod = syn::parse_quote!(
            #[path = "../../outside.rs"]
            mod outside;
        );

        let resolved = resolve_external_module_file(
            &module_dir,
            &item_mod,
            &canonical_file_key(&workspace),
            &canonical_file_key(&workspace.join("Cargo.toml")),
        );

        assert_eq!(resolved, ModuleFileResolution::BoundarySkipped);
    }

    #[test]
    fn resolve_external_module_file_rejects_other_package() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let workspace = temp.path().join("workspace");
        let current = workspace.join("a");
        let other = workspace.join("b");
        let module_dir = current.join("src");
        fs::create_dir_all(&module_dir).unwrap();
        fs::create_dir_all(other.join("src")).unwrap();
        fs::write(current.join("Cargo.toml"), "[package]\nname = \"a\"\n").unwrap();
        fs::write(other.join("Cargo.toml"), "[package]\nname = \"b\"\n").unwrap();
        fs::write(other.join("src/shared.rs"), "pub fn shared() {}").unwrap();
        let item_mod: ItemMod = syn::parse_quote!(
            #[path = "../../b/src/shared.rs"]
            mod shared;
        );

        let resolved = resolve_external_module_file(
            &module_dir,
            &item_mod,
            &canonical_file_key(&workspace),
            &canonical_file_key(&current.join("Cargo.toml")),
        );

        assert_eq!(resolved, ModuleFileResolution::BoundarySkipped);
    }

    #[test]
    fn test_file_path_to_module_path_nested() {
        // Test: src/level/enemy/spawner.rs -> level::enemy::spawner
        let src_root = Path::new("/project/src");
        let file_path = Path::new("/project/src/level/enemy/spawner.rs");
        assert_eq!(
            file_path_to_module_path(file_path, src_root),
            "level::enemy::spawner"
        );
    }

    #[test]
    fn test_file_path_to_module_path_lib() {
        // Test: src/lib.rs -> "" (crate root)
        let src_root = Path::new("/project/src");
        let file_path = Path::new("/project/src/lib.rs");
        assert_eq!(file_path_to_module_path(file_path, src_root), "");
    }

    #[test]
    fn test_file_path_to_module_path_main() {
        // Test: src/main.rs -> "" (crate root)
        let src_root = Path::new("/project/src");
        let file_path = Path::new("/project/src/main.rs");
        assert_eq!(file_path_to_module_path(file_path, src_root), "");
    }

    #[test]
    fn test_file_path_to_module_path_mod() {
        // Test: src/level/mod.rs -> level
        let src_root = Path::new("/project/src");
        let file_path = Path::new("/project/src/level/mod.rs");
        assert_eq!(file_path_to_module_path(file_path, src_root), "level");
    }

    #[test]
    fn test_file_path_to_module_path_deeply_nested_mod() {
        // Test: src/a/b/c/mod.rs -> a::b::c
        let src_root = Path::new("/project/src");
        let file_path = Path::new("/project/src/a/b/c/mod.rs");
        assert_eq!(file_path_to_module_path(file_path, src_root), "a::b::c");
    }

    #[test]
    fn test_file_path_to_module_path_simple() {
        // Test: src/utils.rs -> utils
        let src_root = Path::new("/project/src");
        let file_path = Path::new("/project/src/utils.rs");
        assert_eq!(file_path_to_module_path(file_path, src_root), "utils");
    }

    #[test]
    fn test_file_path_to_module_path_two_levels() {
        // Test: src/foo/bar.rs -> foo::bar
        let src_root = Path::new("/project/src");
        let file_path = Path::new("/project/src/foo/bar.rs");
        assert_eq!(file_path_to_module_path(file_path, src_root), "foo::bar");
    }

    #[test]
    fn test_file_path_to_module_path_bin() {
        // Test: src/bin/cli.rs -> bin::cli
        let src_root = Path::new("/project/src");
        let file_path = Path::new("/project/src/bin/cli.rs");
        assert_eq!(file_path_to_module_path(file_path, src_root), "bin::cli");
    }

    #[test]
    fn test_file_path_to_module_path_mismatched_root() {
        // When strip_prefix fails, we fall back to using the full path
        // This handles edge cases where src_root doesn't match
        let src_root = Path::new("/other/src");
        let file_path = Path::new("/project/src/utils.rs");
        // Falls back to full path processing
        let result = file_path_to_module_path(file_path, src_root);
        // Should still produce something reasonable
        assert!(result.contains("utils"));
    }
}