use std::io;
use std::path::Path;
use std::process::{Command, ExitStatus, Output, Stdio};
use crate::application::run::RunOptions;
use crate::project::Project;
fn cargo_command(project: &Project) -> Command {
let mut command = Command::new("cargo");
command
.current_dir(&project.root)
.env_remove("SESSION_ID")
.env_remove("AOC_TOOLKIT_RUNNER_REPORT_FILE")
.arg("run")
.arg("--quiet")
.arg("--profile")
.arg(&project.config.runner.profile)
.arg("--manifest-path")
.arg(project.manifest_path());
if let Some(binary) = &project.config.runner.binary {
command.arg("--bin").arg(binary);
}
command.arg("--");
command
}
fn command(project: &Project, options: &RunOptions) -> Command {
let mut command = cargo_command(project);
command.arg("run");
if let Some(year) = options.year {
command.arg("--year").arg(year.to_string());
}
if let Some(day) = options.day {
command.arg("--day").arg(day.to_string());
}
if let Some(part) = options.part {
command.arg("--part").arg(part.to_string());
}
if options.all {
command.arg("--all");
}
command
}
pub(crate) fn list_registered_days(project: &Project) -> io::Result<Output> {
cargo_command(project).arg("registry").output()
}
pub(crate) fn plan(project: &Project, options: &RunOptions) -> io::Result<Output> {
command(project, options)
.arg("--plan")
.stderr(Stdio::inherit())
.output()
}
pub fn run(project: &Project, options: &RunOptions, input_dir: &Path) -> io::Result<ExitStatus> {
run_command(project, options, input_dir).status()
}
fn run_command(project: &Project, options: &RunOptions, input_dir: &Path) -> Command {
let mut command = command(project, options);
command.arg("--input-dir").arg(input_dir);
command
}
pub(crate) fn run_with_report(
project: &Project,
options: &RunOptions,
input_dir: &Path,
) -> io::Result<(ExitStatus, Option<Vec<u8>>)> {
let directory = tempfile::tempdir()?;
let report_path = directory.path().join("progress.json");
let status = run_command(project, options, input_dir)
.env("AOC_TOOLKIT_RUNNER_REPORT_FILE", &report_path)
.status()?;
let report = match std::fs::read(&report_path) {
Ok(bytes) => Some(bytes),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => return Err(error),
};
Ok((status, report))
}