aboutsummaryrefslogtreecommitdiff
path: root/src/deck.rs
blob: 3fff77fddd19972bce9e41e7da52f0811daaf8fd (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use crate::model::Line;
use crate::parser;
use anyhow::{Error, Result};
use std::fmt;
use std::fs::File;
use std::io::{prelude::*, BufReader};
use std::path::Path;

#[derive(Debug, Clone)]
struct ParseError {
    line: String,
    line_number: usize,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Error parsing line {}:\n\n{}",
            self.line_number, self.line
        )
    }
}

impl std::error::Error for ParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

pub fn read_file(path: &str) -> Result<Vec<Line>> {
    let file = File::open(path)?;
    let reader = BufReader::new(file);
    let mut entries: Vec<Line> = Vec::new();

    for (index, line) in reader.lines().enumerate() {
        let line = line?;

        if let Some(line) = read_line(index, &line)? {
            entries.push(line)
        }
    }

    Ok(entries)
}

fn read_line(index: usize, line: &str) -> Result<Option<Line>> {
    match parser::parse_line(line) {
        Ok(("", line)) => Ok(line),
        _ => Err(Error::from(ParseError {
            line_number: index + 1,
            line: line.to_string(),
        })),
    }
}

pub fn pp_from_path(path: &str) -> Option<String> {
    Some(capitalize(
        Path::new(&path).with_extension("").file_name()?.to_str()?,
    ))
}

fn capitalize(s: &str) -> String {
    let mut c = s.chars();
    match c.next() {
        None => String::new(),
        Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
    }
}

#[cfg(test)]
pub mod tests {

    use crate::model::Line;
    use anyhow::Result;

    #[test]
    fn errors() {
        is_error("A");
        is_error("A -> a");
        is_error("A : B : C");
        is_error(":");
        is_error("A : a\n-")
    }

    #[test]
    fn ignored() {
        check("", &[]);
        check(" ", &[]);
        check(" \n \n ", &[]);
        check("# 1", &[]);
        check("# 1\n\n # 2", &[]);
    }

    #[test]
    fn card() {
        check("A : a", &[(&["A"], &["a"])]);
    }

    #[test]
    fn cards() {
        check("A : a\nB : b", &[(&["A"], &["a"]), (&["B"], &["b"])]);
    }

    #[test]
    fn alternatives() {
        check("A : a1 | a2", &[(&["A"], &["a1", "a2"])]);
        check("A1 | A2 : a", &[(&["A1", "A2"], &["a"])]);
        check("A1 | A2 : a1 | a2", &[(&["A1", "A2"], &["a1", "a2"])]);
    }

    fn is_error(content: &str) {
        assert!(read_string(content).is_err())
    }

    fn check(content: &str, res: &[(&[&str], &[&str])]) {
        assert_eq!(
            read_string(content).unwrap(),
            res.iter()
                .map(|(part_1, part_2)| Line {
                    part_1: part_1.iter().map(|x| x.to_string()).collect::<Vec<_>>(),
                    part_2: part_2.iter().map(|x| x.to_string()).collect::<Vec<_>>()
                })
                .collect::<Vec<_>>()
        )
    }

    pub fn read_string(content: &str) -> Result<Vec<Line>> {
        let mut entries: Vec<Line> = Vec::new();

        for (index, line) in content.lines().enumerate() {
            if let Some(line) = super::read_line(index, line)? {
                entries.push(line)
            }
        }

        Ok(entries)
    }
}