aoc-runtime 0.7.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Turning command line arguments into a concrete plan of work.
//!
//! Resolution is pure: it takes the parsed arguments, the configuration, a
//! directory and a clock, and produces a [`Plan`] whose variants carry exactly
//! what their handler needs. A mode that requires a language cannot be
//! constructed without one, so no downstream code has to re-check.

use crate::{
    cli::{Cli, Mode},
    config::Config,
    env::{Clock, is_december},
    language::Language,
    puzzle::{Day, Puzzle, Year},
    template::{Params, TemplateError},
};
use chrono::{Datelike, NaiveDate};
use std::path::{Path, PathBuf};

/// A fully resolved unit of work.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Plan {
    /// Build and run a solution, optionally submitting its answers.
    Run {
        /// The puzzle being solved.
        puzzle: Puzzle,
        /// The language the solution is written in.
        language: Language,
        /// The project directory.
        project: PathBuf,
        /// Whether answers should be submitted.
        submit: bool,
    },
    /// Scaffold a new solution.
    Init {
        /// The puzzle being solved.
        puzzle: Puzzle,
        /// The language to scaffold.
        language: Language,
        /// The project directory.
        project: PathBuf,
    },
    /// Print a project directory.
    Path {
        /// The project directory.
        project: PathBuf,
    },
    /// Open a project directory in the editor.
    Code {
        /// The project directory.
        project: PathBuf,
    },
    /// Print a puzzle URL.
    Url {
        /// The puzzle to link to.
        puzzle: Puzzle,
    },
}

/// Resolves arguments, the working directory and the clock into a [`Plan`].
///
/// Precedence for each value is: explicit argument, then whatever the working
/// directory reveals through the configured template, then a date-based
/// default.
///
/// # Errors
///
/// Returns [`ResolveError::LanguageRequired`] if the mode needs a language and
/// none could be determined, or [`ResolveError::Template`] if the template's
/// matcher cannot be compiled.
pub fn plan(
    cli: &Cli,
    config: &Config,
    cwd: &Path,
    clock: &dyn Clock,
) -> Result<Plan, ResolveError> {
    let today = clock.today();
    let detected = config.template.matcher()?.detect(cwd);

    let year = cli
        .year
        .and_then(Year::new)
        .or(detected.year)
        .unwrap_or_else(|| latest_available_year(today));

    let day = cli
        .day
        .and_then(Day::new)
        .or_else(|| detected.day.filter(|&day| year.has_day(day)))
        .unwrap_or_else(|| default_day(year, today));

    let puzzle = Puzzle::new(year, day).ok_or(ResolveError::DayOutOfRange { year, day })?;
    let language = cli.language.or(detected.language);

    if !cli.mode.needs_language() {
        return Ok(Plan::Url { puzzle });
    }

    let language = language.ok_or(ResolveError::LanguageRequired { mode: cli.mode })?;
    let project = config.template.render(Params {
        year,
        day,
        language,
    });

    Ok(match cli.mode {
        Mode::Run => Plan::Run {
            puzzle,
            language,
            project,
            submit: !cli.no_submit,
        },
        Mode::Init => Plan::Init {
            puzzle,
            language,
            project,
        },
        Mode::Path => Plan::Path { project },
        Mode::Code => Plan::Code { project },
        Mode::Url => Plan::Url { puzzle },
    })
}

/// The most recent event that has started on the given date.
///
/// Advent of Code begins on 1 December, so before December the current year's
/// event does not exist yet.
#[must_use]
pub fn latest_available_year(today: NaiveDate) -> Year {
    let year = today.year();
    let available = if is_december(today) { year } else { year - 1 };

    u16::try_from(available)
        .ok()
        .and_then(Year::new)
        .unwrap_or(Year::FIRST)
}

/// The day to use when none was given: today during the event, otherwise the
/// first puzzle.
///
/// Today is clamped to the end of `year`'s event, which is day 12 from
/// [`Year::FIRST_SHORT`] on.
#[must_use]
pub fn default_day(year: Year, today: NaiveDate) -> Day {
    if is_december(today) {
        Day::clamped(year, today.day())
    } else {
        Day::FIRST
    }
}

