aboutsummaryrefslogtreecommitdiffstats
path: root/src/dirs.rs
blob: 937cfcbe87c97dd863d0c296a0995d749eb8d464 (plain) (blame)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use crate::prelude::*;

pub struct Dirs {
    project_dirs: Option<directories::ProjectDirs>,
}

impl Dirs {
    pub fn new() -> Self {
        Self {
            project_dirs: directories::ProjectDirs::from("", "", "teleterm"),
        }
    }

    pub fn create_all(&self) -> Result<()> {
        if let Some(filename) = self.data_dir() {
            std::fs::create_dir_all(filename).with_context(|| {
                crate::error::CreateDir {
                    filename: filename.to_string_lossy(),
                }
            })?;
        }
        Ok(())
    }

    fn global_config_dir(&self) -> &std::path::Path {
        std::path::Path::new("/etc/teleterm")
    }

    fn config_dir(&self) -> Option<&std::path::Path> {
        self.project_dirs
            .as_ref()
            .map(directories::ProjectDirs::config_dir)
    }

    pub fn config_file(
        &self,
        name: &str,
        must_exist: bool,
    ) -> Option<std::path::PathBuf> {
        if let Some(config_dir) = self.config_dir() {
            let file = config_dir.join(name);
            if !must_exist || file.exists() {
                return Some(file);
            }
        }

        let file = self.global_config_dir().join(name);
        if !must_exist || file.exists() {
            return Some(file);
        }

        None
    }

    fn global_data_dir(&self) -> &std::path::Path {
        std::path::Path::new("/var/lib/teleterm")
    }

    fn data_dir(&self) -> Option<&std::path::Path> {
        self.project_dirs
            .as_ref()
            .map(directories::ProjectDirs::data_dir)
    }

    pub fn data_file(
        &self,
        name: &str,
        must_exist: bool,
    ) -> Option<std::path::PathBuf> {
        if let Some(data_dir) = self.data_dir() {
            let file = data_dir.join(name);
            if !must_exist || file.exists() {
                return Some(file);
            }
        }

        let file = self.global_data_dir().join(name);
        if !must_exist || file.exists() {
            return Some(file);
        }

        None
    }
}