aoc_toolkit/application/
fetch.rs1use thiserror::Error;
2
3use super::calendar::{CalendarDate, DayAvailability};
4use crate::{ClientError, InputSource, InputStore};
5
6#[derive(Debug, Default, Clone, Copy)]
7pub struct FetchOptions {
8 pub year: Option<usize>,
9 pub day: Option<usize>,
10 pub all: bool,
11}
12
13#[derive(Debug)]
14pub struct FetchReport {
15 pub year: usize,
16 pub day: usize,
17 pub outcome: Result<InputSource, ClientError>,
18}
19
20#[derive(Debug, Error)]
21pub enum FetchError {
22 #[error("Invalid Advent of Code year: {0}")]
23 InvalidYear(usize),
24
25 #[error("Invalid Advent of Code day: {0}")]
26 InvalidDay(usize),
27
28 #[error("--all cannot be combined with --day")]
29 AllConflict,
30
31 #[error("No puzzles are unlocked for {0}")]
32 NoUnlockedPuzzles(usize),
33
34 #[error("Puzzle {year} / Day {day:02} is not unlocked")]
35 PuzzleLocked { year: usize, day: usize },
36
37 #[error(transparent)]
38 Client(#[from] ClientError),
39}
40
41impl FetchOptions {
42 fn resolve(&self, today: CalendarDate) -> Result<Vec<(usize, usize)>, FetchError> {
43 if self.all && self.day.is_some() {
44 return Err(FetchError::AllConflict);
45 }
46
47 let year = self.year.unwrap_or(today.year);
48
49 if !(2015..=today.year).contains(&year) {
50 return Err(FetchError::InvalidYear(year));
51 }
52
53 let unlocked = today.unlocked_days(year);
54
55 if let Some(day) = self.day {
56 match today.day_availability(year, day) {
57 DayAvailability::OutsideEdition => return Err(FetchError::InvalidDay(day)),
58 DayAvailability::Locked if unlocked > 0 => {
59 return Err(FetchError::PuzzleLocked { year, day });
60 }
61 DayAvailability::Locked | DayAvailability::Unlocked => {}
62 }
63 }
64
65 if unlocked == 0 {
66 return Err(FetchError::NoUnlockedPuzzles(year));
67 }
68
69 if self.all {
70 return Ok((1..=unlocked).map(|day| (year, day)).collect());
71 }
72
73 Ok(vec![(year, self.day.unwrap_or(unlocked))])
74 }
75}
76
77pub fn execute(options: &FetchOptions) -> Result<Vec<FetchReport>, FetchError> {
87 let days = options.resolve(CalendarDate::today())?;
88
89 let mut store = InputStore::global()?;
90 let mut reports = Vec::with_capacity(days.len());
91
92 for (year, day) in days {
93 let outcome = store.get_with_source(year, day).map(|(_, source)| source);
94
95 let failed = outcome.is_err();
96
97 reports.push(FetchReport { year, day, outcome });
98
99 if failed {
100 break;
101 }
102 }
103
104 Ok(reports)
105}
106
107#[cfg(test)]
108mod tests;