use std::ffi::OsString;
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Instant;
use cuno_build::exec::SystemSpawner;
use cuno_build::pipeline::{self, Request, Toolchain};
use cuno_build::{bundled, toolchain};
use cuno_core::{CunoError, Env, ExitClass, Shell};
use cuno_manifest::{ConfigError, Profile, Settings};
use cuno_toolchain::msvc::SystemRegistry;
use cuno_toolchain::{HostOs, SystemRunner};
#[derive(Debug, Default)]
pub struct BuildArgs {
pub release: bool,
pub profile: Option<String>,
pub target: Option<String>,
pub fetching: crate::Fetching,
}
pub(crate) fn in_project(
resolved: Result<Settings, ConfigError>,
cwd: &Path,
) -> Result<Settings, Box<dyn CunoError>> {
match cuno_manifest::find_project(cwd, cuno_core::NameCase::host()) {
Ok(Some(_)) => resolved.map_err(boxed),
Ok(None) => Err(Box::new(CommandError::NoProject {
cwd: cwd.to_owned(),
})),
Err(error) => Err(boxed(error)),
}
}
#[derive(Debug)]
pub enum Goal {
Build,
Check {
programs: bool,
tests: bool,
},
Run {
bin: Option<String>,
args: Vec<OsString>,
},
Test {
filter: Option<String>,
nocapture: bool,
},
}
#[allow(clippy::too_many_arguments)]
pub fn build(
goal: Goal,
args: BuildArgs,
settings: Result<Settings, ConfigError>,
env: &Env,
cwd: &Path,
host: HostOs,
temp: &Path,
shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
let started = Instant::now();
refuse_target(args.target.as_deref())?;
let profile = profile_named(args.release, args.profile.as_deref())?;
let settings = in_project(settings, cwd)?;
let settings =
crate::with_dependencies(settings, args.fetching, env, host, cwd, shell).map_err(boxed)?;
let package = settings
.project
.as_ref()
.expect("in_project found the project the settings were read from");
let (root, manifest) = (package.root(), &package.manifest);
let runner = SystemRunner::new();
let toolchain::Ready {
selected, prepared, ..
} = toolchain::ready(
toolchain::ReadyFor::Build,
&settings,
package,
profile,
env,
host,
temp,
&runner,
&SystemRegistry,
shell,
)?;
let jobs = settings.jobs.get() as usize;
let (pipeline_goal, run) = match &goal {
Goal::Build => (pipeline::Goal::Build, None),
Goal::Check { programs, tests } => (
pipeline::Goal::Check {
programs: *programs,
tests: *tests,
},
None,
),
Goal::Run { bin, args } => (
pipeline::Goal::Run {
bin: bin.as_deref(),
},
Some(args),
),
Goal::Test { .. } => (pipeline::Goal::Test, None),
};
let bundled = bundled::expand(&settings.home).map_err(boxed)?;
let request = Request {
package,
target_dir: &settings.target_dir,
profile,
goal: pipeline_goal,
host,
bundled: &bundled,
jobs,
started,
toolchain: Toolchain::new(&selected, &prepared),
spawner: &SystemSpawner,
};
for warning in cuno_tools::write_editor_files(root, manifest) {
shell.warning(warning);
}
let built = pipeline::build(&request, shell).map_err(boxed)?;
if let Goal::Test { filter, nocapture } = &goal {
let executables: Vec<cuno_test::TestExecutable> = built
.test_executables
.into_iter()
.map(|test| cuno_test::TestExecutable {
path: test.path,
integration: test.file.is_some(),
})
.collect();
let layout = cuno_build::layout::Layout::new(&settings.target_dir, profile, root, host);
let scratch = layout.for_tests().test_dir();
let mut path = std::ffi::OsString::from(layout.profile_dir());
if let Some(rest) = env.get("PATH") {
path.push(";");
path.push(rest);
}
let test_env = env.with("PATH", path);
let summary = cuno_test::run(
&cuno_test::TestRun {
executables: &executables,
filter: filter.as_deref(),
nocapture: *nocapture,
jobs,
root,
cwd,
env: &test_env,
scratch: &scratch,
case: host.name_case(),
launcher: &cuno_test::SystemLauncher,
tests_dir: cuno_build::sources::TESTS_DIR,
scratch_command: cuno_build::pipeline::TEST_SCRATCH_COMMAND,
result_file: cuno_build::pipeline::test_result_file,
},
shell,
);
return Ok(if summary.succeeded() { 0 } else { 1 });
}
let (Some(exe), Some(args)) = (built.exe, run) else {
return Ok(0);
};
let shown = cuno_core::program::shown(&exe, cwd);
shell.status("Running", format!("`{}`", shown.display()));
let status = cuno_core::program::command(&exe, args, env, root)
.status()
.map_err(|e| {
Box::new(CommandError::CannotRun {
exe: exe.clone(),
reason: e.to_string(),
}) as Box<dyn CunoError>
})?;
Ok(status.code().unwrap_or(1))
}
pub(crate) fn profile_named(
release: bool,
name: Option<&str>,
) -> Result<Profile, Box<dyn CunoError>> {
if release {
return Ok(Profile::Release);
}
let Some(name) = name else {
return Ok(Profile::Dev);
};
Profile::parse(name).ok_or_else(|| {
Box::new(CommandError::UnknownProfile {
name: name.to_owned(),
}) as Box<dyn CunoError>
})
}
fn profile_names() -> String {
let names: Vec<&str> = Profile::ALL.iter().map(|(_, name)| *name).collect();
match names.split_last() {
Some((last, [])) => (*last).to_owned(),
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
None => String::new(),
}
}
pub(crate) fn refuse_target(target: Option<&str>) -> Result<(), Box<dyn CunoError>> {
match target {
Some(_) => Err(Box::new(CommandError::TargetNotSupported)),
None => Ok(()),
}
}
pub(crate) fn boxed<E: CunoError + 'static>(error: E) -> Box<dyn CunoError> {
Box::new(error)
}
#[derive(Debug)]
pub enum CommandError {
NoProject {
cwd: PathBuf,
},
UnknownProfile {
name: String,
},
TargetNotSupported,
CannotRun {
exe: PathBuf,
reason: String,
},
}
impl fmt::Display for CommandError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CommandError::NoProject { cwd } => write!(
f,
"could not find Cuno.toml in {} or any parent directory",
cwd.display()
),
CommandError::UnknownProfile { name } => write!(f, "no profile named `{name}`"),
CommandError::TargetNotSupported => f.write_str("--target is not supported yet"),
CommandError::CannotRun { exe, reason } => {
write!(f, "could not run {}: {reason}", exe.display())
}
}
}
}
impl std::error::Error for CommandError {}
impl CunoError for CommandError {
fn exit_class(&self) -> ExitClass {
match self {
CommandError::CannotRun { .. } => ExitClass::Failure,
CommandError::NoProject { .. }
| CommandError::UnknownProfile { .. }
| CommandError::TargetNotSupported => ExitClass::Setup,
}
}
fn help(&self) -> Option<String> {
match self {
CommandError::NoProject { .. } => {
Some("run it in a directory that holds a Cuno.toml, or below one".to_owned())
}
CommandError::UnknownProfile { .. } => Some(format!("use {}", profile_names())),
CommandError::TargetNotSupported | CommandError::CannotRun { .. } => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_profile_is_taken_by_its_name() {
for (profile, name) in Profile::ALL {
assert_eq!(profile_named(false, Some(name)).unwrap(), *profile);
assert!(profile_names().contains(name), "{name}");
}
assert_eq!(profile_named(false, None).unwrap(), Profile::Dev);
assert_eq!(profile_named(true, Some("dev")).unwrap(), Profile::Release);
assert!(profile_named(false, Some("bench")).is_err());
assert_eq!(profile_names(), "dev or release");
}
}