cargo-brief 0.12.1

Visibility-aware Rust API extractor — pseudo-Rust output for AI agent consumption
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;

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

use crate::features::{FeatureGraph, build_feature_graph};

/// Metadata extracted from `cargo metadata`.
pub struct CargoMetadataInfo {
    /// Names of all packages in the workspace.
    pub workspace_packages: Vec<String>,
    /// The package whose manifest_path directory matches cwd, if any.
    pub current_package: Option<String>,
    /// The manifest directory of the current package (for file path resolution).
    pub current_package_manifest_dir: Option<PathBuf>,
    /// The target directory for build artifacts.
    pub target_dir: PathBuf,
    /// Manifest directory for each workspace package (name → dir).
    pub package_manifest_dirs: HashMap<String, PathBuf>,
    /// The workspace root directory (from `workspace_root` in cargo metadata).
    pub workspace_root: PathBuf,
    /// Feature graph for each workspace package (name → graph).
    pub feature_graphs: HashMap<String, FeatureGraph>,
}

/// A resolved target for the pipeline.
#[derive(Debug)]
pub struct ResolvedTarget {
    pub package_name: String,
    pub module_path: Option<String>,
}

/// Load cargo metadata for the workspace.
pub fn load_cargo_metadata(manifest_path: Option<&str>) -> Result<CargoMetadataInfo> {
    let mut cmd = Command::new("cargo");
    cmd.args(["metadata", "--format-version=1", "--no-deps"]);

    if let Some(manifest) = manifest_path {
        cmd.args(["--manifest-path", manifest]);
    }

    let output = cmd.output().context("Failed to run cargo metadata")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("cargo metadata failed:\n{stderr}");
    }

    let metadata: serde_json::Value =
        serde_json::from_slice(&output.stdout).context("Failed to parse cargo metadata")?;

    let target_dir = metadata["target_directory"]
        .as_str()
        .context("No target_directory in cargo metadata")?;

    let workspace_root = metadata["workspace_root"]
        .as_str()
        .context("No workspace_root in cargo metadata")?;

    let cwd = std::env::current_dir().context("Failed to get current directory")?;
    let cwd_canonical = cwd.canonicalize().unwrap_or(cwd);

    let mut workspace_packages = Vec::new();
    let mut current_package = None;
    let mut current_package_manifest_dir = None;
    let mut package_manifest_dirs = HashMap::new();
    let mut feature_graphs = HashMap::new();

    if let Some(packages) = metadata["packages"].as_array() {
        for pkg in packages {
            if let Some(name) = pkg["name"].as_str() {
                workspace_packages.push(name.to_string());

                // Check if this package's manifest directory matches cwd
                if let Some(manifest) = pkg["manifest_path"].as_str() {
                    let manifest_dir = Path::new(manifest).parent().unwrap_or(Path::new(""));
                    let manifest_canonical = manifest_dir
                        .canonicalize()
                        .unwrap_or(manifest_dir.to_path_buf());

                    package_manifest_dirs.insert(name.to_string(), manifest_canonical.clone());

                    if manifest_canonical == cwd_canonical {
                        current_package = Some(name.to_string());
                        current_package_manifest_dir = Some(manifest_canonical);
                    }
                }

                let graph = build_feature_graph(name.to_string(), &pkg["features"]);
                feature_graphs.insert(name.to_string(), graph);
            }
        }
    }

    Ok(CargoMetadataInfo {
        workspace_packages,
        current_package,
        current_package_manifest_dir,
        target_dir: PathBuf::from(target_dir),
        package_manifest_dirs,
        workspace_root: PathBuf::from(workspace_root),
        feature_graphs,
    })
}

