1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use lazy_static::lazy_static;
use regex::Regex;
use serde::Serialize;
use std::{
fs::File,
io::{self, BufRead},
path::{Path, PathBuf},
};
#[derive(Debug, Default, Serialize)]
pub struct Ingredient {
pub name: String,
pub amount: String,
}
#[derive(Debug, Default, Serialize)]
pub struct Recipe {
pub id: usize,
pub name: String,
pub attributes: Vec<(String, String)>,
pub instructions: Vec<String>,
pub ingredients: Vec<Ingredient>,
}
pub fn parse_recipe(path: PathBuf, next_id: usize) -> Recipe {
lazy_static! {
static ref RE_TITL: Regex = Regex::new("^# .*$").unwrap();
static ref RE_ATTR: Regex = Regex::new("^\\* .*$").unwrap();
static ref RE_INGR: Regex = Regex::new("^\\- .*$").unwrap();
static ref RE_INST: Regex = Regex::new("^\\+ .*$").unwrap();
}
println!("Parsing {}", path.display());
let mut name = String::new();
let attributes = Vec::new();
let mut instructions = Vec::new();
let mut ingredients = Vec::new();
if let Ok(lines) = read_lines(path.as_path()) {
for line in lines {
if let Ok(ip) = line {
if RE_TITL.is_match(&ip) {
name = ip.replace("#", "").trim().to_string();
} else if RE_ATTR.is_match(&ip) {
} else if RE_INST.is_match(&ip) {
let instruction = ip.replace("+", "").trim().to_string();
instructions.push(instruction);
} else if RE_INGR.is_match(&ip) {
let ingredient = ip.replace("-", "").trim().to_string();
let amount = ingredient.split(" ").collect::<Vec<&str>>();
let number_of_words = amount.len();
let ingredient = Ingredient {
name: amount[..number_of_words - 2].join(" "),
amount: amount[number_of_words - 2..].join(" "),
};
ingredients.push(ingredient);
}
}
}
}
Recipe {
id: next_id,
name,
attributes,
ingredients,
instructions,
}
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}