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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use serde::{Deserialize, Serialize};
use smart_default::SmartDefault;

mod input;
pub use input::{InputConfig, TitleBoost};

mod output;
pub use output::OutputConfig;

mod stemming;
pub use stemming::StemmingConfig;

mod frontmatter;
pub use self::frontmatter::FrontmatterConfig;

mod file;
pub use file::{DataSource, File, Filetype};

mod srt;
pub use srt::{SRTConfig, SRTTimestampFormat};

mod errors;
pub use errors::ConfigReadError;

#[derive(Serialize, Deserialize, Debug, SmartDefault, PartialEq)]
#[serde(deny_unknown_fields, default)]
pub struct Config {
    pub input: InputConfig,
    pub output: OutputConfig,
}

impl TryFrom<&str> for Config {
    type Error = ConfigReadError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if value.is_empty() {
            return Err(ConfigReadError::EmptyString);
        }

        let toml_output = toml::from_str::<Self>(value);
        let json_output = serde_json::from_str::<Self>(value);

        match (toml_output, json_output) {
            (Ok(toml_config), _) => Ok(toml_config),

            (Err(_), Ok(json_config)) => Ok(json_config),

            (Err(toml_error), Err(json_error)) => {
                if let Some((mut toml_line, mut toml_col)) = toml_error.line_col() {
                    toml_line += 1;
                    toml_col += 1;
                    if toml_line > json_error.line()
                        || (toml_line == json_error.line() && toml_col > json_error.column())
                    {
                        Err(ConfigReadError::UnparseableTomlInput(toml_error))
                    } else {
                        Err(ConfigReadError::UnparseableJsonInput(json_error))
                    }
                } else {
                    Err(ConfigReadError::UnparseableJsonInput(json_error))
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn empty_string_via_tryfrom_returns_error() {
        let contents = r#""#;
        let error = Config::try_from(contents).unwrap_err();
        assert_eq!(error, ConfigReadError::EmptyString)
    }

    fn get_default_config() -> Config {
        Config {
            input: InputConfig {
                UNUSED_surrounding_word_count: None,
                base_directory: "test/federalist".into(),
                url_prefix: "".into(),
                title_boost: TitleBoost::Moderate,
                stemming: StemmingConfig::Language(
                    rust_stemmers::Algorithm::English,
                ),
                html_selector: None,
                exclude_html_selector: None,
                frontmatter_handling: FrontmatterConfig::Omit,
                files: vec![
                    File {
                        title: "Introduction".into(),
                        url: "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-1".into(),
                        explicit_source: Some(
                            DataSource::FilePath(
                                "federalist-1.txt".into(),
                            ),
                        ),
                        id: None,
                        stemming_override: None,
                        html_selector_override: None,
                        exclude_html_selector_override: None,
                        frontmatter_handling_override: None,
                        filetype: None,
                        fields: HashMap::new(),
                    },
                    File {
                        title: "Concerning Dangers from Foreign Force and Influence".into(),
                        url: "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-2".into(),
                        explicit_source: Some(
                            DataSource::FilePath(
                                "federalist-2.txt".into(),
                            ),
                        ),
                        id: None,
                        stemming_override: None,
                        html_selector_override: None,
                        exclude_html_selector_override: None,
                        frontmatter_handling_override: None,
                        filetype: None,
                        fields: HashMap::new(),
                    },
                    File {
                        title: "Concerning Dangers from Foreign Force and Influence 2".into(),
                        url: "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-3".into(),
                        explicit_source: Some(
                            DataSource::FilePath(
                                "federalist-3.txt".into(),
                            ),
                        ),
                        id: None,
                        stemming_override: None,
                        html_selector_override: None,
                        exclude_html_selector_override: None,
                        frontmatter_handling_override: None,
                        filetype: None,
                        fields: HashMap::new(),
                    },
                ],
                break_on_file_error: false,
                srt_config: SRTConfig {
                    timestamp_linking: true,
                    timestamp_template_string: "&t={ts}".into(),
                    timestamp_format: SRTTimestampFormat::NumberOfSeconds,
                },
                minimum_indexed_substring_length: 3,
                minimum_index_ideographic_substring_length: 1,
            },
            output: OutputConfig {
                UNUSED_filename: None,
                debug: true,
                save_nearest_html_id: false,
                excerpt_buffer: 8,
                excerpts_per_result: 5,
                displayed_results_count: 10,
            },
        }
    }

    // This test also makes sure that our default values don't change
    // without being accounted for in tests.
    #[test]
    fn simple_toml_config_is_parseable() {
        let contents = r#"
[input]
base_directory = "test/federalist"
files = [
    {path = "federalist-1.txt", url = "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-1", title = "Introduction"},
    {path = "federalist-2.txt", url = "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-2", title = "Concerning Dangers from Foreign Force and Influence"},
    {path = "federalist-3.txt", url = "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-3", title = "Concerning Dangers from Foreign Force and Influence 2"},
]

[output]
debug = true
    "#;

        let computed = Config::try_from(contents).unwrap();
        let expected = get_default_config();

        assert_eq!(computed, expected)
    }

    #[test]
    fn simple_json_config_is_parseable() {
        let contents = r#"
        {
            "input": {
                "base_directory": "test/federalist",
                "files": [
                    {
                        "path": "federalist-1.txt",
                        "url": "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-1",
                        "title": "Introduction"
                    },
                    {
                        "path": "federalist-2.txt",
                        "url": "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-2",
                        "title": "Concerning Dangers from Foreign Force and Influence"
                    },
                    {
                        "path": "federalist-3.txt",
                        "url": "https://www.congress.gov/resources/display/content/The+Federalist+Papers#TheFederalistPapers-3",
                        "title": "Concerning Dangers from Foreign Force and Influence 2"
                    }
                ]
            },
            "output": {
                "debug": true
            }
        }
    "#;

        let computed = Config::try_from(contents).unwrap();
        let expected = get_default_config();

        assert_eq!(computed, expected)
    }

    #[test]
    fn bad_toml_syntax_fails_with_toml_error() {
        let contents = r#"[input] {}"#;
        let error = Config::try_from(contents).unwrap_err();
        let computed = error.to_string();
        let expected = "Cannot parse config as TOML. Stork recieved error: `expected newline, found a left brace at line 1 column 9`";
        assert_eq!(computed, expected);
    }
    #[test]
    fn bad_json_syntax_fails_with_json_error() {
        let contents = r#"{"input", ]}"#;
        let error = Config::try_from(contents).unwrap_err();
        let computed = error.to_string();
        let expected =
            "Cannot parse config as JSON. Stork recieved error: `expected `:` at line 1 column 9`";
        assert_eq!(computed, expected);
    }

    #[test]
    fn empty_file_array_fails() {
        let contents = r#"
[input]
files = [{}]
    "#;
        let result: toml::de::Error = toml::from_str::<Config>(contents).unwrap_err();
        let computed = result.to_string();
        let expected = "missing field `title` for key `input.files` at line 3 column 10"; // TODO: Can this be nicer?
        assert_eq!(computed, expected);
    }
}