Skip to content

Commit

Permalink
cli return exit code
Browse files Browse the repository at this point in the history
  • Loading branch information
carderne committed Jan 25, 2024
1 parent abbca0f commit d16f109
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 14 deletions.
16 changes: 7 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
mod book;
mod directives;
mod error;
pub mod error;
mod grammar;
mod parser;
mod utils;
pub mod utils;

use directives::AccBal;

use crate::directives::Directive;
use crate::error::BeanError;
Expand All @@ -31,15 +33,11 @@ fn load(text: String) -> (Vec<Directive>, Vec<BeanError>) {
(dirs, errs)
}

/// Load the file at `path`
/// Optionally print the balance if `print_bals=true`
pub fn balance(path: &String, print_bals: bool) {
/// Check and calculate balances for file at path
pub fn balance(path: &String) -> (AccBal, Vec<BeanError>) {
let text = std::fs::read_to_string(path).expect("cannot read file");
let (mut dirs, mut errs) = load(text);
let (bals, book_errs) = book::get_balances(&mut dirs);
errs.extend(book_errs);
utils::print_errors(errs);
if print_bals {
utils::print_bals(bals);
}
(bals, errs)
}
36 changes: 32 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
use bean_rs::balance;
use std::process::ExitCode;
use std::process::Termination;

use clap::{Parser, Subcommand};

use bean_rs::balance;
use bean_rs::error::BeanError;
use bean_rs::utils;

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
Expand All @@ -17,15 +23,37 @@ enum Commands {
Check { path: String },
}

fn main() {
#[derive(Debug)]
struct CliError {}

impl Termination for CliError {
fn report(self) -> ExitCode {
ExitCode::FAILURE
}
}

fn set_exit(errs: &Vec<BeanError>) -> ExitCode {
if errs.is_empty() {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}

fn main() -> ExitCode {
env_logger::init();
let cli = Cli::parse();
match &cli.command {
Commands::Balance { path } => {
balance(path, true);
let (bals, errs) = balance(path);
utils::print_errors(&errs);
utils::print_bals(bals);
set_exit(&errs)
}
Commands::Check { path } => {
balance(path, false);
let (_, errs) = balance(path);
utils::print_errors(&errs);
set_exit(&errs)
}
}
}
2 changes: 1 addition & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub fn print_bals(bals: AccBal) {
}
}

pub fn print_errors(errs: Vec<BeanError>) {
pub fn print_errors(errs: &Vec<BeanError>) {
if !errs.is_empty() {
eprintln!("-- Errors -- ");
}
Expand Down

0 comments on commit d16f109

Please sign in to comment.