Refractor file writing and implement delete feature.

This commit is contained in:
Nicolás A. Ortega Froysa 2022-07-18 14:56:26 +02:00
parent 179cbc144a
commit 3561fe27b9
2 changed files with 23 additions and 7 deletions

View File

@ -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();

View File

@ -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!(),
},
}