/// Resolve the user's positional arguments into a package name and optional module path.
///
/// Resolution rules:
/// 1. `first_arg == "self"` → current package; second_arg becomes module (file path aware)
/// 2. `first_arg` contains `::` → split at first `::`:
///    - prefix `self` → current package + rest as module
///    - otherwise → prefix is package name, rest is module
/// 3. Two args → backward compat: first=package, second=module (file path aware)
/// 4. Single arg, no `::` → if file path, resolve to self module; else check workspace packages; else treat as package
pub fn resolve_target(
    first_arg: &str,
    second_arg: Option<&str>,
    metadata: &CargoMetadataInfo,
) -> Result<ResolvedTarget> {
    // Case 1: explicit "self" keyword
    if first_arg == "self" {
        let pkg = current_package_or_error(metadata)?;
        let module = match second_arg {
            Some(m) => maybe_file_to_module(strip_self_prefix(m), metadata)?,
            None => None,
        };
        return Ok(ResolvedTarget {
            package_name: pkg,
            module_path: module,
        });
    }

    // Case 2: contains "::" — split at first occurrence
    if let Some(idx) = first_arg.find("::") {
        let prefix = &first_arg[..idx];
        let rest = &first_arg[idx + 2..];
        let module = if rest.is_empty() {
            None
        } else {
            Some(rest.to_string())
        };

        if prefix == "self" {
            let pkg = current_package_or_error(metadata)?;
            return Ok(ResolvedTarget {
                package_name: pkg,
                module_path: module,
            });
        } else {
            return Ok(ResolvedTarget {
                package_name: prefix.to_string(),
                module_path: module,
            });
        }
    }

    // Case 3: two args provided → backward compat (file path aware on module arg)
    if let Some(module) = second_arg {
        let module = maybe_file_to_module(module, metadata)?;
        return Ok(ResolvedTarget {
            package_name: first_arg.to_string(),
            module_path: module,
        });
    }

    // Case 4a: single arg that looks like a file path → resolve to self module
    if is_file_path(first_arg) {
        let pkg = current_package_or_error(metadata)?;
        let module = file_path_to_module_path(first_arg, metadata)?;
        return Ok(ResolvedTarget {
            package_name: pkg,
            module_path: module,
        });
    }

    // Case 4b: single arg, no "::" → try workspace package first, then self module
    if let Some(pkg) = find_workspace_package(&metadata.workspace_packages, first_arg) {
        return Ok(ResolvedTarget {
            package_name: pkg,
            module_path: None,
        });
    }

    // Not a known workspace package → treat as external package name.
    // Users should use `self::module` or file paths for self-module access.
    Ok(ResolvedTarget {
        package_name: first_arg.to_string(),
        module_path: None,
    })
}

/// If the input looks like a file path, convert it to a module path; otherwise return as-is.
fn maybe_file_to_module(input: &str, metadata: &CargoMetadataInfo) -> Result<Option<String>> {
    if is_file_path(input) {
        file_path_to_module_path(input, metadata)
    } else if input.is_empty() {
        Ok(None)
    } else {
        Ok(Some(input.to_string()))
    }
}

/// Detect whether a string looks like a file path rather than a module path.
/// File paths contain `/` or end with `.rs`; module paths use `::` separators.
fn is_file_path(s: &str) -> bool {
    s.contains('/') || s.ends_with(".rs")
}

