Improve habit writing to files.

This commit is contained in:
Nicolás A. Ortega Froysa 2022-07-13 23:57:20 +02:00
parent baa2b8c612
commit 0eb8ad8065

View File

@ -18,7 +18,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::{BufReader, BufRead}; use std::io::{BufReader, BufRead, Write};
use crate::habit::Habit; use crate::habit::Habit;
@ -69,8 +69,8 @@ impl HabitMgr
pub fn add(&mut self, name:String, bad:bool, weight:u8, _days:String) pub fn add(&mut self, name:String, bad:bool, weight:u8, _days:String)
{ {
let habits_file = OpenOptions::new() // TODO: Refractor so perhaps we import habits first and then export them
.write(true) let mut habits_file = OpenOptions::new()
.append(true) .append(true)
.open(&self.habits_path) .open(&self.habits_path)
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
@ -78,7 +78,9 @@ impl HabitMgr
}); });
let habit = Habit::new(name.clone(), bad, weight); let habit = Habit::new(name.clone(), bad, weight);
serde_json::to_writer(habits_file, &habit) let mut habit_string = serde_json::to_string(&habit).unwrap();
habit_string.push_str("\n");
habits_file.write_all(habit_string.as_bytes())
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
panic!("Error writing to file {}:\n{}", panic!("Error writing to file {}:\n{}",
self.habits_path.display(), e); self.habits_path.display(), e);