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
use std::{fs::create_dir_all, path::PathBuf};
use crate::{errors::DiaryError, Config};
pub struct InitOptions {
pub path: PathBuf,
}
enum InitStatus {
UseConfig(PathBuf),
UseOpt(PathBuf),
}
fn establish_path(opts: &InitOptions, config: &Config) -> Result<InitStatus, DiaryError> {
if config.diary_path() != &PathBuf::from("") {
if config.diary_path().exists() {
Err(DiaryError::ExistsElsewhere)
} else {
Ok(InitStatus::UseConfig(config.diary_path().clone()))
}
} else {
let diary_path = opts.path.join("diary");
if diary_path.exists() {
return Err(DiaryError::ExistsHere);
}
Ok(InitStatus::UseOpt(diary_path))
}
}
pub fn init(opts: &InitOptions, config: &Config) -> Result<PathBuf, DiaryError> {
let init_status = establish_path(opts, config);
let path = match init_status? {
InitStatus::UseConfig(path) => {
print!("It appears the config file already has a diary path set. ");
println!("Creating a diary folder here: {:?}", path);
path
}
InitStatus::UseOpt(path) => {
println!("Creating a diary folder.");
path
}
};
match create_dir_all(&path) {
Ok(_) => Ok(path),
Err(e) => Err(DiaryError::from(e)),
}
}
#[cfg(test)]
mod tests {
use std::fs::create_dir_all;
use tempfile::tempdir;
use crate::Config;
use super::{init, InitOptions};
#[test]
fn blank_config_valid_path() {
let dir = tempdir().unwrap().path().to_path_buf();
let diary_dir = dir.join("diary");
let opts = InitOptions { path: dir };
let config = Config::default();
init(&opts, &config).unwrap();
assert!(diary_dir.exists());
}
#[test]
fn blank_config_invalid_path() {
let dir = tempdir().unwrap().path().to_path_buf();
let diary_dir = dir.join("diary");
let opts = InitOptions { path: dir };
let config = Config::default();
create_dir_all(diary_dir).unwrap();
init(&opts, &config).expect_err("No error produced.");
}
#[test]
fn filled_config_non_existing_path() {
let dir = tempdir().unwrap().path().to_path_buf();
let diary_dir = dir.join("diary");
let config = Config::new(diary_dir.clone(), String::from("diary"));
let other_dir = tempdir().unwrap().path().to_path_buf();
let opts = InitOptions { path: other_dir };
init(&opts, &config).unwrap();
assert!(diary_dir.exists());
}
#[test]
fn filled_config_existing_path() {
let dir = tempdir().unwrap().path().to_path_buf();
let diary_dir = dir.join("diary");
let config = Config::new(diary_dir.clone(), String::from("diary"));
let other_dir = tempdir().unwrap().path().to_path_buf();
let opts = InitOptions { path: other_dir };
create_dir_all(diary_dir).unwrap();
init(&opts, &config).expect_err("No error produced.");
}
}