/// Convert a file path to a module path.
///
/// Fallback order:
/// 1. Try as cwd-relative path
/// 2. Try as relative to the current package's `src/` directory
///
/// Then strip the `src/` prefix and convert: `.rs` → remove, `mod.rs` → parent,
/// `lib.rs` → None (crate root), `/` → `::`.
fn file_path_to_module_path(input: &str, metadata: &CargoMetadataInfo) -> Result<Option<String>> {
    let input_path = Path::new(input);

    // Try to resolve the file path
    let resolved = if input_path.is_file() {
        // cwd-relative path exists
        input_path
            .canonicalize()
            .with_context(|| format!("Failed to canonicalize path: {input}"))?
    } else if let Some(pkg_dir) = &metadata.current_package_manifest_dir {
        // Try relative to package's src/
        let src_relative = pkg_dir.join("src").join(input);
        if src_relative.is_file() {
            src_relative.canonicalize()?
        } else {
            // Try relative to package root
            let pkg_relative = pkg_dir.join(input);
            if pkg_relative.is_file() {
                pkg_relative.canonicalize()?
            } else {
                bail!(
                    "File not found: '{input}'\n\
                     Searched:\n  - ./{input}\n  - {}/src/{input}\n  - {}/{input}",
                    pkg_dir.display(),
                    pkg_dir.display()
                );
            }
        }
    } else {
        bail!(
            "File not found: '{input}'\n\
             (No current package directory for fallback search.)"
        );
    };

    // Find the package's src/ directory and make path relative to it
    let pkg_dir = metadata
        .current_package_manifest_dir
        .as_ref()
        .context("Cannot resolve file path without a current package")?;
    let src_dir = pkg_dir.join("src");
    let src_canonical = src_dir
        .canonicalize()
        .with_context(|| format!("Package src/ directory not found: {}", src_dir.display()))?;

    let relative = resolved.strip_prefix(&src_canonical).with_context(|| {
        format!(
            "File '{}' is not inside the package's src/ directory ({})",
            resolved.display(),
            src_canonical.display()
        )
    })?;

    path_components_to_module(relative)
}

/// Convert a path relative to `src/` into a module path.
fn path_components_to_module(relative: &Path) -> Result<Option<String>> {
    let file_name = relative
        .file_name()
        .and_then(|f| f.to_str())
        .context("Invalid file name")?;

    // lib.rs at root → crate root (no module path)
    if file_name == "lib.rs" && relative.parent().is_none_or(|p| p == Path::new("")) {
        return Ok(None);
    }

    let stem = relative
        .file_stem()
        .and_then(|s| s.to_str())
        .context("Invalid file stem")?;

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

    // Collect directory components
    if let Some(parent) = relative.parent() {
        for component in parent.components() {
            if let std::path::Component::Normal(s) = component {
                parts.push(s.to_str().context("Non-UTF8 path component")?);
            }
        }
    }

    // mod.rs → use only parent directory path; other files → append stem
    if stem != "mod" {
        parts.push(stem);
    }

    if parts.is_empty() {
        // mod.rs at src root → crate root
        Ok(None)
    } else {
        Ok(Some(parts.join("::")))
    }
}

/// Strip a leading `self::` prefix if present.
fn strip_self_prefix(s: &str) -> &str {
    s.strip_prefix("self::").unwrap_or(s)
}

/// Get the current package or return a descriptive error.
fn current_package_or_error(metadata: &CargoMetadataInfo) -> Result<String> {
    metadata.current_package.clone().ok_or_else(|| {
        anyhow::anyhow!(
            "Cannot resolve 'self': no package found for the current directory.\n\
             Are you in a package directory? (Virtual workspace roots have no package.)"
        )
    })
}

/// Find a dependency's source root from cargo metadata (with deps).
/// Runs `cargo metadata` WITHOUT `--no-deps` to include all resolved dependencies,
/// then finds the package matching `crate_name` (with hyphen/underscore normalization).
pub fn find_dep_source_root(manifest_path: &str, crate_name: &str) -> Result<PathBuf> {
    let output = Command::new("cargo")
        .args([
            "metadata",
            "--format-version=1",
            "--manifest-path",
            manifest_path,
        ])
        .output()
        .context("Failed to run cargo metadata (with deps)")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("cargo metadata failed:\n{stderr}");
    }

    let metadata: serde_json::Value =
        serde_json::from_slice(&output.stdout).context("Failed to parse cargo metadata")?;

    let normalized_query = crate_name.replace('-', "_");

    if let Some(packages) = metadata["packages"].as_array() {
        for pkg in packages {
            if let Some(name) = pkg["name"].as_str()
                && name.replace('-', "_") == normalized_query
                && let Some(manifest) = pkg["manifest_path"].as_str()
            {
                let manifest_dir = Path::new(manifest).parent().unwrap_or(Path::new(""));
                return Ok(manifest_dir.to_path_buf());
            }
        }
    }

    bail!("Package '{crate_name}' not found in dependency tree of '{manifest_path}'")
}