/// Errors produced while resolving a plan.
#[derive(Debug, thiserror::Error)]
pub enum ResolveError {
    /// The mode needs a language and none was given or detected.
    #[error(
        "a language is required for `{mode}` - pass --language, or run from a \
         directory the template can resolve"
    )]
    LanguageRequired {
        /// The mode that needs a language.
        mode: Mode,
    },
    /// The requested day is past the end of the requested event.
    #[error("{year} has no day {day} - that event ends on day {}", .year.last_day())]
    DayOutOfRange {
        /// The event the day was requested in.
        year: Year,
        /// The requested day.
        day: Day,
    },
    /// The template could not be compiled into a matcher.
    #[error("could not build a matcher from the configured template")]
    Template(#[from] TemplateError),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::env::{Env, FixedClock};
    use clap::Parser as _;

    fn env(cwd: &str) -> Env {
        Env {
            home: PathBuf::from("/home/tester"),
            config_dir: PathBuf::from("/home/tester/.config/aoc"),
            config_file: PathBuf::from("/home/tester/.config/aoc/config.yaml"),
            state_dir: PathBuf::from("/home/tester/.local/state/aoc"),
            cwd: PathBuf::from(cwd),
            session_cookie: None,
        }
    }

    fn config() -> Config {
        let (config, _) = Config::from_yaml(
            "template_path: \"/root/{{year}}/day{{pad day}}/{{language}}\"",
            &env("/"),
        )
        .expect("config should load");
        config
    }

    fn cli(args: &[&str]) -> Cli {
        let mut command_line = vec!["aoc"];
        command_line.extend_from_slice(args);
        Cli::try_parse_from(command_line).expect("arguments should parse")
    }

    fn date(year: i32, month: u32, day: u32) -> NaiveDate {
        NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
    }

    fn year(year: u16) -> Year {
        Year::new(year).expect("valid year")
    }

    fn resolve(args: &[&str], cwd: &str, today: NaiveDate) -> Result<Plan, ResolveError> {
        plan(&cli(args), &config(), Path::new(cwd), &FixedClock(today))
    }

    fn puzzle_of(plan: &Plan) -> Option<Puzzle> {
        match plan {
            Plan::Run { puzzle, .. } | Plan::Init { puzzle, .. } | Plan::Url { puzzle } => {
                Some(*puzzle)
            }
            Plan::Path { .. } | Plan::Code { .. } => None,
        }
    }

    fn project_of(plan: &Plan) -> Option<&Path> {
        match plan {
            Plan::Run { project, .. }
            | Plan::Init { project, .. }
            | Plan::Path { project }
            | Plan::Code { project } => Some(project),
            Plan::Url { .. } => None,
        }
    }

    #[test]
    fn the_most_recent_event_depends_on_the_month() {
        assert_eq!(latest_available_year(date(2024, 12, 1)).get(), 2024);
        assert_eq!(latest_available_year(date(2024, 12, 31)).get(), 2024);
        assert_eq!(latest_available_year(date(2024, 11, 30)).get(), 2023);
        assert_eq!(latest_available_year(date(2025, 1, 1)).get(), 2024);
    }

    #[test]
    fn the_default_day_is_today_during_the_event() {
        assert_eq!(default_day(year(2024), date(2024, 12, 1)).get(), 1);
        assert_eq!(default_day(year(2024), date(2024, 12, 14)).get(), 14);
        assert_eq!(default_day(year(2024), date(2024, 12, 25)).get(), 25);
    }

    #[test]
    fn the_default_day_is_clamped_after_the_event_ends() {
        for day in 26..=31 {
            assert_eq!(
                default_day(year(2024), date(2024, 12, day)).get(),
                25,
                "december {day}"
            );
        }
    }

    #[test]
    fn the_default_day_is_clamped_to_a_shortened_event() {
        for day in 13..=31 {
            assert_eq!(
                default_day(year(2025), date(2025, 12, day)).get(),
                12,
                "december {day}"
            );
        }
    }

    #[test]
    fn the_default_day_is_the_first_outside_december() {
        assert_eq!(default_day(year(2024), date(2024, 1, 20)).get(), 1);
        assert_eq!(default_day(year(2024), date(2024, 11, 30)).get(), 1);
    }

    #[test]
    fn explicit_arguments_win_over_everything() {
        let plan = resolve(
            &["-y", "2019", "-d", "3", "-l", "java", "path"],
            "/root/2024/day07/rust",
            date(2024, 12, 14),
        )
        .expect("plan should resolve");

        assert_eq!(project_of(&plan), Some(Path::new("/root/2019/day03/java")));
    }

    #[test]
    fn the_working_directory_wins_over_date_defaults() {
        let plan = resolve(&["path"], "/root/2019/day03/java", date(2024, 12, 14))
            .expect("plan should resolve");

        assert_eq!(project_of(&plan), Some(Path::new("/root/2019/day03/java")));
    }

    #[test]
    fn date_defaults_apply_when_nothing_else_does() {
        let plan = resolve(&["-l", "rust", "path"], "/elsewhere", date(2024, 12, 14))
            .expect("plan should resolve");

        assert_eq!(project_of(&plan), Some(Path::new("/root/2024/day14/rust")));
    }

    #[test]
    fn a_partial_directory_fills_the_rest_from_defaults() {
        let plan = resolve(&["-l", "rust", "path"], "/root/2019", date(2024, 12, 14))
            .expect("plan should resolve");

        assert_eq!(project_of(&plan), Some(Path::new("/root/2019/day14/rust")));
    }

    #[test]
    fn an_explicit_day_the_event_never_had_is_an_error() {
        let error = resolve(
            &["-y", "2025", "-d", "20", "url"],
            "/elsewhere",
            date(2025, 12, 20),
        )
        .expect_err("2025 ends on day 12");

        assert!(
            matches!(error, ResolveError::DayOutOfRange { .. }),
            "{error:?}"
        );
        assert!(error.to_string().contains("2025 has no day 20"), "{error}");
    }

    #[test]
    fn a_detected_day_the_event_never_had_falls_back_to_the_default() {
        let plan = resolve(&["path"], "/root/2025/day20/rust", date(2025, 12, 5))
            .expect("plan should resolve");

        assert_eq!(project_of(&plan), Some(Path::new("/root/2025/day05/rust")));
    }

    #[test]
    fn a_shortened_event_still_accepts_its_own_days() {
        let plan = resolve(
            &["-y", "2025", "-d", "12", "url"],
            "/elsewhere",
            date(2026, 1, 1),
        )
        .expect("plan should resolve");

        assert_eq!(
            puzzle_of(&plan).map(Puzzle::url).as_deref(),
            Some("https://adventofcode.com/2025/day/12")
        );
    }

    #[test]
    fn url_needs_no_language() {
        let plan = resolve(&["url"], "/elsewhere", date(2024, 12, 5)).expect("plan should resolve");

        assert_eq!(
            plan,
            Plan::Url {
                puzzle: puzzle_of(&plan).expect("url carries a puzzle")
            }
        );
        assert_eq!(
            puzzle_of(&plan).map(Puzzle::url).as_deref(),
            Some("https://adventofcode.com/2024/day/5")
        );
    }

    #[test]
    fn other_modes_require_a_language() {
        for mode in ["run", "init", "path", "code"] {
            let error = resolve(&[mode], "/elsewhere", date(2024, 12, 5))
                .expect_err("language is required");

            assert!(
                matches!(error, ResolveError::LanguageRequired { .. }),
                "{mode}: {error:?}"
            );
            assert!(error.to_string().contains(mode), "{error}");
        }
    }

    #[test]
    fn run_submits_unless_told_otherwise() {
        let submitting = resolve(
            &["-l", "rust", "run"],
            "/root/2024/day07/rust",
            date(2024, 12, 7),
        )
        .expect("plan should resolve");
        let quiet = resolve(
            &["-l", "rust", "--no-submit", "run"],
            "/root/2024/day07/rust",
            date(2024, 12, 7),
        )
        .expect("plan should resolve");

        assert!(matches!(submitting, Plan::Run { submit: true, .. }));
        assert!(matches!(quiet, Plan::Run { submit: false, .. }));
    }

    #[test]
    fn each_mode_produces_its_own_plan() {
        let cwd = "/root/2024/day07/rust";
        let today = date(2024, 12, 7);

        assert!(matches!(
            resolve(&["run"], cwd, today),
            Ok(Plan::Run { .. })
        ));
        assert!(matches!(
            resolve(&["init"], cwd, today),
            Ok(Plan::Init { .. })
        ));
        assert!(matches!(
            resolve(&["path"], cwd, today),
            Ok(Plan::Path { .. })
        ));
        assert!(matches!(
            resolve(&["code"], cwd, today),
            Ok(Plan::Code { .. })
        ));
        assert!(matches!(
            resolve(&["url"], cwd, today),
            Ok(Plan::Url { .. })
        ));
    }
}