aoc-runtime 0.6.0

a runtime automation tool for Advent of Code: scaffold, run and submit puzzle solutions
Documentation
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Recovering template parameters from the current working directory.
//!
//! The pattern is generated from the parsed segments **in template order**:
//! everything after each placeholder is wrapped in an optional group, so
//! standing anywhere along the template's path recovers the parameters up to
//! that point, whatever order the placeholders appear in.

use super::{Segment, TemplateError};
use crate::{
    language::Language,
    puzzle::{Day, Year},
};
use regex::Regex;
use std::path::Path;

/// Parameters recovered from a directory path. Every field is best-effort:
/// only explicit command line arguments produce hard errors.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Detected {
    /// The detected year, if the path contained a valid one.
    pub year: Option<Year>,
    /// The detected day, if the path contained a valid one.
    pub day: Option<Day>,
    /// The detected language, if the path contained one.
    pub language: Option<Language>,
}

/// A compiled matcher for one template.
#[derive(Debug, Clone)]
pub struct CwdMatcher {
    pattern: Regex,
}

impl CwdMatcher {
    /// Compiles a matcher for the given segments.
    ///
    /// # Errors
    ///
    /// Returns [`TemplateError::Regex`] if the generated pattern is rejected.
    pub fn build(segments: &[Segment]) -> Result<Self, TemplateError> {
        Ok(Self {
            pattern: Regex::new(&build_pattern(segments))?,
        })
    }

    /// The generated regular expression, exposed for diagnostics and tests.
    #[must_use]
    pub fn pattern(&self) -> &str {
        self.pattern.as_str()
    }

    /// Recovers whatever parameters the path reveals.
    #[must_use]
    pub fn detect(&self, directory: &Path) -> Detected {
        let path = directory.to_string_lossy();
        let path = path.trim_end_matches(['/', '\\']);

        let Some(captures) = self.pattern.captures(path) else {
            return Detected::default();
        };

        let capture = |name| captures.name(name).map(|m| m.as_str());

        Detected {
            year: capture("year")
                .and_then(|v| v.parse().ok())
                .and_then(Year::new),
            day: capture("day")
                .and_then(|v| v.parse().ok())
                .and_then(Day::new),
            language: capture("language").and_then(|v| v.parse().ok()),
        }
    }
}

fn build_pattern(segments: &[Segment]) -> String {
    let mut chunks: Vec<String> = Vec::new();
    let mut pending = String::new();
    let mut seen = Seen::default();

    for segment in segments {
        match segment {
            Segment::Literal(text) => pending.push_str(&literal_pattern(text)),
            Segment::Year | Segment::Day { .. } | Segment::Language => {
                pending.push_str(&placeholder_pattern(segment, &mut seen));
                chunks.push(std::mem::take(&mut pending));
            }
        }
    }

    let mut pattern = String::from("^");
    let mut groups = 0usize;

    for (index, chunk) in chunks.iter().enumerate() {
        if index > 0 {
            pattern.push_str("(?:");
            groups += 1;
        }
        pattern.push_str(chunk);
    }

    if !pending.is_empty() {
        pattern.push_str("(?:");
        groups += 1;
        pattern.push_str(&pending);
    }

    for _ in 0..groups {
        pattern.push_str(")?");
    }

    pattern.push_str("(?:");
    pattern.push_str(SEPARATOR);
    pattern.push_str(".*)?$");
    pattern
}

/// Matches either separator, whichever the template was written with: a
/// template is configured by hand, but the working directory comes from the
/// operating system, which on Windows always reports backslashes.
const SEPARATOR: &str = r"[/\\]";

fn literal_pattern(text: &str) -> String {
    let mut pattern = String::with_capacity(text.len());
    let mut rest = text;

    while let Some(at) = rest.find(['/', '\\']) {
        pattern.push_str(&regex::escape(&rest[..at]));
        pattern.push_str(SEPARATOR);
        rest = &rest[at + 1..];
    }

    pattern.push_str(&regex::escape(rest));
    pattern
}

#[derive(Default)]
struct Seen {
    year: bool,
    day: bool,
    language: bool,
}