/// Load all resolved package directories and direct deps from cargo metadata
/// (WITH deps — runs full dependency resolution).
///
/// Returns `(all_package_dirs, direct_dep_names_of_root)`.
/// `all_package_dirs`: package name → manifest dir for every resolved package.
/// `direct_dep_names`: cargo package names that `root_package` directly depends on.
pub fn load_dep_package_dirs(
    manifest_path: Option<&str>,
    root_package: &str,
) -> Result<(HashMap<String, PathBuf>, Vec<String>)> {
    let mut cmd = Command::new("cargo");
    cmd.args(["metadata", "--format-version=1"]);
    if let Some(mp) = manifest_path {
        cmd.args(["--manifest-path", mp]);
    }

    let output = cmd
        .output()
        .context("Failed to run cargo metadata (with deps)")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("cargo metadata failed:\n{stderr}");
    }

    let metadata: serde_json::Value =
        serde_json::from_slice(&output.stdout).context("Failed to parse cargo metadata")?;

    // Build name → manifest_dir and name → id maps from packages[]
    let mut all_dirs = HashMap::new();
    let mut root_pkg_id: Option<String> = None;
    let normalized_root = root_package.replace('-', "_");

    if let Some(packages) = metadata["packages"].as_array() {
        for pkg in packages {
            if let (Some(name), Some(manifest)) =
                (pkg["name"].as_str(), pkg["manifest_path"].as_str())
            {
                let dir = Path::new(manifest)
                    .parent()
                    .unwrap_or(Path::new(""))
                    .to_path_buf();
                all_dirs.insert(name.to_string(), dir);

                // Match root package by name (with normalization)
                if root_pkg_id.is_none()
                    && name.replace('-', "_") == normalized_root
                    && let Some(id) = pkg["id"].as_str()
                {
                    root_pkg_id = Some(id.to_string());
                }
            }
        }
    }

    // Find root package's node in resolve.nodes[] using the exact id
    let mut direct_dep_names = Vec::new();

    if let Some(ref root_id) = root_pkg_id
        && let Some(nodes) = metadata["resolve"]["nodes"].as_array()
    {
        let root_node = nodes
            .iter()
            .find(|node| node["id"].as_str() == Some(root_id.as_str()));

        if let Some(node) = root_node
            && let Some(deps) = node["deps"].as_array()
        {
            for dep in deps {
                if let Some(dep_name) = dep["name"].as_str() {
                    // dep.name is Rust-identifier form (underscores).
                    // Try exact match first, then hyphen fallback.
                    let cargo_name = if all_dirs.contains_key(dep_name) {
                        dep_name.to_string()
                    } else {
                        let hyphenated = dep_name.replace('_', "-");
                        if all_dirs.contains_key(&hyphenated) {
                            hyphenated
                        } else {
                            continue;
                        }
                    };
                    direct_dep_names.push(cargo_name);
                }
            }
        }
    }

    Ok((all_dirs, direct_dep_names))
}

