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
//! This module deals with creating files and editing them.

pub mod edit;
use std::env;
use std::fs;
use std::path;

// todo: make readable names

/// All necessary filepaths' storage.
#[derive(Debug, PartialEq)]
pub struct FilePaths {
    folder_path: String,
    config_path: String,
    password_path: String,
}

impl FilePaths {
    /// Generate filepaths.
    pub fn default() -> Self {
        #[cfg(target_os = "linux")]
        let folder_path: String = format!("{}/.config/pash", env::var("HOME").unwrap());
        #[cfg(target_os = "windows")]
        let folder_path: String = format!("{}/pash", env::var("APPDATA").unwrap());

        let config_path: String = format!("{}/config.toml", folder_path);
        let password_path: String = format!("{}/passwords.toml", folder_path);

        Self {
            folder_path,
            config_path,
            password_path,
        }
    }

    /// Create files in default filepaths if not exist.
    pub fn init() {
        let list = Self::default();
        let (config_exists, passwords_exist) = (
            path::Path::new(&list.config_path).exists(),
            path::Path::new(&list.password_path).exists(),
        );

        fs::create_dir_all(list.folder_path).expect("Failed to init pash directory");

        if !config_exists && !passwords_exist {
            fs::File::create(list.config_path).expect("Failed to init config file");
            fs::File::create(list.password_path).expect("Failed to init passwords file");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_file_paths() {
        assert_eq!(
            Files(
                format!("{}/.config/pash", env::var("HOME").unwrap()),
                format!("{}/.config/pash/config.toml", env::var("HOME")),
                format!("{}/.config/pash/passwords.toml", env::var("HOME"))
            ),
            Files::default()
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_file_paths() {
        assert_eq!(
            FilePaths {
                folder_path: format!("{}/pash", env::var("APPDATA").unwrap()),
                config_path: format!("{}/pash/config.toml", env::var("APPDATA").unwrap()),
                password_path: format!("{}/pash/passwords.toml", env::var("APPDATA").unwrap())
            },
            FilePaths::default()
        );
    }
}