fn placeholder_pattern(segment: &Segment, seen: &mut Seen) -> String {
    let (first, name, body) = match segment {
        Segment::Year => (
            !std::mem::replace(&mut seen.year, true),
            "year",
            r"\d{4}".to_owned(),
        ),
        Segment::Day { .. } => (
            !std::mem::replace(&mut seen.day, true),
            "day",
            r"\d{1,2}".to_owned(),
        ),
        Segment::Language => (
            !std::mem::replace(&mut seen.language, true),
            "language",
            language_alternation(),
        ),
        Segment::Literal(_) => return String::new(),
    };

    if first {
        format!("(?<{name}>{body})")
    } else {
        format!("(?:{body})")
    }
}

fn language_alternation() -> String {
    let mut names: Vec<&str> = Language::ALL
        .iter()
        .map(|language| language.name())
        .collect();
    names.sort_unstable_by_key(|name| (std::cmp::Reverse(name.len()), *name));
    names.join("|")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::template::Template;

    fn matcher(source: &str) -> CwdMatcher {
        Template::parse(source)
            .expect("template should parse")
            .matcher()
            .expect("pattern should compile")
    }

    fn detect(source: &str, cwd: &str) -> Detected {
        matcher(source).detect(Path::new(cwd))
    }

    fn triple(detected: Detected) -> (Option<u16>, Option<u8>, Option<Language>) {
        (
            detected.year.map(Year::get),
            detected.day.map(Day::get),
            detected.language,
        )
    }

    const CANONICAL: &str = "/root/{{year}}/day{{pad day}}/{{language}}";

    #[test]
    fn generates_an_anchored_pattern_with_nested_optional_groups() {
        assert_eq!(
            matcher(CANONICAL).pattern(),
            r"^[/\\]root[/\\](?<year>\d{4})(?:[/\\]day(?<day>\d{1,2})(?:[/\\](?<language>csharp|python|java|rust))?)?(?:[/\\].*)?$"
        );
    }

    #[test]
    fn recovers_every_parameter_from_a_full_path() {
        assert_eq!(
            triple(detect(CANONICAL, "/root/2024/day07/rust")),
            (Some(2024), Some(7), Some(Language::Rust))
        );
    }

    #[test]
    fn recovers_partial_parameters_from_a_prefix() {
        assert_eq!(triple(detect(CANONICAL, "/root")), (None, None, None));
        assert_eq!(
            triple(detect(CANONICAL, "/root/2024")),
            (Some(2024), None, None)
        );
        assert_eq!(
            triple(detect(CANONICAL, "/root/2024/day07")),
            (Some(2024), Some(7), None)
        );
    }

    #[test]
    fn recovers_parameters_from_a_deeper_directory() {
        assert_eq!(
            triple(detect(CANONICAL, "/root/2024/day07/rust/src/bin")),
            (Some(2024), Some(7), Some(Language::Rust))
        );
    }

    #[test]
    fn two_digit_days_are_not_truncated() {
        for (day, expected) in [
            (1, 1),
            (5, 5),
            (9, 9),
            (10, 10),
            (15, 15),
            (19, 19),
            (25, 25),
        ] {
            let padded = format!("/root/2024/day{day:02}/rust");
            let plain = format!("/root/2024/day{day}/rust");

            assert_eq!(
                triple(detect(CANONICAL, &padded)).1,
                Some(expected),
                "{padded}"
            );
            assert_eq!(
                triple(detect("/root/{{year}}/day{{day}}/{{language}}", &plain)).1,
                Some(expected),
                "{plain}"
            );
        }
    }

    #[test]
    fn out_of_range_values_are_dropped_individually() {
        assert_eq!(
            triple(detect(CANONICAL, "/root/2024/day26/rust")),
            (Some(2024), None, Some(Language::Rust))
        );
        assert_eq!(
            triple(detect(CANONICAL, "/root/2024/day00/rust")),
            (Some(2024), None, Some(Language::Rust))
        );
        assert_eq!(
            triple(detect(CANONICAL, "/root/1999/day07/rust")),
            (None, Some(7), Some(Language::Rust))
        );
    }

    #[test]
    fn unrelated_directories_yield_nothing() {
        assert_eq!(triple(detect(CANONICAL, "/tmp")), (None, None, None));
        assert_eq!(
            triple(detect(CANONICAL, "/elsewhere/2024/day07/rust")),
            (None, None, None)
        );
    }

    #[test]
    fn a_broken_middle_segment_stops_detection_there() {
        assert_eq!(
            triple(detect(CANONICAL, "/root/2024/scratch/rust")),
            (Some(2024), None, None)
        );
    }

    #[test]
    fn partial_matching_follows_template_order_not_a_fixed_order() {
        let reordered = "/root/{{language}}/{{year}}/day{{day}}";

        assert_eq!(
            triple(detect(reordered, "/root/rust")),
            (None, None, Some(Language::Rust))
        );
        assert_eq!(
            triple(detect(reordered, "/root/rust/2024")),
            (Some(2024), None, Some(Language::Rust))
        );
        assert_eq!(
            triple(detect(reordered, "/root/rust/2024/day7")),
            (Some(2024), Some(7), Some(Language::Rust))
        );
    }

    #[test]
    fn a_trailing_literal_is_optional() {
        let with_suffix = "/root/{{year}}/day{{pad day}}/{{language}}/solution";

        assert_eq!(
            triple(detect(with_suffix, "/root/2024/day07/rust")),
            (Some(2024), Some(7), Some(Language::Rust))
        );
        assert_eq!(
            triple(detect(with_suffix, "/root/2024/day07/rust/solution")),
            (Some(2024), Some(7), Some(Language::Rust))
        );
    }

    #[test]
    fn spaced_out_placeholders_still_detect() {
        assert_eq!(
            triple(detect(
                "/root/{{ year }}/day{{ pad day }}/{{ language }}",
                "/root/2024/day07/java"
            )),
            (Some(2024), Some(7), Some(Language::Java))
        );
    }

    #[test]
    fn literal_regex_metacharacters_are_escaped() {
        let dotted = "/root/a.c/{{year}}/day{{pad day}}";

        assert_eq!(triple(detect(dotted, "/root/a.c/2024/day07")).0, Some(2024));
        assert_eq!(triple(detect(dotted, "/root/abc/2024/day07")).0, None);
    }

    #[test]
    fn either_separator_matches_whichever_the_template_used() {
        assert_eq!(
            triple(detect(CANONICAL, r"\root\2024\day07\rust")),
            (Some(2024), Some(7), Some(Language::Rust))
        );
        assert_eq!(
            triple(detect(
                r"C:\aoc\{{year}}\day{{pad day}}\{{language}}",
                r"C:\aoc\2024\day07\rust"
            )),
            (Some(2024), Some(7), Some(Language::Rust))
        );
        assert_eq!(
            triple(detect(
                r"C:\aoc\{{year}}\day{{pad day}}\{{language}}",
                "C:/aoc/2024/day07/rust"
            )),
            (Some(2024), Some(7), Some(Language::Rust))
        );
    }

    #[test]
    fn trailing_separators_are_ignored() {
        assert_eq!(
            triple(detect(CANONICAL, "/root/2024/day07/rust/")),
            (Some(2024), Some(7), Some(Language::Rust))
        );
    }

    #[test]
    fn every_language_is_recognised() {
        for language in Language::ALL {
            let cwd = format!("/root/2024/day07/{}", language.name());
            assert_eq!(triple(detect(CANONICAL, &cwd)).2, Some(*language), "{cwd}");
        }
    }

    #[test]
    fn matching_is_case_sensitive() {
        assert_eq!(
            triple(detect(CANONICAL, "/Root/2024/day07/rust")),
            (None, None, None)
        );
        assert_eq!(triple(detect(CANONICAL, "/root/2024/day07/Rust")).2, None);
    }

    #[test]
    fn repeated_placeholders_capture_once() {
        let repeated = "/root/{{year}}/day{{pad day}}/{{year}}";

        assert_eq!(
            triple(detect(repeated, "/root/2024/day07/2024")),
            (Some(2024), Some(7), None)
        );
    }
}