Skip to main content

cargo_detect_package/
lib.rs

1#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3
4//! A Cargo tool to detect the package that a file belongs to, passing the package name
5//! to a subcommand.
6//!
7//! This crate provides the core logic for package detection, exposed via the [`run`] function.
8//! The binary entry point is in `main.rs`.
9
10mod detection;
11mod execution;
12mod pal;
13mod types;
14mod workspace;
15
16use detection::{DetectedPackage, detect_package};
17use execution::{execute_with_cargo_args, execute_with_env_var};
18use pal::{Filesystem, FilesystemFacade};
19pub use types::*;
20use workspace::validate_workspace_context;
21
22/// Core logic of the tool, extracted for testability.
23///
24/// This function contains all the business logic without any process-global dependencies
25/// like `std::env::args()`, making it suitable for direct testing.
26#[doc(hidden)]
27pub fn run(input: &RunInput) -> Result<RunOutcome, RunError> {
28    run_with_filesystem(input, &FilesystemFacade::target())
29}
30
31/// Internal implementation of `run` that accepts a filesystem abstraction.
32///
33/// This allows mocking filesystem operations in tests.
34fn run_with_filesystem(input: &RunInput, fs: &impl Filesystem) -> Result<RunOutcome, RunError> {
35    // Validate that we are running from within the same workspace as the target path.
36    // This also canonicalizes paths and finds the workspace root, which we reuse later.
37    let workspace_context = validate_workspace_context(&input.path, fs)
38        .map_err(|e| RunError::WorkspaceValidation(e.to_string()))?;
39
40    let detected_package = detect_package(&workspace_context, fs)
41        .map_err(|e| RunError::PackageDetection(e.to_string()))?;
42
43    // Handle outside package actions.
44    match (&detected_package, &input.outside_package) {
45        (DetectedPackage::Workspace, OutsidePackageAction::Ignore) => {
46            println!("Path is not in any package, ignoring as requested");
47            return Ok(RunOutcome::Ignored);
48        }
49        (DetectedPackage::Workspace, OutsidePackageAction::Error) => {
50            return Err(RunError::OutsidePackage);
51        }
52        (DetectedPackage::Package(name), _) => {
53            println!("Detected package: {name}");
54        }
55        (DetectedPackage::Workspace, OutsidePackageAction::Workspace) => {
56            println!("Path is not in any package, using workspace scope");
57        }
58    }
59
60    assert_early_exit_cases_handled(&detected_package, &input.outside_package);
61
62    let exit_status = match &input.via_env {
63        Some(env_var) => execute_with_env_var(
64            &workspace_context.workspace_root,
65            env_var,
66            &detected_package,
67            &input.subcommand,
68        ),
69        None => execute_with_cargo_args(
70            &workspace_context.workspace_root,
71            &detected_package,
72            &input.subcommand,
73        ),
74    }
75    .map_err(RunError::CommandExecution)?;
76
77    let subcommand_succeeded = exit_status.success();
78
79    match detected_package {
80        DetectedPackage::Package(package_name) => Ok(RunOutcome::PackageDetected {
81            package_name,
82            subcommand_succeeded,
83        }),
84        DetectedPackage::Workspace => Ok(RunOutcome::WorkspaceScope {
85            subcommand_succeeded,
86        }),
87    }
88}
89
90/// Defense-in-depth check: verifies that the match block in `run()` has handled all early-exit
91/// cases. If this assertion fails, it indicates a logic bug in the match block that should have
92/// returned early for the Ignore and Error cases.
93///
94/// This assertion can never fail with the current code structure because the match block returns
95/// early for both (Workspace, Ignore) and (Workspace, Error) cases.
96// Defense-in-depth check that can never be reached due to earlier match block logic.
97#[cfg_attr(test, mutants::skip)]
98#[cfg_attr(coverage_nightly, coverage(off))]
99fn assert_early_exit_cases_handled(
100    detected_package: &DetectedPackage,
101    outside_package: &OutsidePackageAction,
102) {
103    let is_early_exit_case = matches!(
104        (detected_package, outside_package),
105        (
106            DetectedPackage::Workspace,
107            OutsidePackageAction::Ignore | OutsidePackageAction::Error
108        )
109    );
110    assert!(
111        !is_early_exit_case,
112        "Logic error: the match block above must return early for Ignore/Error cases"
113    );
114}
115
116// Mock-based tests that do not require real filesystem access.
117// These tests duplicate key scenarios from the integration tests but use a mock filesystem,
118// enabling fine-grained control over filesystem behavior (e.g., files disappearing mid-operation).
119#[cfg(test)]
120#[cfg_attr(coverage_nightly, coverage(off))]
121mod mock_tests {
122    use std::io;
123    use std::path::{Path, PathBuf};
124
125    use super::*;
126    use crate::detection::WorkspaceContext;
127    use crate::pal::{FilesystemFacade, MockFilesystem};
128
129    /// Helper to create a mock filesystem for a simple workspace with one package.
130    ///
131    /// Structure:
132    /// ```text
133    /// /workspace/
134    ///   Cargo.toml (workspace)
135    ///   package_a/
136    ///     Cargo.toml (package: "package_a")
137    ///     src/
138    ///       lib.rs
139    ///   README.md
140    /// ```
141    fn create_simple_workspace_mock() -> MockFilesystem {
142        let mut mock = MockFilesystem::new();
143
144        // current_dir returns the workspace root.
145        mock.expect_current_dir()
146            .returning(|| Ok(PathBuf::from("/workspace")));
147
148        // Set up cargo_toml_exists expectations.
149        mock.expect_cargo_toml_exists().returning(|dir| {
150            let path_str = dir.to_string_lossy();
151            path_str == "/workspace" || path_str == "/workspace/package_a"
152        });
153
154        // Set up read_cargo_toml expectations.
155        mock.expect_read_cargo_toml().returning(|dir| {
156            let path_str = dir.to_string_lossy();
157            if path_str == "/workspace" {
158                Ok(r#"[workspace]
159members = ["package_a"]
160"#
161                .to_string())
162            } else if path_str == "/workspace/package_a" {
163                Ok(r#"[package]
164name = "package_a"
165version = "0.1.0"
166"#
167                .to_string())
168            } else {
169                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
170            }
171        });
172
173        // Set up is_file expectations.
174        mock.expect_is_file().returning(|path| {
175            let path_str = path.to_string_lossy();
176            path_str.ends_with(".rs") || path_str.ends_with(".md")
177        });
178
179        // Set up exists expectations.
180        mock.expect_exists().returning(|path| {
181            let path_str = path.to_string_lossy();
182            path_str == "/workspace"
183                || path_str == "/workspace/Cargo.toml"
184                || path_str == "/workspace/package_a"
185                || path_str == "/workspace/package_a/Cargo.toml"
186                || path_str == "/workspace/package_a/src"
187                || path_str == "/workspace/package_a/src/lib.rs"
188                || path_str == "/workspace/README.md"
189        });
190
191        // Set up canonicalize expectations - returns path as-is for virtual filesystem.
192        mock.expect_canonicalize()
193            .returning(|path| Ok(path.to_path_buf()));
194
195        mock
196    }
197
198    #[test]
199    fn mock_package_detection_in_simple_workspace() {
200        let mock = create_simple_workspace_mock();
201        let fs = FilesystemFacade::from_mock(mock);
202
203        let context =
204            validate_workspace_context(Path::new("/workspace/package_a/src/lib.rs"), &fs).unwrap();
205
206        let result = detect_package(&context, &fs).unwrap();
207
208        assert_eq!(result, DetectedPackage::Package("package_a".to_string()));
209    }
210
211    #[test]
212    fn mock_workspace_root_file_fallback() {
213        let mock = create_simple_workspace_mock();
214        let fs = FilesystemFacade::from_mock(mock);
215
216        let context = validate_workspace_context(Path::new("/workspace/README.md"), &fs).unwrap();
217
218        let result = detect_package(&context, &fs).unwrap();
219
220        assert_eq!(result, DetectedPackage::Workspace);
221    }
222
223    #[test]
224    fn mock_nonexistent_file_error() {
225        let mut mock = MockFilesystem::new();
226
227        mock.expect_current_dir()
228            .returning(|| Ok(PathBuf::from("/workspace")));
229
230        mock.expect_cargo_toml_exists()
231            .returning(|dir| dir.to_string_lossy() == "/workspace");
232
233        mock.expect_read_cargo_toml().returning(|dir| {
234            if dir.to_string_lossy() == "/workspace" {
235                Ok("[workspace]\nmembers = []\n".to_string())
236            } else {
237                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
238            }
239        });
240
241        mock.expect_exists().returning(|path| {
242            let path_str = path.to_string_lossy();
243            path_str == "/workspace" || path_str == "/workspace/Cargo.toml"
244        });
245
246        mock.expect_canonicalize().returning(|path| {
247            let path_str = path.to_string_lossy();
248            if path_str.contains("nonexistent") {
249                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
250            } else {
251                Ok(path.to_path_buf())
252            }
253        });
254
255        let fs = FilesystemFacade::from_mock(mock);
256
257        let result =
258            validate_workspace_context(Path::new("/workspace/package_a/src/nonexistent.rs"), &fs);
259
260        assert!(result.is_err());
261        assert!(result.unwrap_err().to_string().contains("does not exist"));
262    }
263
264    #[test]
265    fn mock_file_disappears_during_package_detection() {
266        // This test demonstrates the power of mocking - we can simulate a file disappearing
267        // between the exists check and the read operation.
268        use std::sync::Arc;
269        use std::sync::atomic::{AtomicBool, Ordering};
270
271        let file_exists = Arc::new(AtomicBool::new(true));
272        let file_exists_clone = Arc::clone(&file_exists);
273
274        let mut mock = MockFilesystem::new();
275
276        mock.expect_current_dir()
277            .returning(|| Ok(PathBuf::from("/workspace")));
278
279        mock.expect_cargo_toml_exists().returning(move |dir| {
280            let path_str = dir.to_string_lossy();
281            if path_str == "/workspace/package_a" {
282                // First call returns true, then we "delete" the file.
283                let exists = file_exists_clone.load(Ordering::SeqCst);
284                file_exists_clone.store(false, Ordering::SeqCst);
285                exists
286            } else {
287                path_str == "/workspace"
288            }
289        });
290
291        mock.expect_read_cargo_toml().returning(|dir| {
292            let path_str = dir.to_string_lossy();
293            if path_str == "/workspace" {
294                Ok("[workspace]\nmembers = [\"package_a\"]\n".to_string())
295            } else {
296                // File was "deleted" - return error.
297                Err(io::Error::new(io::ErrorKind::NotFound, "file was deleted"))
298            }
299        });
300
301        mock.expect_is_file()
302            .returning(|path| path.to_string_lossy().ends_with(".rs"));
303
304        mock.expect_exists().returning(|_| true);
305
306        mock.expect_canonicalize()
307            .returning(|path| Ok(path.to_path_buf()));
308
309        let fs = FilesystemFacade::from_mock(mock);
310
311        // Create context directly to skip validation (which would also call the mock).
312        let context = WorkspaceContext {
313            absolute_target_path: PathBuf::from("/workspace/package_a/src/lib.rs"),
314            workspace_root: PathBuf::from("/workspace"),
315        };
316
317        // The file exists when cargo_toml_exists is called, but disappears when we try to read it.
318        let result = detect_package(&context, &fs);
319
320        assert!(result.is_err());
321        assert!(result.unwrap_err().to_string().contains("deleted"));
322    }
323
324    #[test]
325    fn mock_invalid_toml_in_package() {
326        let mut mock = MockFilesystem::new();
327
328        mock.expect_current_dir()
329            .returning(|| Ok(PathBuf::from("/workspace")));
330
331        mock.expect_cargo_toml_exists().returning(|dir| {
332            let path_str = dir.to_string_lossy();
333            path_str == "/workspace" || path_str == "/workspace/bad_package"
334        });
335
336        mock.expect_read_cargo_toml().returning(|dir| {
337            let path_str = dir.to_string_lossy();
338            if path_str == "/workspace" {
339                Ok("[workspace]\nmembers = [\"bad_package\"]\n".to_string())
340            } else if path_str == "/workspace/bad_package" {
341                // Return malformed TOML.
342                Ok("[package\nname = \"bad\"\n".to_string())
343            } else {
344                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
345            }
346        });
347
348        mock.expect_is_file()
349            .returning(|path| path.to_string_lossy().ends_with(".rs"));
350
351        mock.expect_exists().returning(|_| true);
352
353        mock.expect_canonicalize()
354            .returning(|path| Ok(path.to_path_buf()));
355
356        let fs = FilesystemFacade::from_mock(mock);
357
358        let context = WorkspaceContext {
359            absolute_target_path: PathBuf::from("/workspace/bad_package/src/lib.rs"),
360            workspace_root: PathBuf::from("/workspace"),
361        };
362
363        let result = detect_package(&context, &fs);
364
365        assert!(result.is_err());
366        let error_msg = result.unwrap_err().to_string();
367        assert!(
368            error_msg.contains("TOML") || error_msg.contains("parse"),
369            "Expected TOML parse error, got: {error_msg}"
370        );
371    }
372
373    #[test]
374    fn mock_package_without_name_field() {
375        let mut mock = MockFilesystem::new();
376
377        mock.expect_current_dir()
378            .returning(|| Ok(PathBuf::from("/workspace")));
379
380        mock.expect_cargo_toml_exists().returning(|dir| {
381            let path_str = dir.to_string_lossy();
382            path_str == "/workspace" || path_str == "/workspace/nameless"
383        });
384
385        mock.expect_read_cargo_toml().returning(|dir| {
386            let path_str = dir.to_string_lossy();
387            if path_str == "/workspace" {
388                Ok("[workspace]\nmembers = [\"nameless\"]\n".to_string())
389            } else if path_str == "/workspace/nameless" {
390                // Valid TOML but missing package name.
391                Ok("[package]\nversion = \"0.1.0\"\n".to_string())
392            } else {
393                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
394            }
395        });
396
397        mock.expect_is_file()
398            .returning(|path| path.to_string_lossy().ends_with(".rs"));
399
400        mock.expect_exists().returning(|_| true);
401
402        mock.expect_canonicalize()
403            .returning(|path| Ok(path.to_path_buf()));
404
405        let fs = FilesystemFacade::from_mock(mock);
406
407        let context = WorkspaceContext {
408            absolute_target_path: PathBuf::from("/workspace/nameless/src/lib.rs"),
409            workspace_root: PathBuf::from("/workspace"),
410        };
411
412        let result = detect_package(&context, &fs);
413
414        assert!(result.is_err());
415        assert!(
416            result
417                .unwrap_err()
418                .to_string()
419                .contains("Could not find package name")
420        );
421    }
422
423    #[test]
424    fn mock_nested_package_detection() {
425        // Test that we find the nearest package, not the workspace root.
426        let mut mock = MockFilesystem::new();
427
428        mock.expect_current_dir()
429            .returning(|| Ok(PathBuf::from("/workspace")));
430
431        mock.expect_cargo_toml_exists().returning(|dir| {
432            let path_str = dir.to_string_lossy();
433            path_str == "/workspace"
434                || path_str == "/workspace/crates/inner"
435                || path_str == "/workspace/crates"
436        });
437
438        mock.expect_read_cargo_toml().returning(|dir| {
439            let path_str = dir.to_string_lossy();
440            if path_str == "/workspace" {
441                Ok("[workspace]\nmembers = [\"crates/*\"]\n".to_string())
442            } else if path_str == "/workspace/crates/inner" {
443                Ok("[package]\nname = \"inner-package\"\nversion = \"0.1.0\"\n".to_string())
444            } else {
445                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
446            }
447        });
448
449        mock.expect_is_file()
450            .returning(|path| path.to_string_lossy().ends_with(".rs"));
451
452        mock.expect_exists().returning(|_| true);
453
454        mock.expect_canonicalize()
455            .returning(|path| Ok(path.to_path_buf()));
456
457        let fs = FilesystemFacade::from_mock(mock);
458
459        let context = WorkspaceContext {
460            absolute_target_path: PathBuf::from("/workspace/crates/inner/src/lib.rs"),
461            workspace_root: PathBuf::from("/workspace"),
462        };
463
464        let result = detect_package(&context, &fs).unwrap();
465
466        assert_eq!(
467            result,
468            DetectedPackage::Package("inner-package".to_string())
469        );
470    }
471
472    #[test]
473    fn mock_directory_target_instead_of_file() {
474        let mock = create_simple_workspace_mock();
475        let fs = FilesystemFacade::from_mock(mock);
476
477        // Target is a directory, not a file.
478        let context = WorkspaceContext {
479            absolute_target_path: PathBuf::from("/workspace/package_a/src"),
480            workspace_root: PathBuf::from("/workspace"),
481        };
482
483        let result = detect_package(&context, &fs).unwrap();
484
485        assert_eq!(result, DetectedPackage::Package("package_a".to_string()));
486    }
487
488    #[test]
489    fn mock_current_dir_outside_workspace() {
490        let mut mock = MockFilesystem::new();
491
492        mock.expect_current_dir()
493            .returning(|| Ok(PathBuf::from("/some/random/path")));
494
495        mock.expect_cargo_toml_exists().returning(|_| false);
496
497        let fs = FilesystemFacade::from_mock(mock);
498
499        let result = validate_workspace_context(Path::new("file.rs"), &fs);
500
501        assert!(result.is_err());
502        assert!(
503            result
504                .unwrap_err()
505                .to_string()
506                .contains("not within a Cargo workspace")
507        );
508    }
509
510    #[test]
511    fn mock_current_dir_fails() {
512        let mut mock = MockFilesystem::new();
513
514        mock.expect_current_dir().returning(|| {
515            Err(io::Error::new(
516                io::ErrorKind::PermissionDenied,
517                "access denied",
518            ))
519        });
520
521        let fs = FilesystemFacade::from_mock(mock);
522
523        let result = validate_workspace_context(Path::new("file.rs"), &fs);
524
525        result.unwrap_err();
526    }
527
528    #[test]
529    fn mock_detect_package_reaches_filesystem_root() {
530        // This tests the case where try_get_parent() returns None because we have walked
531        // up to the filesystem root. We simulate this by having a workspace at the root
532        // and a target file directly in the root - when we try to get parent of root, we get None.
533        let mut mock = MockFilesystem::new();
534
535        mock.expect_is_file()
536            .returning(|path| path.to_string_lossy() == "/file.rs");
537
538        // No Cargo.toml exists anywhere except at root (which is the workspace root).
539        mock.expect_cargo_toml_exists()
540            .returning(|dir| dir.to_string_lossy() == "/");
541
542        mock.expect_read_cargo_toml().returning(|dir| {
543            if dir.to_string_lossy() == "/" {
544                Ok("[workspace]\nmembers = []\n".to_string())
545            } else {
546                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
547            }
548        });
549
550        let fs = FilesystemFacade::from_mock(mock);
551
552        // Create a context where the file is at root level and workspace is root.
553        // The parent of "/" is None, so try_get_parent will return None.
554        let context = WorkspaceContext {
555            absolute_target_path: PathBuf::from("/file.rs"),
556            workspace_root: PathBuf::from("/"),
557        };
558
559        // Since the file is at root and there is no package-level Cargo.toml (only workspace),
560        // and we will hit None from try_get_parent when trying to go above root,
561        // detect_package should return Workspace.
562        let result = detect_package(&context, &fs).unwrap();
563
564        assert_eq!(result, DetectedPackage::Workspace);
565    }
566}