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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
//! Configuration file definition
//!
//! # Examples
//!
//! ```rust
//! use timelog::{Config, Entry, Result};
//!
//! # fn main() -> Result<()> {
//! # let events: Vec<Entry> = vec![];
//! # let mut event_iter = events.into_iter();
//! let conf = Config::from_file("~/.timelogrc")?;
//!
//! println!("Dir: {}", conf.dir());
//! println!("Logfile: {}", conf.logfile());
//! println!("Editor: {}", conf.editor());
//! #   Ok(())
//! #  }
//! ```
//!
//! # Description
//!
//! The [`Config`] struct represents the configuration file information.

use std::cmp::PartialEq;
use std::collections::HashMap;
use std::env;
use std::fmt::Debug;
use std::fs::{canonicalize, OpenOptions};
use std::io::prelude::*;
use std::io::BufWriter;
use std::path::PathBuf;

use configparser::ini::Ini;
use lazy_static::lazy_static;
use tilde_expand::tilde_expand;

#[doc(inline)]
use crate::error::PathError;
use crate::Result;

lazy_static! {
    /// Default path to the timelog config file
    pub static ref DEFAULT_CONF: String = normalize_path("~/.timelogrc").unwrap();
    /// Default path to the timelog log directory
    pub static ref DEFAULT_DIR: String = normalize_path("~/timelog").unwrap();
    /// Default command to open the editor
    pub static ref DEFAULT_EDITOR: String = env::var("VISUAL")
        .or_else(|_| env::var("EDITOR"))
        .unwrap_or_else(|_| String::from("vim"));
}

/// Default command to open the browser
#[cfg(target_os = "macos")]
pub const DEFAULT_BROWSER: &str = "open";

/// Default command to open the browser
#[cfg(not(target_os = "macos"))]
pub const DEFAULT_BROWSER: &str = "chromium-browser";

/// Type specifying the configuration for the timelog program.
#[derive(Clone, Debug, PartialEq)]
pub struct Config {
    /// The name of the configuration file
    configfile: String,
    /// The path of the directory that stores the log and stack files
    dir: String,
    /// The path to the editor used with the `edit` command
    editor: String,
    /// The path to the browser used with the `chart` command
    browser: String,
    /// The default command if none is entered
    defcmd: String,
    /// List of aliases to extend the commands
    aliases: HashMap<String, String>,
}

/// Utility function to handle tilde expansion of a path.
///
/// ## Errors
///
/// - Return a [`PathError::InvalidPath`] if there are invalid characters in the path
pub fn normalize_path(filename: &str) -> std::result::Result<String, PathError> {
    // If this fails, the user directory must contain invalid characters.
    String::from_utf8(tilde_expand(filename.as_bytes()))
        .map_err(|e| PathError::InvalidPath(filename.to_owned(), e.to_string()))
}

// Ensure the filename either exists or could be created in the supplied directory
//
// ## Errors
//
// - Return [`PathError::FilenameMissing`] if the filename does not exist.
// - Return [`PathError::InvalidPath`] if the dirname portion of the file is not valid.
fn ensure_filename(file: &str) -> std::result::Result<String, PathError> {
    if file.is_empty() {
        return Err(PathError::FilenameMissing);
    }
    let mut dir = PathBuf::from(normalize_path(file)?);
    let filename = dir
        .file_name()
        .ok_or(PathError::FilenameMissing)?
        .to_os_string();
    dir.pop();

    let mut candir =
        canonicalize(dir).map_err(|e| PathError::InvalidPath(file.to_owned(), e.to_string()))?;
    candir.push(filename);
    Ok(candir.to_str().unwrap().to_owned())
}

