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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//! etc source
use crate::{Error, Meta, Tree};
use std::{
    convert::{From, Into},
    fs,
    path::{Path, PathBuf},
};

/// contains dir and file
pub struct Etc(PathBuf);

impl Etc {
    /// Abstract an etc dir
    pub fn new<P>(root: P) -> Result<Etc, Error>
    where
        P: AsRef<Path> + Sized,
    {
        if !root.as_ref().exists() {
            fs::create_dir_all(&root)?;
        }

        let mut perms = fs::metadata(&root)?.permissions();
        if perms.readonly() {
            perms.set_readonly(false);
        }

        Ok(Etc(root.as_ref().to_path_buf()))
    }

    /// Convert `Etc` to `Tree`
    pub fn tree(self) -> Result<Tree, Error> {
        Tree::batch(self)
    }
}

impl Meta for Etc {
    fn real_path(&self) -> Result<PathBuf, Error> {
        Ok(self.0.to_owned())
    }
}

impl<'e> Meta for &Etc {
    fn real_path(&self) -> Result<PathBuf, Error> {
        Ok(self.0.to_owned())
    }
}

impl<'e> Meta for &mut Etc {
    fn real_path(&self) -> Result<PathBuf, Error> {
        Ok(self.0.to_owned())
    }
}

impl<P> From<P> for Etc
where
    P: AsRef<Path> + Sized,
{
    fn from(p: P) -> Etc {
        Etc(p.as_ref().to_path_buf())
    }
}

impl Into<String> for Etc {
    fn into(self) -> String {
        self.name().unwrap_or_else(|_| "".to_string())
    }
}