Skip to main content

aoc_toolkit/adapters/rust/
run.rs

1use std::io;
2use std::path::Path;
3use std::process::{Command, ExitStatus, Output, Stdio};
4
5use crate::application::run::RunOptions;
6use crate::project::Project;
7
8fn cargo_command(project: &Project) -> Command {
9    let mut command = Command::new("cargo");
10
11    command
12        .current_dir(&project.root)
13        .env_remove("SESSION_ID")
14        .env_remove("AOC_TOOLKIT_RUNNER_REPORT_FILE")
15        .arg("run")
16        .arg("--quiet")
17        .arg("--profile")
18        .arg(&project.config.runner.profile)
19        .arg("--manifest-path")
20        .arg(project.manifest_path());
21
22    if let Some(binary) = &project.config.runner.binary {
23        command.arg("--bin").arg(binary);
24    }
25
26    command.arg("--");
27    command
28}
29
30fn command(project: &Project, options: &RunOptions) -> Command {
31    let mut command = cargo_command(project);
32    command.arg("run");
33
34    if let Some(year) = options.year {
35        command.arg("--year").arg(year.to_string());
36    }
37
38    if let Some(day) = options.day {
39        command.arg("--day").arg(day.to_string());
40    }
41
42    if let Some(part) = options.part {
43        command.arg("--part").arg(part.to_string());
44    }
45
46    if options.all {
47        command.arg("--all");
48    }
49
50    command
51}
52
53pub(crate) fn list_registered_days(project: &Project) -> io::Result<Output> {
54    cargo_command(project).arg("registry").output()
55}
56
57pub(crate) fn plan(project: &Project, options: &RunOptions) -> io::Result<Output> {
58    command(project, options)
59        .arg("--plan")
60        .stderr(Stdio::inherit())
61        .output()
62}
63
64/// Executes the local Rust runner using prepared puzzle inputs.
65///
66/// # Errors
67///
68/// Returns an error if the runner process cannot be executed.
69pub fn run(project: &Project, options: &RunOptions, input_dir: &Path) -> io::Result<ExitStatus> {
70    run_command(project, options, input_dir).status()
71}
72
73fn run_command(project: &Project, options: &RunOptions, input_dir: &Path) -> Command {
74    let mut command = command(project, options);
75    command.arg("--input-dir").arg(input_dir);
76    command
77}
78
79pub(crate) fn run_with_report(
80    project: &Project,
81    options: &RunOptions,
82    input_dir: &Path,
83) -> io::Result<(ExitStatus, Option<Vec<u8>>)> {
84    let directory = tempfile::tempdir()?;
85    let report_path = directory.path().join("progress.json");
86
87    let status = run_command(project, options, input_dir)
88        .env("AOC_TOOLKIT_RUNNER_REPORT_FILE", &report_path)
89        .status()?;
90
91    let report = match std::fs::read(&report_path) {
92        Ok(bytes) => Some(bytes),
93        Err(error) if error.kind() == io::ErrorKind::NotFound => None,
94        Err(error) => return Err(error),
95    };
96
97    Ok((status, report))
98}