impl Default for Config {
    /// Create a [`Config`] with all of the default parameters.
    ///
    /// ## Panics
    ///
    /// If any of the default valures are not legal in the current system, the code will
    /// panic. These is a programmer-specified defaults, and should never fail.
    fn default() -> Self {
        Self {
            configfile: normalize_path("~/.timelogrc").expect("Invalid config file"),
            dir: normalize_path("~/timelog").expect("Invalid user dir"),
            editor: "vim".into(),
            browser: DEFAULT_BROWSER.into(),
            defcmd: "curr".into(),
            aliases: HashMap::new(),
        }
    }
}

// Utility function for extracting conf data.
fn conf_get<'a>(base: &'a HashMap<String, Option<String>>, key: &'static str) -> Option<&'a str> {
    match base.get(key) {
        Some(Some(val)) => Some(val),
        _ => None,
    }
}

impl Config {
    /// Create a new [`Config`] object with supplied parameters
    ///
    /// ## Errors
    ///
    /// - Return [`PathError::InvalidConfigPath`] if the configuration filename is not valid.
    /// - Return [`PathError::InvalidTimelogPath`] if the timelog directory is not valid.
    pub fn new(
        config: &str, dir: Option<&str>, editor: Option<&str>, browser: Option<&str>,
        cmd: Option<&str>
    ) -> Result<Self> {
        let dir = dir.unwrap_or("~/timelog");
        Ok(Self {
            configfile: normalize_path(config).map_err(|_| PathError::InvalidConfigPath)?,
            dir: normalize_path(dir).map_err(|_| PathError::InvalidTimelogPath)?,
            editor: editor.unwrap_or("vim").into(),
            browser: browser.unwrap_or(DEFAULT_BROWSER).into(),
            defcmd: cmd.unwrap_or("curr").into(),
            aliases: HashMap::new(),
        })
    }

    /// Create a new [`Config`] object from the supplied config file
    ///
    /// ## Errors
    ///
    /// - Return [`PathError::InvalidConfigPath`] if the configuration filename is not valid.
    /// - Return [`PathError::InvalidTimelogPath`] if the timelog directory is not valid.
    /// - Return [`PathError::FileAccess`] if the config file is not accessible.
    pub fn from_file(filename: &str) -> Result<Self> {
        let configfile = ensure_filename(filename)?;
        let mut parser = Ini::new();
        let config = parser
            .load(&configfile)
            .map_err(|e| PathError::FileAccess(configfile.to_owned(), e))?;

        let default = HashMap::new();
        let base = match config.get("default") {
            Some(hash) => hash,
            _ => &default,
        };
        let mut conf = Config::new(
            &configfile,
            conf_get(base, "dir"),
            conf_get(base, "editor"),
            conf_get(base, "browser"),
            conf_get(base, "defcmd"),
        )?;
        if let Some(aliases) = config.get("alias") {
            aliases.iter().for_each(|(k, v)| {
                conf.set_alias(k, v.as_ref().unwrap());
            });
        }

        Ok(conf)
    }

    /// Return a [`String`] containing the name of the config file.
    pub fn configfile(&self) -> &str { self.configfile.as_str() }

    /// Return the path of the directory that stores the log and stack files
    pub fn dir(&self) -> &str { self.dir.as_str() }

    /// Set the path of the directory that stores the log and stack files
    pub fn set_dir(&mut self, dir: &str) { self.dir = dir.to_owned() }

    /// Return the path to the editor used with the `edit` command
    pub fn editor(&self) -> &str { self.editor.as_str() }

    /// Set the path to the editor used with the `edit` command
    pub fn set_editor(&mut self, editor: &str) { self.editor = editor.to_owned() }

    /// The path to the browser used with the `chart` command
    pub fn browser(&self) -> &str { self.browser.as_str() }

    /// The path to the browser used with the `chart` command
    pub fn set_browser(&mut self, browser: &str) { self.browser = browser.to_owned() }

    /// Return the default command if none is entered
    pub fn defcmd(&self) -> &str { self.defcmd.as_str() }

    /// The file containing the timelog entries
    pub fn logfile(&self) -> String { format!("{}/timelog.txt", self.dir) }

