~jshsj/rust_todo

ref: f88eef58a9d1867152e6352ad31cc9e789008292 rust_todo/src/tasks.rs -rw-r--r-- 7.2 KiB
f88eef58 — JSH changed vec<Task> to HashMap<String, Task> 1 year, 9 months ago
                                                                                
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
use chrono::{DateTime, Utc};
use serde;
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;
use std::fmt;
use std::fs::{read_dir, remove_file, File};

use failure::Error;

static PATH_PREFIX: &str = "./tasks/";

#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Task {
    pub name: String,
    pub path: String,
    pub sub_tasks: HashMap<String, SubTask>,
    pub done: bool,
    pub due_date: Option<DateTime<Utc>>,
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct SubTask {
    pub name: String,
    pub done: bool,
    pub due_date: Option<DateTime<Utc>>,
}

impl Task {
    fn new(name: String, due_date: Option<DateTime<Utc>>) -> Result<Task, Error> {
        let path = convert_name_to_path(&name);
        let t = Task {
            name,
            path,
            sub_tasks: HashMap::<String, SubTask>::new(),
            done: false,
            due_date,
        };
        t.save()?;
        Ok(t)
    }

    fn add_subtask(&mut self, name: String, due_date: Option<DateTime<Utc>>) -> Result<(), Error> {
        self.sub_tasks
            .insert(name.clone(), SubTask::new(name, due_date));
        self.save()?;
        Ok(())
    }

    fn remove_subtask(&mut self, name: String) -> Result<(), Error> {
        match self.sub_tasks.remove(&name) {
            Some(_t) => Ok(()),
            None => bail!("Task not found"),
        }
    }

    fn save(&self) -> Result<(), Error> {
        let file = File::create(format!("{}{}", PATH_PREFIX, self.path))?;
        serde_json::to_writer(file, &self)?;
        Ok(())
    }

    fn delete(&self) -> Result<(), Error> {
        remove_file(format!("{}{}", PATH_PREFIX, self.path))?;
        Ok(())
    }
}

impl SubTask {
    fn new(name: String, due_date: Option<DateTime<Utc>>) -> SubTask {
        SubTask {
            name,
            done: false,
            due_date,
        }
    }
}

impl fmt::Display for Task {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

impl fmt::Display for SubTask {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

pub struct TaskManager {
    tasklist: HashMap<String, Task>,
}

impl TaskManager {
    pub fn new() -> TaskManager {
        let mut t = TaskManager {
            tasklist: HashMap::<String, Task>::new(),
        };
        t.init();
        t
    }

    pub fn add_task(&mut self, name: String) -> Result<(), Error> {
        self.tasklist.insert(name.clone(), Task::new(name, None)?);
        Ok(())
    }

    pub fn add_task_with_date(
        &mut self,
        name: String,
        due_date: DateTime<Utc>,
    ) -> Result<(), Error> {
        self.tasklist
            .insert(name.clone(), Task::new(name, Some(due_date))?);
        Ok(())
    }

    pub fn add_subtask(&mut self, task_name: String, subtask_name: String) -> Result<(), Error> {
        let task: &mut Task = self.get_task_by_name(task_name)?;
        &task.add_subtask(subtask_name, None)?;
        Ok(())
    }

    pub fn add_substask_with_date(
        &mut self,
        task_name: String,
        subtask_name: String,
        due_date: DateTime<Utc>,
    ) -> Result<(), Error> {
        let task: &mut Task = self.get_task_by_name(task_name)?;
        &task.add_subtask(subtask_name, Some(due_date))?;
        Ok(())
    }

    pub fn remove_subtask(&mut self, task_name: String, subtask_name: String) -> Result<(), Error> {
        let task: &mut Task = self.get_task_by_name(task_name)?;
        &task.remove_subtask(subtask_name)?;
        Ok(())
    }

    fn get_task_by_name(&mut self, task_name: String) -> Result<&mut Task, Error> {
        match self.tasklist.get_mut(&task_name) {
            Some(task) => Ok(&mut *task),
            None => bail!("Task not found"),
        }
        //let tasklist: Vec<Task> = self.tasklist.as_ref();
        //let filtered: Vec<Task> = tasklist.into_iter().filter(|t| t.name == task_name).collect();
    }

    pub fn delete_task(&mut self, task_name: String) -> Result<(), Error> {
        match self.tasklist.get_mut(&task_name) {
            Some(task) => {
                task.delete()?;
                Ok(())
            }
            None => bail!("Task not found"),
        }
    }

    pub fn all_tasks(&mut self) -> &HashMap<String, Task> {
        &self.tasklist
    }

    fn init(&mut self) {
        let task_files = read_task_files();
        for task_file in task_files {
            //let t: Vec<&str> = task_file.split("/").collect();
            //let path = String::from(t[2]);
            &self.load_task(task_file);
        }
    }

    fn load_task(&mut self, path: String) {
        let file = File::open(&path).unwrap();
        let task: Task =
            serde_json::from_reader(file).expect(format!("Can't parse file {}", path).as_str());
        self.tasklist.insert(String::from(task.name.as_str()), task);
    }
}

//HELPERS

fn convert_name_to_path(name: &str) -> String {
    let lowercase = name.to_lowercase();
    let lowercase: Vec<&str> = lowercase.split(" ").collect();

    lowercase.join("_")
}

fn convert_path_to_name(path: &str) -> String {
    String::from("test")
}

fn read_task_files() -> Vec<String> {
    let files = read_dir("./tasks").expect("directory doesn't exist");
    let mut task_files = Vec::<String>::new();

    for file in files {
        task_files.push(String::from(file.unwrap().path().to_str().unwrap()));
    }

    task_files
}

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

    fn setup_test_manager(test: String) -> TaskManager {
        let mut task_manager = TaskManager::new();
        task_manager.add_task(String::from(test)).unwrap();
        task_manager
    }

    fn destroy(test: String) {
        remove_file(format!("./tasks/{}", test)).unwrap();
    }

    #[test]
    fn add_task() {
        let mut task_manager = TaskManager::new();
        let task = Task::new(String::from("Test"), None).unwrap();
        assert!(task_manager.add_task(String::from("Test")).is_ok());
        assert_eq!(
            task.name,
            task_manager
                .get_task_by_name(String::from("Test"))
                .unwrap()
                .name
        );
        destroy(String::from("test"));
    }

    #[test]
    fn add_subtask() {
        let mut manager = setup_test_manager(String::from("add_subtask"));
        assert!(manager
            .add_subtask(String::from("add_subtask"), String::from("Subtask"))
            .is_ok());
        assert!(manager
            .get_task_by_name(String::from("add_subtask"))
            .unwrap()
            .sub_tasks
            .contains_key("Subtask"));

        destroy(String::from("add_subtask"));
    }

    #[test]
    #[should_panic]
    fn add_subtask_to_nonexisting_task() {
        let mut manager = setup_test_manager(String::from("add_subtask_panic"));
        manager
            .add_subtask(String::from("thats not happening"), String::from("SDADA"))
            .unwrap();
        destroy(String::from("add_subtask_panic"));
    }

    #[test]
    fn delete_task() {
        let mut manager = setup_test_manager(String::from("delete_task"));
        manager.add_task(String::from("test_delete")).unwrap();
        assert!(manager.delete_task(String::from("test_delete")).is_ok());
        destroy(String::from("delete_task"));
    }
}