Skip to content

Commit

Permalink
Missing file is shown in bold red, #82
Browse files Browse the repository at this point in the history
  • Loading branch information
frosklis committed Aug 25, 2021
1 parent 506da95 commit dbb46ab
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 20 deletions.
14 changes: 8 additions & 6 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use regex::Regex;

use crate::commands::roi::Frequency;
use crate::commands::{accounts, balance, commodities, payees, prices, register, roi, statistics};
use crate::error::{ConfigFileDoesNotExistError, TimeParseError};
use crate::error::{MissingFileError, TimeParseError};
use crate::models::Ledger;
use chrono::NaiveDate;

Expand Down Expand Up @@ -206,7 +206,7 @@ fn init_paths(args: Vec<String>) -> Result<Vec<String>, Box<dyn std::error::Erro
let file = Path::new(&args[i + 1]);
if !file.exists() {
eprintln!("Config file '{}' does not exist", args[i + 1]);
return Err(Box::new(ConfigFileDoesNotExistError{}));
return Err(Box::new(MissingFileError::ConfigFileDoesNotExistError(file.to_path_buf())));
}
possible_paths.push(args[i + 1].clone());
continue;
Expand All @@ -223,7 +223,6 @@ fn init_paths(args: Vec<String>) -> Result<Vec<String>, Box<dyn std::error::Erro
}
}


/// Entry point for the command line app
pub fn run_app(input_args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
let mut config_file = None;
Expand Down Expand Up @@ -251,7 +250,7 @@ pub fn run_app(input_args: Vec<String>) -> Result<(), Box<dyn std::error::Error>

let start = Instant::now();

let mut ledger = Ledger::try_from(&opt.options).unwrap();
let mut ledger = Ledger::try_from(&opt.options)?;
let duration = start.elapsed();
println!(
"Loaded ledger from {:?} in {:?}",
Expand Down Expand Up @@ -368,7 +367,10 @@ fn parse_config_file(file: &Path, input_args: &[String]) -> Vec<String> {
}
args
}
fn execute_command(opt: Opt, maybe_ledger: Option<Ledger>) -> Result<(), Box<dyn std::error::Error>> {
fn execute_command(
opt: Opt,
maybe_ledger: Option<Ledger>,
) -> Result<(), Box<dyn std::error::Error>> {
// Print options
if let Err(e) = match opt.cmd {
Command::Balance {
Expand Down Expand Up @@ -472,7 +474,7 @@ pub fn date_parser(date: &str) -> Result<NaiveDate, Box<dyn std::error::Error>>
Ok((t1, _t2, _b)) => Ok(t1.date()),
Err(e) => {
eprintln!("{:?}", e);
Err(Box::new(TimeParseError{}))
Err(Box::new(TimeParseError {}))
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/commands/statistics.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::convert::TryFrom;

use crate::models::Ledger;
use crate::{ CommonOpts};
use crate::CommonOpts;

/// Statistics command
///
Expand Down
5 changes: 4 additions & 1 deletion src/dinero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ use std::env;
fn main() {
match dinero::run_app(env::args().collect()) {
Ok(_) => {}
Err(_) => std::process::exit(1),
Err(x) => {
eprintln!("{}", x);
std::process::exit(1)
},
}
}
23 changes: 16 additions & 7 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,38 @@
use colored::ColoredString;
use colored::{ColoredString, Colorize};
use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;

#[derive(Debug)]
pub struct EmptyLedgerFileError;
impl Error for EmptyLedgerFileError{}
impl Error for EmptyLedgerFileError {}
impl Display for EmptyLedgerFileError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "The file does not have any information")
}
}

#[derive(Debug)]
pub struct ConfigFileDoesNotExistError;
impl Error for ConfigFileDoesNotExistError{}
impl Display for ConfigFileDoesNotExistError {
pub enum MissingFileError {
ConfigFileDoesNotExistError(PathBuf),
JournalFileDoesNotExistError(PathBuf),
}
impl Error for MissingFileError{}
impl Display for MissingFileError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Config file does not exist.")
let (title, file) =
match self {
MissingFileError::ConfigFileDoesNotExistError(x) => ("Configuration", x.to_str().unwrap()),
MissingFileError::JournalFileDoesNotExistError(x) => ("Journal", x.to_str().unwrap()),
};
write!(f, "{} file does not exist: {}", title, format!("{}",file).red().bold())
}
}

#[derive(Debug)]
pub struct TimeParseError;
impl Error for TimeParseError{}
impl Error for TimeParseError {}
impl Display for TimeParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Couldn't parse time.")
Expand Down
4 changes: 2 additions & 2 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ pub use transaction::{
Cleared, Posting, PostingOrigin, PostingType, Transaction, TransactionStatus, TransactionType,
};

use crate::{error::EmptyLedgerFileError, parser::ParsedLedger};
use crate::parser::value_expr::build_root_node_from_expression;
use crate::parser::{tokenizers, value_expr};
use crate::{parser::value_expr::build_root_node_from_expression};
use crate::{error::EmptyLedgerFileError, parser::ParsedLedger};
use crate::{filter::filter_expression, CommonOpts};
use crate::{models::transaction::Cost, parser::Tokenizer};
use crate::{GenericError, List};
Expand Down
14 changes: 11 additions & 3 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::convert::TryFrom;
use std::fs::read_to_string;
use std::path::PathBuf;

use crate::error::MissingFileError;
use crate::models::{Account, Comment, Currency, HasName, Payee, Transaction};
use crate::parser::utils::count_decimals;
use crate::{models, CommonOpts, List};
Expand Down Expand Up @@ -92,7 +93,7 @@ pub struct Tokenizer<'a> {
}

impl<'a> TryFrom<&'a PathBuf> for Tokenizer<'a> {
type Error = std::io::Error;
type Error = Box<dyn std::error::Error>;
fn try_from(file: &'a PathBuf) -> Result<Self, Self::Error> {
match read_to_string(file) {
Ok(content) => {
Expand All @@ -103,8 +104,15 @@ impl<'a> TryFrom<&'a PathBuf> for Tokenizer<'a> {
content,
seen_files,
})
}
Err(err) => Err(err),
},
Err(err) => {
match err.kind() {
std::io::ErrorKind::NotFound => {
Err(Box::new(MissingFileError::JournalFileDoesNotExistError(file.to_path_buf())))
},
_ => Err(Box::new(err))
}
},
}
}
}
Expand Down

0 comments on commit dbb46ab

Please sign in to comment.