    /// The file that holds the stack
    pub fn stackfile(&self) -> String { format!("{}/stack.txt", self.dir) }

    /// The file containing the timelog entries
    pub fn reportfile(&self) -> String { format!("{}/report.html", self.dir) }

    /// Write the configuration to disk in the file specified by the [`Config`]
    ///
    /// ## Errors
    ///
    /// - Return [`PathError::FileAccess`] if we are unable to write the configuration.
    pub fn create(&self) -> std::result::Result<(), PathError> {
        let configfile = self.configfile();
        let file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(configfile)
            .map_err(|e| PathError::FileAccess(configfile.to_string(), e.to_string()))?;
        let mut stream = BufWriter::new(file);

        writeln!(&mut stream, "dir={}", self.dir())
            .map_err(|e| PathError::FileWrite(configfile.to_string(), e.to_string()))?;
        writeln!(&mut stream, "editor={}", self.editor())
            .map_err(|e| PathError::FileWrite(configfile.to_string(), e.to_string()))?;
        writeln!(&mut stream, "browser={}", self.browser())
            .map_err(|e| PathError::FileWrite(configfile.to_string(), e.to_string()))?;
        writeln!(&mut stream, "defcmd={}", self.defcmd())
            .map_err(|e| PathError::FileWrite(configfile.to_string(), e.to_string()))?;

        writeln!(&mut stream, "\n[alias]")
            .map_err(|e| PathError::FileWrite(configfile.to_string(), e.to_string()))?;
        for (key, val) in self.aliases.iter() {
            writeln!(stream, "    {} = {}", key, val)
                .map_err(|e| PathError::FileWrite(configfile.to_string(), e.to_string()))?;
        }

        stream
            .flush()
            .map_err(|e| PathError::FileWrite(configfile.to_string(), e.to_string()))?;
        Ok(())
    }

    /// Return an iterator over the alias names
    pub fn alias_names(&self) -> impl Iterator<Item = &'_ String> { self.aliases.keys() }

    /// Retrieve the value associate with the named alias, if one exists.
    pub fn alias(&self, key: &str) -> Option<&String> { self.aliases.get(key) }

    /// Set the value of the named alias
    fn set_alias(&mut self, name: &str, val: &str) {
        self.aliases.insert(name.to_owned(), val.to_owned());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use spectral::prelude::*;
    use std::fs::File;
    use tempfile::TempDir;

    #[test]
    fn test_default() {
        let config = Config::default();
        assert_that!(config.dir()).is_equal_to(&*normalize_path("~/timelog").unwrap());
        assert_that!(config.logfile())
            .is_equal_to(&normalize_path("~/timelog/timelog.txt").unwrap());
        assert_that!(config.stackfile())
            .is_equal_to(&normalize_path("~/timelog/stack.txt").unwrap());
        assert_that!(config.reportfile())
            .is_equal_to(&normalize_path("~/timelog/report.html").unwrap());
        assert_that!(config.editor()).is_equal_to("vim");
        assert_that!(config.browser()).is_equal_to(DEFAULT_BROWSER);
        assert_that!(config.defcmd()).is_equal_to("curr");
        assert_that!(config.alias_names().count()).is_equal_to(0);
    }

    #[test]
    fn test_new() {
        let config = Config::new(
            "~/.timelogrc", Some("~/timelog"), Some("vim"), Some("chromium-browser"), Some("curr")
        ).expect("Failed to create config");

        assert_that!(config.dir()).is_equal_to(&*normalize_path("~/timelog").unwrap());
        assert_that!(config.logfile())
            .is_equal_to(&normalize_path("~/timelog/timelog.txt").unwrap());
        assert_that!(config.stackfile())
            .is_equal_to(&normalize_path("~/timelog/stack.txt").unwrap());
        assert_that!(config.reportfile())
            .is_equal_to(&normalize_path("~/timelog/report.html").unwrap());
        assert_that!(config.editor()).is_equal_to("vim");
        assert_that!(config.browser()).is_equal_to("chromium-browser");
        assert_that!(config.defcmd()).is_equal_to("curr");
        assert_that!(config.alias_names().count()).is_equal_to(0);
    }

    #[test]
    fn test_from_file_dir_only() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let path = tmpdir.path();
        let path_str = path.to_str().unwrap();

        let filename = format!("{}/.timerc", path_str);
        let mut file = File::create(&filename).unwrap();
        let _ = file.write_all(format!("dir = {}", path_str).as_bytes());

        let config = Config::from_file(&filename).expect("Failed to create config from file");
        let expect_log = normalize_path(format!("{}/timelog.txt", path_str).as_str())
            .expect("Failed to create logfile name");
        let expect_stack = normalize_path(format!("{}/stack.txt", path_str).as_str())
            .expect("Failed to create stackfile name");
        let expect_report = normalize_path(format!("{}/report.html", path_str).as_str())
            .expect("Failed to create report file name");
        assert_that!(config.dir()).is_equal_to(path_str);
        assert_that!(config.logfile()).is_equal_to(&expect_log);
        assert_that!(config.stackfile()).is_equal_to(&expect_stack);
        assert_that!(config.reportfile()).is_equal_to(&expect_report);
        assert_that!(config.editor()).is_equal_to("vim");
        assert_that!(config.browser()).is_equal_to(DEFAULT_BROWSER);
        assert_that!(config.defcmd()).is_equal_to("curr");
        assert_that!(config.alias_names().count()).is_equal_to(0);
    }

