Refactor some functions into our cli module

This commit is contained in:
Jeremy Wall 2021-11-21 13:16:16 -05:00
parent 6651bf2996
commit 0428f9d9f0
3 changed files with 29 additions and 28 deletions

View File

@ -17,7 +17,7 @@ use std::io::Read;
use std::io::{BufRead, BufReader};
use std::path::Path;
use recipes::{parse, Recipe};
use recipes::{parse, IngredientAccumulator, Recipe};
#[derive(Debug)]
pub enum ParseError {
@ -25,6 +25,8 @@ pub enum ParseError {
Syntax(String),
}
// TODO(jwall): We should think a little more closely about
// the error modeling for this application.
macro_rules! try_open {
($path:expr) => {
match File::open(&$path) {
@ -39,8 +41,6 @@ macro_rules! try_open {
impl From<std::io::Error> for ParseError {
fn from(err: std::io::Error) -> Self {
// TODO(jwall): This error should allow us to collect more information
// about the cause of the error.
ParseError::IO(err)
}
}
@ -84,3 +84,25 @@ where
}
Ok(recipe_list)
}
pub fn output_recipe_info(r: Recipe, print_ingredients: bool) {
println!("Title: {}", r.title);
println!("");
if print_ingredients {
println!("Ingredients:");
for (_, i) in r.get_ingredients() {
println!("\t* {} {}", i.amt, i.name);
}
}
}
pub fn output_ingredients_list(rs: Vec<Recipe>) {
let mut acc = IngredientAccumulator::new();
for r in rs {
acc.accumulate_from(&r);
}
for (_, i) in acc.ingredients() {
print!("{}", i.amt);
println!(" {}", i.name);
}
}

View File

@ -41,29 +41,6 @@ where
.setting(clap::AppSettings::SubcommandRequiredElseHelp)
}
fn output_recipe_info(r: Recipe, print_ingredients: bool) {
println!("Title: {}", r.title);
println!("");
if print_ingredients {
println!("Ingredients:");
for (_, i) in r.get_ingredients() {
print!("\t* {}", i.amt);
println!(" {}", i.name);
}
}
}
fn output_ingredients_list(rs: Vec<Recipe>) {
let mut acc = IngredientAccumulator::new();
for r in rs {
acc.accumulate_from(&r);
}
for (_, i) in acc.ingredients() {
print!("{}", i.amt);
println!(" {}", i.name);
}
}
fn main() {
let matches = create_app().get_matches();
if let Some(matches) = matches.subcommand_matches("recipe") {
@ -71,7 +48,7 @@ fn main() {
let recipe_file = matches.value_of("INPUT").unwrap();
match cli::parse_recipe(recipe_file) {
Ok(r) => {
output_recipe_info(r, matches.is_present("ingredients"));
cli::output_recipe_info(r, matches.is_present("ingredients"));
}
Err(e) => {
eprintln!("{:?}", e);
@ -82,7 +59,7 @@ fn main() {
let menu_file = matches.value_of("INPUT").unwrap();
match cli::read_menu_list(menu_file) {
Ok(rs) => {
output_ingredients_list(rs);
cli::output_ingredients_list(rs);
}
Err(e) => {
eprintln!("{:?}", e);

View File

@ -316,6 +316,8 @@ pub enum Measure {
use Measure::{Count, Volume, Weight};
// TODO(jwall): We should have an affinity for certain types of volume measurements
// based on the original measurement type.
impl Measure {
pub fn tsp(qty: Quantity) -> Self {
Volume(Tsp(qty))