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
use ayun_core::{errors::ContainerError, traits::InstanceTrait, Container, Result};

#[derive(Debug)]
pub struct Path {
    inner: std::path::PathBuf,
}

impl InstanceTrait for Path {
    fn register(_: &Container) -> Result<Self, ContainerError>
    where
        Self: Sized,
    {
        let base_path = std::env::var("CARGO_MANIFEST_DIR")
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|_| {
                std::env::current_dir()
                    .expect("project directory does not exist or permissions are insufficient")
            });

        Ok(Self::new(base_path))
    }
}

impl Path {
    fn new(path: std::path::PathBuf) -> Self {
        Self { inner: path }
    }

    pub fn base(&self, path: &str) -> std::path::PathBuf {
        self.inner.join(path)
    }
}

impl std::ops::Deref for Path {
    type Target = std::path::PathBuf;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl std::fmt::Display for Path {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.to_string_lossy().fmt(f)
    }
}

pub fn base_path(str: &str) -> Result<std::path::PathBuf> {
    Ok(ayun_core::app().resolve::<Path>()?.base(str))
}