use std::ffi::OsString;
use std::fmt;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, Instant};
use crumbkit::{Failure, Recovery, Run, Sink};
use starmap::{
Bindings, Bound, Environment, Mode, Name, NoPlace, Placeholder, Problem, ProviderKind, Source,
Spec, Verdict,
};
use starmap_resolve::{
AppName, Context, Keychain, Lookup, OnePassword, Places, ResolveProblem, Resolver, SecretError,
Slot, WorkspaceName, resolve,
};
use crate::cli::{Assignment, RunArgs, SpecFile};
use crate::codes::{
BIND_NO_PLACE, BIND_NO_PROVIDER, SECRET_UNBOUND, SECRET_UNREADABLE, VARIABLE_INVALID,
VARIABLE_MISSING, VARIABLE_SECRET, VARIABLE_UNKNOWN,
};
use crate::dotenv::{self, DotEnvFailure};
use crate::spec::{self, SpecFailure};
use crate::{files, mode};
mod ask;
mod child;
#[cfg(test)]
mod tests;
pub(crate) use ask::{Ask, Terminal};
const RESOLVE_DEADLINE: Duration = Duration::from_secs(60);
const SAVE_DEADLINE: Duration = Duration::from_secs(30);
const TEXT_ONLY: &str = "this command hands the terminal to another program";
pub(crate) fn run(
args: &RunArgs,
vars: Vec<(OsString, OsString)>,
output: Run,
notes: &mut dyn Write,
) -> ExitCode {
let one_password = OnePassword::new(PathBuf::from("op"));
let keychain = Keychain::new();
run_with(args, vars, output, notes, &[&one_password, &keychain])
}
fn run_with(
args: &RunArgs,
vars: Vec<(OsString, OsString)>,
mut output: Run,
notes: &mut dyn Write,
resolvers: &[&dyn Resolver],
) -> ExitCode {
let mut sink = Sink::standard();
if let Some(code) = output.refuse_fields_for_text(&mut sink, TEXT_ONLY) {
return code;
}
let mut command = child::command(&args.program);
let gathered = match gather(args, vars) {
Ok(gathered) => gathered,
Err(refused) => return refuse(&mut sink, &mut output, &refused, notes),
};
if output.is_json() {
print_notes(notes, &gathered.notes);
return crumbkit_child::hand_over(output, command);
}
let interactive = !output.no_input() && ask::terminals();
let settled = {
let mut terminal = Terminal::new(&mut output, interactive);
settle(gathered, resolvers, &mut terminal)
};
match settled {
Ok(ready) => {
print_notes(notes, &ready.notes);
ready.environment.apply(&mut command);
crumbkit_child::hand_over(output, command)
}
Err(refused) => refuse(&mut sink, &mut output, &refused, notes),
}
}
fn refuse<O: Write, E: Write>(
sink: &mut Sink<O, E>,
output: &mut Run,
refused: &Refused,
notes: &mut dyn Write,
) -> ExitCode {
for failure in &refused.failures {
output.print_failure(sink, failure);
}
print_notes(notes, &refused.notes);
let code = refused
.failures
.first()
.map_or(1, |failure| output.failure_exit(failure.code()));
crumbkit::events::ended(code, None)
}
fn print_notes(notes: &mut dyn Write, lines: &[String]) {
for line in lines {
let _ = writeln!(notes, "{line}");
}
}
#[derive(Debug)]
pub(crate) struct Ready {
pub(crate) environment: Environment,
pub(crate) notes: Vec<String>,
}
#[derive(Debug)]
pub(crate) struct Refused {
pub(crate) failures: Vec<RunFailure>,
pub(crate) notes: Vec<String>,
}
impl Refused {
fn new(failures: Vec<RunFailure>, mut notes: Vec<String>) -> Self {
let count = failures.len();
let problems = if count == 1 { "problem" } else { "problems" };
notes.push(format!(
"starmap started nothing, because of {count} {problems}."
));
Self { failures, notes }
}
}
#[derive(Debug)]
pub(crate) struct Gathered {
spec: Spec,
file: String,
caller: Bindings,
mode: Mode,
places: Places,
workspace: WorkspaceName,
app: AppName,
notes: Vec<String>,
}
pub(crate) fn gather(args: &RunArgs, vars: Vec<(OsString, OsString)>) -> Result<Gathered, Refused> {
let mut notes = Vec::new();
let path = &args.file.spec;
let spec::Opened { spec, located } =
spec::open(path).map_err(|failure| Refused::new(vec![failure.into()], Vec::new()))?;
let checkout = checkout(path)?;
let dotenv_file = located.dotenv;
let dotenv = dotenv::read(&dotenv_file, &spec).map_err(|failures| {
Refused::new(failures.into_iter().map(Into::into).collect(), Vec::new())
})?;
if !dotenv.undeclared.is_empty() {
notes.push(format!(
"{} sets {}, which {} does not declare, so the program does not receive {}.",
dotenv_file.display(),
dotenv.undeclared.join(", "),
located.file.display(),
if dotenv.undeclared.len() == 1 {
"it"
} else {
"them"
},
));
}
let home = vars
.iter()
.find(|(key, _)| key == "HOME")
.map(|(_, value)| PathBuf::from(value));
let overrides =
assignments(&spec, &args.set).map_err(|failures| Refused::new(failures, notes.clone()))?;
let values = dotenv.values.into_iter().chain(vars).chain(overrides);
let caller = starmap::capture(&spec, values);
let (mode, mode_note) = mode::decide(&spec, &caller);
notes.push(mode_note);
let app = AppName::of_dir(&checkout);
let workspace = args
.workspace
.clone()
.unwrap_or_else(|| WorkspaceName::from(&app));
let mut places =
Places::new(checkout.clone()).workspace(workspace.clone(), app.clone(), checkout);
if let Some(home) = home {
places = places.home(home);
}
Ok(Gathered {
spec,
file: path.display().to_string(),
caller,
mode,
places,
workspace,
app,
notes,
})
}
pub(crate) fn settle(
gathered: Gathered,
resolvers: &[&dyn Resolver],
ask: &mut dyn Ask,
) -> Result<Ready, Refused> {
let Gathered {
spec,
file,
caller,
mode,
places,
workspace,
app,
mut notes,
} = gathered;
let deadline = Instant::now() + RESOLVE_DEADLINE;
let mut context = Context::new(places, &caller, deadline);
for resolver in resolvers {
context = context.resolver(*resolver);
}
let resolution = resolve(&spec, mode, &context);
for name in &resolution.ignored {
notes.push(ignored_note(&spec, name));
}
let mut bindings = resolution.bindings;
let (unbound, other): (Vec<_>, Vec<_>) = resolution
.failures
.into_iter()
.partition(|failure| matches!(failure.problem, ResolveProblem::Unbound));
let mut failures: Vec<RunFailure> = other
.into_iter()
.map(|failure| RunFailure::resolve(failure.name, failure.problem))
.collect();
if failures.is_empty()
&& !unbound.is_empty()
&& let Verdict::Refused(refusals) = starmap::check(&spec, &bindings, mode)
{
failures.extend(
refusals
.iter()
.filter(|finding| !unbound.iter().any(|failure| failure.name == finding.name))
.map(|finding| RunFailure::check(finding.name.clone(), &finding.problem, &file)),
);
}
let can_start = failures.is_empty();
for failure in unbound {
let typed = if can_start {
typed(
Slot::new(&workspace, &app, &failure.name),
resolvers,
ask,
&mut notes,
)
} else {
None
};
match typed {
Some(bound) => bindings.bind(failure.name, bound),
None => failures.push(RunFailure::Unbound { name: failure.name }),
}
}
if !failures.is_empty() {
return Err(Refused::new(failures, notes));
}
checked(&spec, &file, &bindings, mode, notes)
}
fn checked(
spec: &Spec,
file: &str,
bindings: &Bindings,
mode: Mode,
notes: Vec<String>,
) -> Result<Ready, Refused> {
match starmap::check(spec, bindings, mode) {
Verdict::Ready(environment) => Ok(Ready { environment, notes }),
Verdict::Refused(refusals) => {
let failures = refusals
.iter()
.map(|finding| RunFailure::check(finding.name.clone(), &finding.problem, file))
.collect();
Err(Refused::new(failures, notes))
}
}
}
fn typed(
slot: Slot<'_>,
resolvers: &[&dyn Resolver],
ask: &mut dyn Ask,
notes: &mut Vec<String>,
) -> Option<Bound> {
if !ask.can_ask() {
return None;
}
let name = slot.name;
let secret = ask.secret(name)?;
let lookup = Lookup::Saved { slot };
let (workspace, app) = (slot.workspace.as_str(), slot.app.as_str());
let question = format!(
"Save {name} to the Keychain for workspace {workspace} and app {app}, so later runs find it?"
);
if ask.save(&question) {
let deadline = Instant::now() + SAVE_DEADLINE;
let mut result = Err(SecretError::Unsupported);
for resolver in resolvers {
result = resolver.save(lookup, &secret, deadline);
if !matches!(result, Err(SecretError::Unsupported)) {
break;
}
}
notes.push(match result {
Ok(()) => format!(
"The Keychain holds {name} as service starmap.{workspace} and account {app}/{name}, and later runs read it from there."
),
Err(error) => format!(
"starmap could not save {name} to the Keychain, because {error}, so only this run has it."
),
});
}
Some(Bound::Secret(secret))
}
fn ignored_note(spec: &Spec, name: &Name) -> String {
let used = match spec.variable(name).map(starmap::Variable::source) {
Some(Source::Generated { .. }) => "its generated value in the Keychain",
_ => "its bind",
};
format!("{name} is set in this shell, and starmap ignored it and used {used}.")
}
fn assignments(
spec: &Spec,
set: &[Assignment],
) -> Result<Vec<(OsString, OsString)>, Vec<RunFailure>> {
let mut values = Vec::new();
let mut failures = Vec::new();
for assignment in set {
let name = &assignment.name;
match spec.variable(name).map(starmap::Variable::source) {
None => failures.push(RunFailure::Unknown { name: name.clone() }),
Some(Source::Secret { .. } | Source::Generated { .. }) => {
failures.push(RunFailure::SetSecret { name: name.clone() });
}
Some(_) => values.push((
OsString::from(name.as_str()),
OsString::from(&assignment.value),
)),
}
}
if failures.is_empty() {
Ok(values)
} else {
Err(failures)
}
}
fn checkout(path: &Path) -> Result<PathBuf, Refused> {
let file = path.display().to_string();
files::canonical(path)
.map(|path| path.parent().map(Path::to_path_buf).unwrap_or(path))
.map_err(|error| {
Refused::new(
vec![SpecFailure::Unreadable { file, error }.into()],
Vec::new(),
)
})
}
#[derive(Debug, Failure)]
pub(crate) enum RunFailure {
#[failure(forward, diagnostic)]
Spec(SpecFailure),
#[failure(forward)]
DotEnv(DotEnvFailure),
#[failure(
code = VARIABLE_UNKNOWN,
hint = "declare {name} in starmap.toml",
alternative = Recovery::Hint(format!("remove --set {name}")),
field(key = name.as_str()),
)]
Unknown {
name: Name,
},
#[failure(
code = VARIABLE_SECRET,
hint = "remove --set {name}, and give {name} a bind in starmap.toml",
alternative = Recovery::Hint(format!(
"remove --set {name}, and let starmap run ask for it at a terminal"
)),
field(key = name.as_str()),
)]
SetSecret {
name: Name,
},
#[failure(
code = VARIABLE_MISSING,
hint = "set {name} in this shell, in .env or with --set {name}=VALUE",
field(key = name.as_str()),
)]
Missing {
name: Name,
mode: Mode,
},
#[failure(
code = VARIABLE_INVALID,
recovery = Recovery::Run(SpecFile::call(&["explain"], file).value("names", name.as_str())),
field(key = name.as_str()),
)]
Invalid {
name: Name,
problem: String,
file: String,
},
#[failure(
code = BIND_NO_PROVIDER,
hint = "set {name} in this shell, in .env or with --set {name}=VALUE",
alternative = Recovery::Hint(format!("start the app under a host that provides {kind}")),
field(key = name.as_str()),
)]
NoProvider {
name: Name,
kind: ProviderKind,
},
#[failure(
code = BIND_NO_PLACE,
hint = "set HOME in this shell",
alternative = Recovery::Hint(format!("set {name} with --set {name}=VALUE")),
field(key = name.as_str()),
)]
NoPlace {
name: Name,
placeholder: Placeholder,
},
#[failure(
code = SECRET_UNBOUND,
hint = "run starmap run at a terminal without --no-input, type {name} and save it to the Keychain",
alternative = Recovery::Hint(format!(
"give {name} a bind in starmap.toml, such as {{ one-password = \"op://vault/item/field\" }}"
)),
field(key = name.as_str()),
)]
Unbound {
name: Name,
},
#[failure(
code = SECRET_UNREADABLE,
hint = "starmap run keeps generated values only in the macOS login keychain, so run it in a macOS session that has one, or make {name} a secret with a one-password bind in starmap.toml",
field(key = name.as_str()),
)]
NoStore {
name: Name,
},
#[failure(
code = SECRET_UNREADABLE,
hint = "check the bind of {name} in starmap.toml, unlock 1Password or the Keychain, and check that the 1Password CLI op is installed and signed in, then run the command again",
field(key = name.as_str()),
)]
Secret {
name: Name,
error: SecretError,
},
}
impl RunFailure {
fn resolve(name: Name, problem: ResolveProblem) -> Self {
match problem {
ResolveProblem::NoProvider(kind) => Self::NoProvider { name, kind },
ResolveProblem::NoPlace(NoPlace(placeholder)) => Self::NoPlace { name, placeholder },
ResolveProblem::Unbound => Self::Unbound { name },
ResolveProblem::Secret(error) => Self::Secret { name, error },
ResolveProblem::Deadline => Self::Secret {
name,
error: SecretError::Deadline,
},
ResolveProblem::NoResolver => Self::NoStore { name },
ResolveProblem::Provider(error) => Self::Secret {
name,
error: SecretError::Program(io::Error::other(error.to_string())),
},
_ => Self::Secret {
name,
error: SecretError::Program(io::Error::other("the value could not be resolved")),
},
}
}
fn check(name: Name, problem: &Problem, file: &str) -> Self {
let file = file.to_owned();
match problem {
Problem::Missing { mode } => Self::Missing { name, mode: *mode },
Problem::Invalid(error) => Self::Invalid {
name,
problem: error.to_string(),
file,
},
Problem::ShowMismatch { .. } => Self::Invalid {
name,
problem: "the value is held as a secret where starmap.toml shows it, or the other way round"
.to_owned(),
file,
},
Problem::ModeMismatch { decided } => Self::Invalid {
name,
problem: format!("the resolved value decides {decided} mode"),
file,
},
_ => Self::Invalid {
name,
problem: "the value does not fit the variable".to_owned(),
file,
},
}
}
}
impl fmt::Display for RunFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Spec(failure) => failure.fmt(formatter),
Self::DotEnv(failure) => failure.fmt(formatter),
Self::Unknown { name } => {
write!(
formatter,
"--set names {name}, which starmap.toml does not declare"
)
}
Self::SetSecret { name } => write!(
formatter,
"--set gives {name} a value, and starmap.toml declares it as a secret"
),
Self::Missing { name, mode } => {
write!(
formatter,
"{name} is required in {mode} mode and has no value"
)
}
Self::Invalid { name, problem, .. } => write!(formatter, "{name}: {problem}"),
Self::NoProvider { name, kind } => write!(
formatter,
"{name} needs a value from the provider {kind}, and starmap run has no provider of that kind"
),
Self::NoPlace { name, placeholder } => write!(
formatter,
"the path bind of {name} uses {placeholder}, and starmap run has no directory for it"
),
Self::Unbound { name } => write!(
formatter,
"{name} is a secret with no bind, no value in this shell and no value saved in the Keychain"
),
Self::NoStore { name } => write!(
formatter,
"no secret store that starmap run uses on this machine handles {name}"
),
Self::Secret { name, error } => {
write!(formatter, "{name} could not be read, because {error}")
}
}
}
}
impl std::error::Error for RunFailure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Spec(failure) => failure.source(),
Self::DotEnv(failure) => failure.source(),
Self::Secret { error, .. } => Some(error),
_ => None,
}
}
}
impl From<SpecFailure> for RunFailure {
fn from(failure: SpecFailure) -> Self {
Self::Spec(failure)
}
}
impl From<DotEnvFailure> for RunFailure {
fn from(failure: DotEnvFailure) -> Self {
Self::DotEnv(failure)
}
}