diff --git a/src/habitmgr.rs b/src/habitmgr.rs index c3a7165..3833d33 100644 --- a/src/habitmgr.rs +++ b/src/habitmgr.rs @@ -40,7 +40,6 @@ impl HabitMgr */ if !habits_path.is_file() { - println!("First launch: creating files."); let habits_file = OpenOptions::new() .create(true) .write(true) @@ -75,9 +74,8 @@ impl HabitMgr self.habits = serde_json::from_reader(habits_reader).unwrap(); } - pub fn add(&mut self, name:String, bad:bool, weight:u8, _days:String) + fn write_habits(&self) { - self.import_habits(); let habits_file = OpenOptions::new() .truncate(true) .write(true) @@ -85,18 +83,31 @@ impl HabitMgr .unwrap_or_else(|e| { panic!("Error opening file {}:\n{}", self.habits_path.display(), e); }); - - self.habits.push(Habit::new(name.clone(), bad, weight)); let habits_writer = BufWriter::new(habits_file); serde_json::to_writer(habits_writer, &self.habits) .unwrap_or_else(|e| { panic!("Error writing to file {}:\n{}", self.habits_path.display(), e); }); + } + + pub fn add(&mut self, name:String, bad:bool, weight:u8, _days:String) + { + self.import_habits(); + self.habits.push(Habit::new(name.clone(), bad, weight)); + self.write_habits(); println!("New habit {} added.", &name); } + pub fn delete(&mut self, id:usize) + { + self.import_habits(); + let old_habit = self.habits.remove(id); + self.write_habits(); + println!("Removed habit {}", old_habit.get_name()); + } + pub fn list(&mut self, all:bool, verbose:bool) { self.import_habits(); diff --git a/src/main.rs b/src/main.rs index 6c702ac..0ec30a9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -62,8 +62,11 @@ enum Command }, #[structopt(alias = "mod")] Modify { }, - #[structopt(alias = "rm")] - Remove { }, + #[structopt(alias = "del")] + Delete { + #[structopt(help = "ID of the habit to delete")] + id:usize, + }, #[structopt(alias = "stats")] Statistics { }, } @@ -102,6 +105,8 @@ fn main() hmgr.add(name, bad, weight, days), Command::List { all, verbose } => hmgr.list(all, verbose), + Command::Delete { id } => + hmgr.delete(id), _ => todo!(), }, }