aboutsummaryrefslogtreecommitdiff
path: root/src/app.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/app.rs')
-rw-r--r--src/app.rs58
1 files changed, 36 insertions, 22 deletions
diff --git a/src/app.rs b/src/app.rs
index 2d83714..81a574a 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -2,6 +2,7 @@ use std::default::Default;
2use std::f64; 2use std::f64;
3use std::fs::{File, OpenOptions}; 3use std::fs::{File, OpenOptions};
4use std::io::prelude::*; 4use std::io::prelude::*;
5use std::path::PathBuf;
5 6
6use cursive::direction::{Absolute, Direction}; 7use cursive::direction::{Absolute, Direction};
7use cursive::event::{Event, EventResult, Key}; 8use cursive::event::{Event, EventResult, Key};
@@ -161,34 +162,47 @@ impl App {
161 } 162 }
162 163
163 pub fn load_state() -> Self { 164 pub fn load_state() -> Self {
164 let data_file = utils::data_file(); 165 let (regular_f, auto_f) = (utils::habit_file(), utils::auto_habit_file());
165 if let Ok(ref mut file) = File::open(data_file) { 166 let read_from_file = |file: PathBuf| -> Vec<Box<dyn HabitWrapper>> {
166 let mut j = String::new(); 167 if let Ok(ref mut f) = File::open(file) {
167 file.read_to_string(&mut j); 168 let mut j = String::new();
168 return App { 169 f.read_to_string(&mut j);
169 habits: serde_json::from_str(&j).unwrap(), 170 return serde_json::from_str(&j).unwrap();
170 ..Default::default() 171 } else {
171 }; 172 return Vec::new();
172 } else { 173 }
173 Self::new() 174 };
174 } 175
176 let mut regular = read_from_file(regular_f);
177 let auto = read_from_file(auto_f);
178 regular.extend(auto);
179 return App {
180 habits: regular,
181 ..Default::default()
182 };
175 } 183 }
176 184
177 // this function does IO 185 // this function does IO
178 // TODO: convert this into non-blocking async function 186 // TODO: convert this into non-blocking async function
179 fn save_state(&self) { 187 fn save_state(&self) {
180 let j = serde_json::to_string_pretty(&self.habits).unwrap(); 188 let (regular, auto): (Vec<_>, Vec<_>) = self.habits.iter().partition(|&x| !x.is_auto());
181 let data_file = utils::data_file(); 189 let (regular_f, auto_f) = (utils::habit_file(), utils::auto_habit_file());
182 190
183 match OpenOptions::new() 191 let write_to_file = |data: Vec<&Box<dyn HabitWrapper>>, file: PathBuf| {
184 .write(true) 192 let j = serde_json::to_string_pretty(&data).unwrap();
185 .create(true) 193 match OpenOptions::new()
186 .truncate(true) 194 .write(true)
187 .open(data_file) 195 .create(true)
188 { 196 .truncate(true)
189 Ok(ref mut file) => file.write_all(j.as_bytes()).unwrap(), 197 .open(file)
190 Err(_) => panic!("Unable to write!"), 198 {
199 Ok(ref mut f) => f.write_all(j.as_bytes()).unwrap(),
200 Err(_) => panic!("Unable to write!"),
201 };
191 }; 202 };
203
204 write_to_file(regular, regular_f);
205 write_to_file(auto, auto_f);
192 } 206 }
193 207
194 pub fn parse_command(&mut self, input: &str) { 208 pub fn parse_command(&mut self, input: &str) {