use std::sync::Mutex;
use isothrum_runner::{ProcessError, ProcessSpec, Stream};
use crate::context::Context;
use crate::host::tool_path::{self, Env};
#[derive(Debug)]
#[non_exhaustive]
pub struct Step {
pub program: String,
pub args: Vec<String>,
pub note: Option<Note>,
pub interactions: Vec<super::Interaction>,
pub(crate) private: Option<tempfile::TempDir>,
pub(crate) not_served: Option<NotServed>,
}
pub(crate) const NOT_SERVED: i32 = 69;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NotServed {
DockerDistribution,
HypervEdition,
}
impl Step {
pub(crate) fn not_served(mut self, why: NotServed) -> Step {
self.not_served = Some(why);
self
}
}
#[must_use]
pub fn step(program: impl Into<String>, args: &[&str]) -> Step {
Step {
program: program.into(),
args: args.iter().map(ToString::to_string).collect(),
note: None,
interactions: Vec::new(),
private: None,
not_served: None,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Note {
InstallingFromVendor {
dependency: super::Dependency,
agreement: Option<Agreement>,
},
QemuUpdatingHomebrewFirst,
BuildsFromSource(super::Dependency),
TrustingAzureTap,
AzureCliCask,
DownloadingVmwareUtility {
version: &'static str,
},
Removing(super::Dependency),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Agreement {
pub name: &'static str,
pub url: &'static str,
}
#[must_use]
pub fn command_line(step: &Step) -> String {
format!("$ {} {}", step.program, step.args.join(" "))
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StepFailed {
NoPkexec,
Missing {
program: String,
},
NotStarted(String),
PromptRefused,
NoPolkitAgent,
SudoRefused,
NotServed(NotServed),
Homebrew(super::brew::Trouble),
Exited {
program: String,
code: Option<i32>,
known: Option<super::exit_codes::Known>,
},
}
impl std::fmt::Display for StepFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
StepFailed::NoPkexec => f.write_str("pkexec isn't installed: no password prompt can be shown"),
StepFailed::Missing { program } => write!(f, "{program} isn't installed"),
StepFailed::NotStarted(why) => write!(f, "the step couldn't be started: {why}"),
StepFailed::PromptRefused => f.write_str("the password prompt was dismissed or the password refused"),
StepFailed::NoPolkitAgent => f.write_str("no password prompt could be shown: no polkit agent runs"),
StepFailed::SudoRefused => f.write_str("sudo needs a password, and none can be asked for unattended"),
StepFailed::NotServed(why) => write!(f, "this system isn't one the step serves: {why:?}"),
StepFailed::Homebrew(trouble) => write!(f, "Homebrew is broken: {trouble:?}"),
StepFailed::Exited { program, code: Some(code), .. } => write!(f, "`{program}` exited with code {code}"),
StepFailed::Exited { program, code: None, .. } => write!(f, "`{program}` was ended by a signal"),
}
}
}
impl std::error::Error for StepFailed {}
pub async fn run_steps(cx: &Context, steps: &[Step], on_line: &mut (dyn FnMut(&str) + Send)) -> Result<(), StepFailed> {
for step in steps {
if step.note.is_none() {
on_line(&command_line(step));
}
run_step(cx, step, on_line).await?;
}
Ok(())
}
pub async fn run_step(cx: &Context, step: &Step, on_line: &mut (dyn FnMut(&str) + Send)) -> Result<Option<super::exit_codes::Done>, StepFailed> {
run_step_on(cx, step, &Env::here(), on_line).await
}
pub(crate) async fn run_step_on(
cx: &Context,
step: &Step,
env: &Env,
on_line: &mut (dyn FnMut(&str) + Send),
) -> Result<Option<super::exit_codes::Done>, StepFailed> {
let mut spec = ProcessSpec::new(&step.program, step.args.iter().map(String::as_str));
if let Some(path) = tool_path::refreshed_value(cx, env).await {
spec.env.push(("PATH".to_owned(), path));
}
let watch = Mutex::new(Watch::new(step));
let exit = {
let mut each = |stream: Stream, line: &str| {
let mut watched = watch.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
watched.line(line);
if stream == Stream::Stderr {
watched.error_line(line);
}
drop(watched);
on_line(line);
};
cx.runner.run(&spec, &mut each).await
};
let exit = match exit {
Ok(exit) => exit,
Err(ProcessError::Missing { .. }) if step.program == "pkexec" => return Err(StepFailed::NoPkexec),
Err(ProcessError::Missing { program }) => return Err(StepFailed::Missing { program }),
Err(e) => return Err(StepFailed::NotStarted(e.to_string())),
};
watch.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner).end(step, exit.code)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Program {
Winget,
Powershell,
Pkexec,
UnattendedSudo,
Other,
}
fn is_brew_step(step: &Step) -> bool {
step.program.contains("brew") || step.args.iter().any(|a| a.contains("brew"))
}
impl Program {
fn of(step: &Step) -> Program {
match step.program.as_str() {
"winget" => Program::Winget,
"powershell" => Program::Powershell,
"pkexec" => Program::Pkexec,
"sudo" if step.args.first().is_some_and(|a| a == "-n") => Program::UnattendedSudo,
_ => Program::Other,
}
}
}
#[derive(Debug)]
struct Watch {
program: Program,
pkexec_refusal: Option<super::pkexec::Refusal>,
sudo_refused: bool,
brew: bool,
brew_trouble: Option<super::brew::Trouble>,
installer_code: Option<u32>,
}
impl Watch {
fn new(step: &Step) -> Watch {
Watch {
program: Program::of(step),
pkexec_refusal: None,
sudo_refused: false,
brew: is_brew_step(step),
brew_trouble: None,
installer_code: None,
}
}
fn line(&mut self, line: &str) {
if self.program == Program::Winget {
self.installer_code = super::exit_codes::installer_exit_code(line).or(self.installer_code);
}
}
fn error_line(&mut self, line: &str) {
if self.program == Program::Pkexec
&& let Some(refusal) = super::pkexec::Refusal::of_line(line)
{
self.pkexec_refusal = Some(refusal);
}
if self.program == Program::UnattendedSudo && line.starts_with("sudo: ") && line.contains("password") {
self.sudo_refused = true;
}
if self.brew && self.brew_trouble.is_none() {
self.brew_trouble = super::brew::Trouble::of_line(line);
}
}
fn end(self, step: &Step, code: Option<i32>) -> Result<Option<super::exit_codes::Done>, StepFailed> {
if let Some(refusal) = self.pkexec_refusal.filter(|_| matches!(code, Some(126 | 127))) {
return Err(match refusal {
super::pkexec::Refusal::NoAgent => StepFailed::NoPolkitAgent,
super::pkexec::Refusal::Refused => StepFailed::PromptRefused,
});
}
if code == Some(0) {
return Ok(None);
}
if self.program == Program::Winget
&& let Some(done) = super::exit_codes::winget_done(code)
{
return Ok(Some(done));
}
if self.sudo_refused {
return Err(StepFailed::SudoRefused);
}
if let Some(why) = step.not_served.filter(|_| code == Some(NOT_SERVED)) {
return Err(StepFailed::NotServed(why));
}
if let Some(trouble) = self.brew_trouble {
return Err(StepFailed::Homebrew(trouble));
}
let known = match self.program {
Program::Winget => super::exit_codes::winget_failure(code, self.installer_code),
Program::Powershell => super::exit_codes::installer_failure(code),
Program::Pkexec | Program::UnattendedSudo | Program::Other => None,
};
Err(StepFailed::Exited {
program: step.program.clone(),
code,
known,
})
}
}
#[cfg(test)]
mod tests;