use crate::project::{Language, Project};
use crate::{ClientError, InputStore, adapters};
use std::process::ExitStatus;
#[derive(Debug, Default, Clone, Copy)]
pub struct RunOptions {
pub year: Option<usize>,
pub day: Option<u8>,
pub part: Option<u8>,
pub all: bool,
}
pub fn execute(project: &Project, options: &RunOptions) -> Result<ExitStatus, RunError> {
options.validate()?;
let output = match project.config.project.language {
Language::Rust => adapters::rust::plan(project, options)?,
};
if !output.status.success() {
return Ok(output.status);
}
let days: Vec<(usize, usize)> =
serde_json::from_slice(&output.stdout).map_err(RunError::InvalidPlan)?;
if days.is_empty()
|| days
.iter()
.any(|(year, day)| !(2015..=9999).contains(year) || !(1..=25).contains(day))
{
return Err(RunError::InvalidPlanDays);
}
let mut inputs = InputStore::global()?;
for (year, day) in days {
inputs.get(year, day)?;
}
match project.config.project.language {
Language::Rust => Ok(adapters::rust::run(
project,
options,
inputs.account_root(),
)?),
}
}
#[derive(Debug, thiserror::Error)]
pub enum RunOptionsError {
#[error("Day must be between 1 and 25")]
InvalidDay,
#[error("Part must be either 1 or 2")]
InvalidPart,
#[error("--all cannot be combined with --day or --part")]
AllConflict,
#[error("--day is required when using --year with --part")]
MissingDay,
}
impl RunOptions {
pub fn validate(&self) -> Result<(), RunOptionsError> {
if self.day.is_some_and(|day| !(1..=25).contains(&day)) {
return Err(RunOptionsError::InvalidDay);
}
if self.part.is_some_and(|part| !(1..=2).contains(&part)) {
return Err(RunOptionsError::InvalidPart);
}
if self.all && (self.day.is_some() || self.part.is_some()) {
return Err(RunOptionsError::AllConflict);
}
if self.year.is_some() && self.part.is_some() && self.day.is_none() {
return Err(RunOptionsError::MissingDay);
}
Ok(())
}
}
#[derive(Debug, thiserror::Error)]
pub enum RunError {
#[error(transparent)]
InvalidOptions(#[from] RunOptionsError),
#[error("Failed to execute runner: {0}")]
Process(#[from] std::io::Error),
#[error("Cannot decode runner execution plan: {0}")]
InvalidPlan(#[source] serde_json::Error),
#[error("Runner returned an invalid execution plan")]
InvalidPlanDays,
#[error(transparent)]
Client(#[from] ClientError),
}