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::fs::{File, OpenOptions};
use std::io::{BufReader, BufRead, Write};
use std::fs::OpenOptions;
use std::io::{BufReader, BufWriter};
use crate::habit::Habit;
pub struct HabitMgr
{
habits:Vec<Habit>,
//data_dir:PathBuf,
habits_path:PathBuf,
}
@ -34,53 +33,62 @@ impl HabitMgr
pub fn new(data_dir:&PathBuf) -> Self
{
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()
{
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| {
panic!("Error creating file {}:\n{}",
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
{
habits: Vec::new(),
//data_dir: data_dir.clone(),
habits_path,
}
}
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| {
panic!("Error opening file {}:\n{}", self.habits_path.display(), e);
});
let reader = BufReader::new(&habits_file);
// TODO: figure out a way to do this with from_reader() instead to simplify
//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);
}
let habits_reader = BufReader::new(&habits_file);
self.habits = serde_json::from_reader(habits_reader).unwrap();
}
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
let mut habits_file = OpenOptions::new()
.append(true)
self.import_habits();
let habits_file = OpenOptions::new()
.truncate(true)
.write(true)
.open(&self.habits_path)
.unwrap_or_else(|e| {
panic!("Error opening file {}:\n{}", self.habits_path.display(), e);
});
let habit = Habit::new(name.clone(), bad, weight);
let mut habit_string = serde_json::to_string(&habit).unwrap();
habit_string.push_str("\n");
habits_file.write_all(habit_string.as_bytes())
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);