Skip to main content

ghpascon_rust/utils/
path.rs

1use std::path::PathBuf;
2
3/// Returns the directory where the current executable is located.
4///
5/// # Errors
6///
7/// Returns an error if the executable path cannot be determined or
8/// if the path has no parent directory.
9///
10/// # Example
11///
12/// ```no_run
13/// use ghpascon_rust::utils::path::get_working_dir;
14///
15/// let dir = get_working_dir().expect("could not determine executable directory");
16/// println!("running from: {}", dir.display());
17/// ```
18pub fn get_working_dir() -> Result<PathBuf, std::io::Error> {
19    let exe = std::env::current_exe()?;
20    exe.parent().map(|p| p.to_path_buf()).ok_or_else(|| {
21        std::io::Error::new(
22            std::io::ErrorKind::NotFound,
23            "executable has no parent directory",
24        )
25    })
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    fn test_returns_existing_directory() {
34        let dir = get_working_dir().expect("get_working_dir failed");
35        assert!(dir.exists(), "directory should exist");
36        assert!(dir.is_dir(), "path should be a directory");
37    }
38}