/// Find a package in the workspace, normalizing hyphens/underscores.
fn find_workspace_package(packages: &[String], query: &str) -> Option<String> {
    let normalized = query.replace('-', "_");
    packages
        .iter()
        .find(|p| p.replace('-', "_") == normalized)
        .cloned()
}

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

    fn test_metadata(packages: &[&str], current: Option<&str>) -> CargoMetadataInfo {
        CargoMetadataInfo {
            workspace_packages: packages.iter().map(|s| s.to_string()).collect(),
            current_package: current.map(|s| s.to_string()),
            current_package_manifest_dir: None,
            target_dir: PathBuf::from("/tmp/target"),
            package_manifest_dirs: HashMap::new(),
            workspace_root: PathBuf::from("/tmp"),
            feature_graphs: HashMap::new(),
        }
    }

    fn test_metadata_with_dir(
        packages: &[&str],
        current: Option<&str>,
        manifest_dir: &Path,
    ) -> CargoMetadataInfo {
        CargoMetadataInfo {
            workspace_packages: packages.iter().map(|s| s.to_string()).collect(),
            current_package: current.map(|s| s.to_string()),
            current_package_manifest_dir: Some(manifest_dir.to_path_buf()),
            target_dir: PathBuf::from("/tmp/target"),
            package_manifest_dirs: HashMap::new(),
            workspace_root: PathBuf::from("/tmp"),
            feature_graphs: HashMap::new(),
        }
    }

    #[test]
    fn test_self_keyword_no_module() {
        let meta = test_metadata(&["my-crate"], Some("my-crate"));
        let resolved = resolve_target("self", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "my-crate");
        assert_eq!(resolved.module_path, None);
    }

    #[test]
    fn test_self_keyword_with_module() {
        let meta = test_metadata(&["my-crate"], Some("my-crate"));
        let resolved = resolve_target("self", Some("foo::bar"), &meta).unwrap();
        assert_eq!(resolved.package_name, "my-crate");
        assert_eq!(resolved.module_path, Some("foo::bar".to_string()));
    }

    #[test]
    fn test_self_keyword_strips_self_prefix_in_module() {
        let meta = test_metadata(&["my-crate"], Some("my-crate"));
        let resolved = resolve_target("self", Some("self::foo"), &meta).unwrap();
        assert_eq!(resolved.module_path, Some("foo".to_string()));
    }

    #[test]
    fn test_self_no_current_package_errors() {
        let meta = test_metadata(&["other"], None);
        let result = resolve_target("self", None, &meta);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("self"));
    }

    #[test]
    fn test_double_colon_self_prefix() {
        let meta = test_metadata(&["my-crate"], Some("my-crate"));
        let resolved = resolve_target("self::cli", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "my-crate");
        assert_eq!(resolved.module_path, Some("cli".to_string()));
    }

    #[test]
    fn test_double_colon_package_prefix() {
        let meta = test_metadata(&["hecs", "my-crate"], Some("my-crate"));
        let resolved = resolve_target("hecs::world", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "hecs");
        assert_eq!(resolved.module_path, Some("world".to_string()));
    }

    #[test]
    fn test_double_colon_trailing_empty() {
        let meta = test_metadata(&["my-crate"], Some("my-crate"));
        let resolved = resolve_target("self::", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "my-crate");
        assert_eq!(resolved.module_path, None);
    }

    #[test]
    fn test_two_args_backward_compat() {
        let meta = test_metadata(&["hecs"], Some("my-crate"));
        let resolved = resolve_target("hecs", Some("world"), &meta).unwrap();
        assert_eq!(resolved.package_name, "hecs");
        assert_eq!(resolved.module_path, Some("world".to_string()));
    }

    #[test]
    fn test_single_arg_known_package() {
        let meta = test_metadata(&["hecs", "my-crate"], Some("my-crate"));
        let resolved = resolve_target("hecs", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "hecs");
        assert_eq!(resolved.module_path, None);
    }

    #[test]
    fn test_single_arg_unknown_resolves_as_package() {
        let meta = test_metadata(&["my-crate"], Some("my-crate"));
        let resolved = resolve_target("cli", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "cli");
        assert_eq!(resolved.module_path, None);
    }

    #[test]
    fn test_single_arg_no_current_package_assumes_external() {
        let meta = test_metadata(&[], None);
        let resolved = resolve_target("hecs", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "hecs");
        assert_eq!(resolved.module_path, None);
    }

    #[test]
    fn test_hyphen_underscore_normalization() {
        let meta = test_metadata(&["my-crate"], Some("my-crate"));
        let resolved = resolve_target("my_crate", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "my-crate");
        assert_eq!(resolved.module_path, None);
    }

    // === File path detection ===

    #[test]
    fn test_is_file_path_with_slash() {
        assert!(is_file_path("src/cli.rs"));
        assert!(is_file_path("foo/bar"));
    }

    #[test]
    fn test_is_file_path_with_rs_extension() {
        assert!(is_file_path("cli.rs"));
        assert!(is_file_path("model.rs"));
    }

    #[test]
    fn test_is_file_path_not_module() {
        assert!(!is_file_path("cli"));
        assert!(!is_file_path("foo::bar"));
    }

    // === path_components_to_module unit tests ===

    #[test]
    fn test_path_to_module_simple_file() {
        let result = path_components_to_module(Path::new("cli.rs")).unwrap();
        assert_eq!(result, Some("cli".to_string()));
    }

    #[test]
    fn test_path_to_module_nested_file() {
        let result = path_components_to_module(Path::new("model/item.rs")).unwrap();
        assert_eq!(result, Some("model::item".to_string()));
    }

    #[test]
    fn test_path_to_module_mod_rs() {
        let result = path_components_to_module(Path::new("model/mod.rs")).unwrap();
        assert_eq!(result, Some("model".to_string()));
    }

    #[test]
    fn test_path_to_module_lib_rs() {
        let result = path_components_to_module(Path::new("lib.rs")).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_path_to_module_deeply_nested() {
        let result = path_components_to_module(Path::new("a/b/c.rs")).unwrap();
        assert_eq!(result, Some("a::b::c".to_string()));
    }

    // === File path in resolve_target (integration with real filesystem) ===

    #[test]
    fn test_single_arg_file_path_cwd_relative() {
        // src/cli.rs exists relative to cwd (the project root)
        let cwd = std::env::current_dir().unwrap();
        let meta = test_metadata_with_dir(&["cargo-brief"], Some("cargo-brief"), &cwd);
        let resolved = resolve_target("src/cli.rs", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "cargo-brief");
        assert_eq!(resolved.module_path, Some("cli".to_string()));
    }

    #[test]
    fn test_single_arg_file_path_lib_rs() {
        let cwd = std::env::current_dir().unwrap();
        let meta = test_metadata_with_dir(&["cargo-brief"], Some("cargo-brief"), &cwd);
        let resolved = resolve_target("src/lib.rs", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "cargo-brief");
        assert_eq!(resolved.module_path, None);
    }

    #[test]
    fn test_self_with_file_path_module() {
        let cwd = std::env::current_dir().unwrap();
        let meta = test_metadata_with_dir(&["cargo-brief"], Some("cargo-brief"), &cwd);
        let resolved = resolve_target("self", Some("src/resolve.rs"), &meta).unwrap();
        assert_eq!(resolved.package_name, "cargo-brief");
        assert_eq!(resolved.module_path, Some("resolve".to_string()));
    }

    #[test]
    fn test_two_args_file_path_module() {
        let cwd = std::env::current_dir().unwrap();
        let meta = test_metadata_with_dir(&["cargo-brief"], Some("cargo-brief"), &cwd);
        let resolved = resolve_target("cargo-brief", Some("src/cli.rs"), &meta).unwrap();
        assert_eq!(resolved.package_name, "cargo-brief");
        assert_eq!(resolved.module_path, Some("cli".to_string()));
    }

    #[test]
    fn test_file_path_src_fallback() {
        // "cli.rs" doesn't exist at cwd, but does at src/cli.rs
        let cwd = std::env::current_dir().unwrap();
        let meta = test_metadata_with_dir(&["cargo-brief"], Some("cargo-brief"), &cwd);
        let resolved = resolve_target("cli.rs", None, &meta).unwrap();
        assert_eq!(resolved.package_name, "cargo-brief");
        assert_eq!(resolved.module_path, Some("cli".to_string()));
    }

    #[test]
    fn test_file_path_not_found_errors() {
        let cwd = std::env::current_dir().unwrap();
        let meta = test_metadata_with_dir(&["cargo-brief"], Some("cargo-brief"), &cwd);
        let result = resolve_target("nonexistent.rs", None, &meta);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }
}