summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: 02c0b461a03da31866c35cd3b39a5f4ed8ef1dfa (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::fs;
use std::io::{Read, Write};
use std::path::PathBuf;

use directories::ProjectDirs;

const ORGANIZATION: &str = "jhspetersson";
const APPLICATION: &str = "fselect";
const CONFIG_FILE: &str = "config.toml";

macro_rules! vec_of_strings {
    ($($str:literal),*) => {
        vec![
            $(String::from($str)),*
        ]
    }
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Config {
    pub no_color : Option<bool>,
    pub gitignore: Option<bool>,
    pub hgignore: Option<bool>,
    pub dockerignore: Option<bool>,
    pub is_zip_archive : Vec<String>,
    pub is_archive : Vec<String>,
    pub is_audio : Vec<String>,
    pub is_book : Vec<String>,
    pub is_doc : Vec<String>,
    pub is_image : Vec<String>,
    pub is_source : Vec<String>,
    pub is_video : Vec<String>,
    pub default_file_size_format : Option<String>,
    pub check_for_updates: Option<bool>,
    #[serde(skip_serializing, default = "get_false")]
    pub debug : bool,
    #[serde(skip)]
    save : bool,
}

fn get_false() -> bool {
    false
}

impl Config {
    pub fn new() -> Result<Config, String> {
        let mut config_file;

        if let Some(cf) = Self::get_current_dir_config() {
            config_file = cf;
        } else {
            let config_dir = Self::get_project_dir();

            if config_dir.is_none() {
                return Ok(Config::default());
            }

            config_file = config_dir.unwrap();
            config_file.push(CONFIG_FILE);

            if !config_file.exists() {
                return Ok(Config::default());
            }
        }

        Config::from(config_file)
    }

    pub fn from(config_file: PathBuf) -> Result<Config, String> {
        if let Ok(mut file) = fs::File::open(&config_file) {
            let mut contents = String::new();
            if let Ok(_) = file.read_to_string(&mut contents) {
                match toml::from_str(&contents) {
                    Ok(config) => Ok(config),
                    Err(err) => Err(err.to_string())
                }
            } else {
                Err("Could not read config file. Using default settings.".to_string())
            }
        } else {
            Err("Could not open config file. Using default settings.".to_string())
        }
    }

    fn get_current_dir_config() -> Option<PathBuf> {
        if let Ok(mut pb) = std::env::current_exe() {
            pb.pop();
            pb.push(CONFIG_FILE);
            if pb.exists() {
                return Some(pb);
            }
        }

        None
    }

    #[cfg(not(windows))]
    fn get_project_dir() -> Option<PathBuf> {
        match ProjectDirs::from("", ORGANIZATION, APPLICATION) {
            Some(pd) => Some(pd.config_dir().to_path_buf()),
            _ => None
        }
    }

    #[cfg(windows)]
    fn get_project_dir() -> Option<PathBuf> {
        match ProjectDirs::from("", ORGANIZATION, APPLICATION) {
            Some(pd) => Some(pd.config_dir().parent().unwrap().to_path_buf()),
            _ => None
        }
    }

    pub fn save(&self) {
        if !self.save {
            return;
        }

        let config_dir = Self::get_project_dir();

        if config_dir.is_none() {
            return;
        }

        let mut config_file = config_dir.unwrap();
        let _ = fs::create_dir_all(&config_file);
        config_file.push(CONFIG_FILE);

        if config_file.exists() {
            return;
        }

        let toml = toml::to_string_pretty(&self).unwrap();

        if let Ok(mut file) = fs::File::create(&config_file) {
            let _ = file.write_all(&toml.as_bytes());
        }
    }

    pub fn default() -> Config {
        Config {
            no_color : Some(false),
            gitignore : Some(false),
            hgignore : Some(false),
            dockerignore : Some(false),
            is_zip_archive : vec_of_strings![".zip", ".jar", ".war", ".ear"],
            is_archive : vec_of_strings![".7z", ".bz2", ".bzip2", ".gz", ".gzip", ".lz", ".rar", ".tar", ".xz", ".zip"],
            is_audio : vec_of_strings![".aac", ".aiff", ".amr", ".flac", ".gsm", ".m4a", ".m4b", ".m4p", ".mp3", ".ogg", ".wav", ".wma"],
            is_book : vec_of_strings![".azw3", ".chm", ".djv", ".djvu", ".epub", ".fb2", ".mobi", ".pdf"],
            is_doc : vec_of_strings![".accdb", ".doc", ".docm", ".docx", ".dot", ".dotm", ".dotx", ".mdb", ".odp", ".ods", ".odt", ".pdf", ".potm", ".potx", ".ppt", ".pptm", ".pptx", ".rtf", ".xlm", ".xls", ".xlsm", ".xlsx", ".xlt", ".xltm", ".xltx", ".xps"],
            is_image : vec_of_strings![".bmp", ".exr", ".gif", ".heic", ".jpeg", ".jpg", ".jxl", ".png", ".psb", ".psd",  ".svg", ".tga", ".tiff", ".webp"],
            is_source : vec_of_strings![".asm", ".bas", ".c", ".cc", ".ceylon", ".clj", ".coffee", ".cpp", ".cs", ".d", ".dart", ".elm", ".erl", ".go", ".gradle", ".groovy", ".h", ".hh", ".hpp", ".java", ".jl", ".js", ".jsp", ".jsx", ".kt", ".kts", ".lua", ".nim", ".pas", ".php", ".pl", ".pm", ".py", ".rb", ".rs", ".scala", ".sol", ".swift", ".tcl", ".ts", ".tsx", ".vala", ".vb", ".zig"],
            is_video : vec_of_strings![".3gp", ".avi", ".flv", ".m4p", ".m4v", ".mkv", ".mov", ".mp4", ".mpeg", ".mpg", ".webm", ".wmv"],
            default_file_size_format : Some(String::new()),
            check_for_updates : Some(false),
            debug : false,
            save : true,
        }
    }
}

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

    #[test]
    fn default_config() {
        let config = Config::default();

        assert!(config.is_source.contains(&String::from(".rs")));
    }
}