polykit_core/
path_utils.rs

1//! Shared path utilities for package discovery.
2
3use std::path::Path;
4
5/// Converts a file path to its corresponding package name.
6///
7/// This function extracts the package name from a file path relative to
8/// the packages directory. It handles both direct file paths and paths
9/// to polykit.toml configuration files.
10///
11/// # Arguments
12///
13/// * `file_path` - The file path to convert
14/// * `packages_dir` - The base packages directory
15///
16/// # Returns
17///
18/// Returns `Some(package_name)` if a package can be determined, `None` otherwise.
19pub fn file_to_package(file_path: &Path, packages_dir: &Path) -> Option<String> {
20    let relative = file_path.strip_prefix(packages_dir).ok()?;
21
22    for component in relative.components() {
23        if let std::path::Component::Normal(name) = component {
24            let name_str = name.to_string_lossy();
25            if name_str == "polykit.toml" {
26                return relative
27                    .parent()
28                    .and_then(|p| p.components().next())
29                    .and_then(|c| {
30                        if let std::path::Component::Normal(n) = c {
31                            Some(n.to_string_lossy().to_string())
32                        } else {
33                            None
34                        }
35                    });
36            }
37        }
38    }
39
40    relative.components().next().and_then(|c| {
41        if let std::path::Component::Normal(n) = c {
42            Some(n.to_string_lossy().to_string())
43        } else {
44            None
45        }
46    })
47}