Start reorganizing code by creating files module

This commit is contained in:
Joscha 2021-11-21 22:48:41 +01:00
parent f1ff3f7aaa
commit 5674bcdc00
5 changed files with 232 additions and 16 deletions

59
src/files.rs Normal file
View file

@ -0,0 +1,59 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::{fs, io, result};
use chrono_tz::Tz;
use crate::commands::File;
use crate::parse;
#[derive(Debug)]
pub struct Files {
files: HashMap<PathBuf, File>,
timezone: Option<Tz>,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{0}")]
IoError(#[from] io::Error),
#[error("{0}")]
ParseError(#[from] parse::Error),
}
pub type Result<T> = result::Result<T, Error>;
impl Files {
pub fn load(path: &Path) -> Result<Self> {
let mut new = Self {
files: HashMap::new(),
timezone: None,
};
new.load_file(path)?;
new.determine_timezone()?;
Ok(new)
}
fn load_file(&mut self, path: &Path) -> Result<()> {
let canon_path = path.canonicalize()?;
if self.files.contains_key(&canon_path) {
// We've already loaded this exact file.
return Ok(());
}
let content = fs::read_to_string(path)?;
let file = parse::parse(path, &content)?;
self.files.insert(canon_path, file);
// TODO Also load all imported files
Ok(())
}
fn determine_timezone(&mut self) -> Result<()> {
// TODO Implement once files can specify time zones
Ok(())
}
}

View file

@ -1,13 +1,12 @@
use std::fs;
use std::path::PathBuf;
use chrono::NaiveDate;
use structopt::StructOpt;
use crate::eval::entries::DateRange;
use crate::files::Files;
mod commands;
mod eval;
mod files;
mod format;
mod parse;
@ -19,15 +18,7 @@ pub struct Opt {
fn main() -> anyhow::Result<()> {
let opt = Opt::from_args();
let content = fs::read_to_string(&opt.file)?;
let file = parse::parse(&opt.file, &content)?;
let entries = eval::eval(
&file,
DateRange::new(
NaiveDate::from_ymd(2021, 1, 1),
NaiveDate::from_ymd(2021, 12, 31),
),
)?;
println!("{:#?}", entries);
let files = Files::load(&opt.file)?;
println!("{:#?}", files);
Ok(())
}

View file

@ -2,7 +2,7 @@ use std::path::Path;
use std::result;
use chrono::NaiveDate;
use pest::error::{Error, ErrorVariant};
use pest::error::ErrorVariant;
use pest::iterators::Pair;
use pest::prec_climber::{Assoc, Operator, PrecClimber};
use pest::{Parser, Span};
@ -16,9 +16,10 @@ use crate::commands::{
#[grammar = "parse/todayfile.pest"]
struct TodayfileParser;
type Result<T> = result::Result<T, Error<Rule>>;
pub type Error = pest::error::Error<Rule>;
pub type Result<T> = result::Result<T, Error>;
fn error<S: Into<String>>(span: Span, message: S) -> Error<Rule> {
fn error<S: Into<String>>(span: Span, message: S) -> Error {
Error::new_from_span(
ErrorVariant::CustomError {
message: message.into(),