ytil_sys/
dir.rs

1use std::path::Path;
2use std::path::PathBuf;
3
4use color_eyre::eyre::OptionExt as _;
5
6/// Builds a path starting from the home directory by appending the given parts, returning a [`PathBuf`].
7///
8/// # Errors
9/// - The home directory cannot be determined.
10pub fn build_home_path<P: AsRef<Path>>(parts: &[P]) -> color_eyre::Result<PathBuf> {
11    let home_path = std::env::home_dir().ok_or_eyre("missing home dir | env=HOME")?;
12    Ok(build_path(home_path, parts))
13}
14
15/// Builds a path by appending multiple parts to a root path.
16pub fn build_path<P: AsRef<Path>>(mut root: PathBuf, parts: &[P]) -> PathBuf {
17    for part in parts {
18        root.push(part);
19    }
20    root
21}
22
23/// Resolve workspace root directory.
24///
25/// Ascends three levels from this crate's manifest.
26///
27/// # Errors
28/// - Directory traversal fails (unexpected layout).
29pub fn get_workspace_root() -> color_eyre::Result<PathBuf> {
30    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
31    Ok(manifest_dir
32        .parent()
33        .and_then(|p| p.parent())
34        .and_then(|p| p.parent())
35        .ok_or_eyre(format!(
36            "cannot get workspace root | manifest_dir={}",
37            manifest_dir.display()
38        ))?
39        .to_path_buf())
40}