use std::time::Duration;
use isothrum_runner::ProcessSpec;
use crate::context::Context;
use crate::failure::{self, Failure, Refusal};
pub mod aws;
pub mod azure;
pub mod gcp;
pub mod oci;
pub mod token;
pub use token::{TokenError, digitalocean, linode};
pub use isothrum_runner::Cloud;
pub const CLI_TIMEOUT: Duration = Duration::from_secs(60);
#[must_use]
pub fn cli(cloud: Cloud) -> Option<&'static str> {
match cloud {
Cloud::Aws => Some(aws::CLI),
Cloud::Azure => Some(azure::CLI),
Cloud::Gcp => Some(gcp::CLI),
Cloud::Oci => Some(oci::CLI),
_ => None,
}
}
async fn run(cx: &Context, limit: Duration, spec: &ProcessSpec, read: fn(&str) -> Refusal) -> Result<String, Failure> {
failure::answer(cx, limit, spec, read).await
}
async fn ask(cx: &Context, program: &str, args: &[&str], read: fn(&str) -> Refusal) -> Result<String, Failure> {
run(cx, CLI_TIMEOUT, &ProcessSpec::new(program, args.iter().copied()), read).await
}
fn unreadable(program: &str, why: impl std::fmt::Display) -> Failure {
Failure::Unreadable {
program: program.to_owned(),
why: why.to_string(),
}
}
fn json_list(program: &str, out: &str) -> Result<Vec<serde_json::Value>, Failure> {
serde_json::from_str(out).map_err(|e| unreadable(program, format!("its answer isn't a JSON list ({e})")))
}
fn line(out: &str) -> String {
out.trim().to_owned()
}
fn says(said: &str, words: &[&str]) -> bool {
let lower = said.to_ascii_lowercase();
words.iter().any(|w| lower.contains(&w.to_ascii_lowercase()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SignIn {
Aws {
profile: Option<String>,
},
Azure,
Gcp,
}
impl SignIn {
#[must_use]
pub fn command(&self) -> ProcessSpec {
match self {
SignIn::Aws { profile } => {
let mut args = vec!["login".to_owned()];
if let Some(p) = profile {
args.extend(["--profile".to_owned(), p.clone()]);
}
ProcessSpec::new(aws::CLI, args)
}
SignIn::Azure => ProcessSpec::new(azure::CLI, ["login"]),
SignIn::Gcp => ProcessSpec::new(gcp::CLI, ["auth", "login", "--update-adc"]),
}
}
}
pub async fn sign_in(cx: &Context, which: &SignIn, on_line: &mut (dyn FnMut(&str) + Send)) -> Result<(), Failure> {
let spec = which.command();
on_line(&format!("$ {}", spec.line()));
let mut last = String::new();
let mut each = |_: isothrum_runner::Stream, l: &str| {
if !l.trim().is_empty() {
l.trim().clone_into(&mut last);
}
on_line(l);
};
let program = spec.program.clone();
match cx.runner.run(&spec, &mut each).await {
Ok(exit) if exit.success() => Ok(()),
Ok(exit) => Err(Failure::Refused {
refusal: Refusal::Other,
said: if last.is_empty() { exit.to_string() } else { last },
program,
}),
Err(isothrum_runner::ProcessError::Missing { .. }) => Err(Failure::Missing { program }),
Err(other) => Err(Failure::NotStarted {
program,
reason: other.to_string(),
}),
}
}
#[cfg(test)]
mod tests;