use std::path::PathBuf;
use shep_core::config::discover;
use shep_core::paths::ShepPaths;
use crate::cli::RuntimeArgs;
use crate::commands::foreground::{self, ForegroundOptions};
use crate::commands::lifecycle::{resolve_target, target_exit_code};
use crate::commands::reap;
use crate::exit::ExitCode;
use crate::output::Streams;
const DISCOVERY_NAMES: &str = "Flockfile.toml, Flockfile.yaml, Flockfile.yml, Flockfile.json, \
Flockfile.json5, flockfile.toml, flockfile.yaml, flockfile.yml, flockfile.json, \
flockfile.json5";
pub async fn runtime(
streams: &mut Streams<'_>,
quiet: bool,
paths: ShepPaths,
args: &RuntimeArgs,
) -> ExitCode {
let target = match &args.target {
Some(target) => target.clone(),
None => match discovered_target(streams) {
Ok(target) => target,
Err(code) => return code,
},
};
let apps = match resolve_target(&target, None, &[], false) {
Ok(apps) => apps,
Err(err) => {
let code = target_exit_code(&err);
return streams.fail(code, &err.to_string());
}
};
let options = ForegroundOptions {
paths,
apps,
tidy_up: false,
};
let forced = std::env::var_os("SHEP_FORCE_INIT").is_some();
if !reap::should_split(std::process::id(), args.supervise, forced) {
return foreground::run(streams, quiet, options).await;
}
match reap::run_init().await {}
}
pub(crate) fn discovered_target(streams: &mut Streams<'_>) -> Result<String, ExitCode> {
let cwd = get_cwd(streams)?;
match discover(&cwd) {
Some(path) => Ok(path.to_string_lossy().into_owned()),
None => {
let message = format!(
"no Flockfile found in {} (looked for {DISCOVERY_NAMES})",
cwd.display()
);
Err(streams.fail(ExitCode::Usage, &message))
}
}
}
pub(crate) fn get_cwd(streams: &mut Streams<'_>) -> Result<PathBuf, ExitCode> {
std::env::current_dir().map_err(|err| {
let message = format!("could not read the current directory: {err}");
streams.fail(ExitCode::Usage, &message)
})
}