Skip to main content

aoc_toolkit/application/
run.rs

1mod progress_report;
2
3pub use progress_report::{
4    DayFailure, DayProgress, PartProgress, PartStatus, ProgressReport, ProgressReportError,
5};
6
7use crate::project::{Language, Project};
8use crate::{ClientError, InputStore, adapters};
9use std::process::ExitStatus;
10
11#[derive(Debug, Default, Clone, Copy)]
12pub struct RunOptions {
13    pub year: Option<usize>,
14    pub day: Option<u8>,
15    pub part: Option<u8>,
16    pub all: bool,
17}
18
19/// Executes a project's configured runner.
20///
21/// # Errors
22///
23/// Returns an error if planning, input preparation, or process execution fails.
24pub fn execute(project: &Project, options: &RunOptions) -> Result<ExitStatus, RunError> {
25    execute_inner(project, options, false).map(|execution| execution.status)
26}
27
28/// Executes a project's configured runner and requests a progress report.
29///
30/// # Errors
31///
32/// Returns an error if planning, input preparation, process execution,
33/// or report file I/O fails.
34pub fn execute_with_report(
35    project: &Project,
36    options: &RunOptions,
37) -> Result<RunExecution, RunError> {
38    execute_inner(project, options, true)
39}
40
41pub struct RunExecution {
42    pub status: ExitStatus,
43    pub progress_report: Option<ProgressReport>,
44}
45
46fn execute_inner(
47    project: &Project,
48    options: &RunOptions,
49    request_report: bool,
50) -> Result<RunExecution, RunError> {
51    options.validate()?;
52
53    let output = match project.config.project.language {
54        Language::Rust => adapters::rust::plan(project, options)?,
55    };
56
57    if !output.status.success() {
58        return Ok(RunExecution {
59            status: output.status,
60            progress_report: None,
61        });
62    }
63
64    let days: Vec<(usize, usize)> =
65        serde_json::from_slice(&output.stdout).map_err(RunError::InvalidPlan)?;
66
67    if days.is_empty()
68        || days
69            .iter()
70            .any(|(year, day)| !(2015..=9999).contains(year) || !(1..=25).contains(day))
71    {
72        return Err(RunError::InvalidPlanDays);
73    }
74
75    let mut inputs = InputStore::global()?;
76
77    for &(year, day) in &days {
78        inputs.get(year, day)?;
79    }
80
81    let (status, report_bytes) = match project.config.project.language {
82        Language::Rust if request_report => {
83            adapters::rust::run_with_report(project, options, inputs.account_root())?
84        }
85        Language::Rust => (
86            adapters::rust::run(project, options, inputs.account_root())?,
87            None,
88        ),
89    };
90
91    let progress_report = report_bytes
92        .as_deref()
93        .map(|bytes| ProgressReport::decode(bytes, &days, options.part))
94        .transpose()?;
95
96    Ok(RunExecution {
97        status,
98        progress_report,
99    })
100}
101
102#[derive(Debug, thiserror::Error)]
103pub enum RunOptionsError {
104    #[error("Day must be between 1 and 25")]
105    InvalidDay,
106
107    #[error("Part must be either 1 or 2")]
108    InvalidPart,
109
110    #[error("--all cannot be combined with --day or --part")]
111    AllConflict,
112
113    #[error("--day is required when using --year with --part")]
114    MissingDay,
115}
116
117impl RunOptions {
118    /// # Errors
119    ///
120    /// Returns an error if the options are invalid.
121    pub fn validate(&self) -> Result<(), RunOptionsError> {
122        if self.day.is_some_and(|day| !(1..=25).contains(&day)) {
123            return Err(RunOptionsError::InvalidDay);
124        }
125
126        if self.part.is_some_and(|part| !(1..=2).contains(&part)) {
127            return Err(RunOptionsError::InvalidPart);
128        }
129
130        if self.all && (self.day.is_some() || self.part.is_some()) {
131            return Err(RunOptionsError::AllConflict);
132        }
133
134        if self.year.is_some() && self.part.is_some() && self.day.is_none() {
135            return Err(RunOptionsError::MissingDay);
136        }
137
138        Ok(())
139    }
140}
141
142#[derive(Debug, thiserror::Error)]
143pub enum RunError {
144    #[error(transparent)]
145    InvalidOptions(#[from] RunOptionsError),
146
147    #[error("Failed to execute runner: {0}")]
148    Process(#[from] std::io::Error),
149
150    #[error("Cannot decode runner execution plan: {0}")]
151    InvalidPlan(#[source] serde_json::Error),
152
153    #[error("Runner returned an invalid execution plan")]
154    InvalidPlanDays,
155
156    #[error(transparent)]
157    Client(#[from] ClientError),
158
159    #[error(transparent)]
160    InvalidProgressReport(#[from] ProgressReportError),
161}