Use readers/writers more extensively.

This commit is contained in:
Nicolás A. Ortega Froysa 2022-07-18 14:30:04 +02:00
parent 0eb8ad8065
commit 179cbc144a

View File

@ -17,15 +17,14 @@
*/ */
use std::path::PathBuf; use std::path::PathBuf;
use std::fs::{File, OpenOptions}; use std::fs::OpenOptions;
use std::io::{BufReader, BufRead, Write}; use std::io::{BufReader, BufWriter};
use crate::habit::Habit; use crate::habit::Habit;
pub struct HabitMgr pub struct HabitMgr
{ {
habits:Vec<Habit>, habits:Vec<Habit>,
//data_dir:PathBuf,
habits_path:PathBuf, habits_path:PathBuf,
} }
@ -34,56 +33,65 @@ impl HabitMgr
pub fn new(data_dir:&PathBuf) -> Self pub fn new(data_dir:&PathBuf) -> Self
{ {
let habits_path:PathBuf = data_dir.clone().join("active_habits.json"); let habits_path:PathBuf = data_dir.clone().join("active_habits.json");
/*
* There may be a way of simplifying this, but the idea is that if we try
* to read the file without any JSON code in it then we'll get an error.
* This code avoids said error.
*/
if !habits_path.is_file() if !habits_path.is_file()
{ {
File::create(&habits_path) println!("First launch: creating files.");
let habits_file = OpenOptions::new()
.create(true)
.write(true)
.open(&habits_path)
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
panic!("Error creating file {}:\n{}", panic!("Error creating file {}:\n{}",
habits_path.display(), e); habits_path.display(), e);
}); });
let habit_writer = BufWriter::new(&habits_file);
serde_json::to_writer(habit_writer, &Vec::<Habit>::new())
.unwrap_or_else(|e| {
panic!("Error writing to file {}:\n{}",
habits_path.display(), e);
});
} }
Self Self
{ {
habits: Vec::new(), habits: Vec::new(),
//data_dir: data_dir.clone(),
habits_path, habits_path,
} }
} }
fn import_habits(&mut self) fn import_habits(&mut self)
{ {
let habits_file = File::open(&self.habits_path) let habits_file = OpenOptions::new()
.read(true)
.open(&self.habits_path)
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
panic!("Error opening file {}:\n{}", self.habits_path.display(), e); panic!("Error opening file {}:\n{}", self.habits_path.display(), e);
}); });
let reader = BufReader::new(&habits_file); let habits_reader = BufReader::new(&habits_file);
// TODO: figure out a way to do this with from_reader() instead to simplify self.habits = serde_json::from_reader(habits_reader).unwrap();
//habits = serde_json::from_reader(reader).unwrap();
for (_i, line) in reader.lines().enumerate()
{
let habit:Habit = serde_json::from_str(line.unwrap().as_str()).unwrap();
self.habits.push(habit);
}
} }
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)
{ {
// TODO: Refractor so perhaps we import habits first and then export them self.import_habits();
let mut habits_file = OpenOptions::new() let habits_file = OpenOptions::new()
.append(true) .truncate(true)
.write(true)
.open(&self.habits_path) .open(&self.habits_path)
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
panic!("Error opening file {}:\n{}", self.habits_path.display(), e); panic!("Error opening file {}:\n{}", self.habits_path.display(), e);
}); });
let habit = Habit::new(name.clone(), bad, weight); self.habits.push(Habit::new(name.clone(), bad, weight));
let mut habit_string = serde_json::to_string(&habit).unwrap(); let habits_writer = BufWriter::new(habits_file);
habit_string.push_str("\n"); serde_json::to_writer(habits_writer, &self.habits)
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);
}); });
println!("New habit {} added.", &name); println!("New habit {} added.", &name);