    #[test]
    fn test_from_file_base() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let path = tmpdir.path();
        let path_str = path.to_str().unwrap();

        let filename = format!("{}/.timerc", path_str);
        let mut file = File::create(&filename).unwrap();
        let output = format!("dir={}\neditor=nano\nbrowser=firefox\ndefcmd=stop", path_str);
        let _ = file.write_all(output.as_bytes());

        let config = Config::from_file(&filename).expect("Failed to create config");
        let expect_log = normalize_path(format!("{}/timelog.txt", path_str).as_str())
            .expect("Failed to create logfile name");
        let expect_stack = normalize_path(format!("{}/stack.txt", path_str).as_str())
            .expect("Failed to create stackfile name");
        let expect_report = normalize_path(format!("{}/report.html", path_str).as_str())
            .expect("Failed to create report file name");
        assert_that!(config.dir()).is_equal_to(&*normalize_path(path_str).unwrap());
        assert_that!(config.logfile()).is_equal_to(&expect_log);
        assert_that!(config.stackfile()).is_equal_to(&expect_stack);
        assert_that!(config.reportfile()).is_equal_to(&expect_report);
        assert_that!(config.editor()).is_equal_to("nano");
        assert_that!(config.browser()).is_equal_to("firefox");
        assert_that!(config.defcmd()).is_equal_to("stop");
        assert_that!(config.alias_names().count()).is_equal_to(0);
    }

    #[test]
    fn test_from_file_aliases() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let path = tmpdir.path();
        let path_str = path.to_str().unwrap();

        let filename = format!("{}/.timerc", path_str);
        let mut file = File::create(&filename).unwrap();
        let _ = file.write_all(b"[alias]\na=start +play @A\nb=start +work @B");

        let config = Config::from_file(&filename).expect("Failed to create config");
        let mut names: Vec<&String> = config.alias_names().collect();
        names.sort();
        assert_that!(names).is_equal_to(vec![&"a".to_owned(), &"b".to_owned()]);
        assert_that!(config.alias("a"))
            .is_some()
            .is_equal_to(&"start +play @A".to_owned());
        assert_that!(config.alias("b"))
            .is_some()
            .is_equal_to(&"start +work @B".to_owned());
    }
}