Move imports to respective functions.

This commit is contained in:
Nicolás A. Ortega Froysa 2022-07-12 23:49:38 +02:00
parent e65563c824
commit 80ac11462c
2 changed files with 49 additions and 27 deletions

View File

@ -17,7 +17,7 @@
*/
use std::path::PathBuf;
use std::fs::File;
use std::fs::{File, OpenOptions};
use std::io::{BufReader, BufRead};
use crate::habit::Habit;
@ -25,39 +25,72 @@ use crate::habit::Habit;
pub struct HabitMgr
{
habits:Vec<Habit>,
data_dir:PathBuf,
}
impl HabitMgr
{
pub fn new(actives_p:&PathBuf) -> Self
pub fn new(data_dir:&PathBuf) -> Self
{
let actives_f = File::open(&actives_p)
Self
{
habits: Vec::new(),
data_dir: data_dir.clone(),
}
}
fn import_habits(&mut self)
{
// TODO: move habits_path to new function to avoid redundant code
let habits_path:PathBuf = self.data_dir.clone().join("active_habits.json");
if !habits_path.is_file()
{
File::create(&habits_path)
.unwrap_or_else(|e| {
panic!("Error creating file {}:\n{}",
habits_path.display(), e)
});
}
let habits_file = File::open(&habits_path)
.unwrap_or_else(|e| {
panic!("Error opening file {}:\n{}", actives_p.display(), e);
panic!("Error opening file {}:\n{}", habits_path.display(), e);
});
let reader = BufReader::new(&actives_f);
//let imports:Vec<Habit> = serde_json::from_reader(reader).unwrap();
let mut imports:Vec<Habit> = Vec::new();
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();
imports.push(habit);
}
Self
{
habits: imports,
self.habits.push(habit);
}
}
pub fn add(&mut self, name:String, bad:bool, weight:u8, _days:String)
{
self.habits.push(Habit::new(name, bad, weight));
let habits_path:PathBuf = self.data_dir.clone().join("active_habits.json");
if !habits_path.is_file()
{
File::create(&habits_path)
.unwrap_or_else(|e| {
panic!("Error creating file {}:\n{}",
habits_path.display(), e)
});
}
let habits_file = OpenOptions::new()
.write(true)
.append(true)
.open(&habits_path)
.unwrap_or_else(|e| {
panic!("Error opening file {}:\n{}", habits_path.display(), e);
});
let habit = Habit::new(name, bad, weight);
}
pub fn list(&self, all:bool, verbose:bool)
pub fn list(&mut self, all:bool, verbose:bool)
{
self.import_habits();
for i in &self.habits
{
println!("{}", i.get_name());

View File

@ -21,7 +21,6 @@ use structopt::clap::AppSettings;
use std::env;
use std::path::PathBuf;
use std::fs;
use std::fs::File;
mod habit;
mod habitmgr;
@ -91,17 +90,7 @@ fn main()
.unwrap_or_else(|e| { panic!("Filesystem error: {}", e) });
}
let actives_p:PathBuf = data_dir.clone().join("active_habits.json");
if !actives_p.is_file()
{
File::create(&actives_p)
.unwrap_or_else(|e| {
panic!("Error creating file {}:\n{}",
actives_p.display(), e)
});
}
let mut hmgr = HabitMgr::new(&actives_p);
let mut hmgr = HabitMgr::new(&data_dir);
match opts.cmd
{