use std::{
ffi::{OsStr, OsString},
future::Future,
io,
path::PathBuf,
pin::Pin,
process::Stdio,
sync::{Mutex, PoisonError},
time::Duration,
};
use tokio::process::Command;
use super::{
gh_query,
model::{Batch, FetchPlan},
};
use crate::executable::{find_on, is_executable_file};
pub(crate) trait Forge: Send + Sync {
fn read<'a>(
&'a self,
host: &'a str,
plan: &'a FetchPlan,
) -> Pin<Box<dyn Future<Output = Result<Batch, ReadError>> + Send + 'a>>;
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum ReadError {
#[error("{0}")]
NotInstalled(String),
#[error("{0}")]
SignedOut(String),
#[error("{0}")]
Failed(String),
}
#[derive(Debug)]
pub(crate) enum Ended<'a> {
Unstarted(&'a io::Error),
Said(&'a str),
}
pub(crate) fn classify(ended: Ended<'_>) -> ReadError {
match ended {
Ended::Unstarted(error) if error.kind() == io::ErrorKind::NotFound => {
ReadError::NotInstalled(error.to_string())
}
Ended::Unstarted(error) => ReadError::Failed(error.to_string()),
Ended::Said(why) => {
let line = why.lines().map(str::trim).find(|line| !line.is_empty());
let line = line.unwrap_or_default();
let line = line.strip_prefix("gh: ").unwrap_or(line).to_owned();
let signed_out = why.contains("401")
|| why.contains("Bad credentials")
|| why.contains("gh auth login");
if signed_out {
ReadError::SignedOut(line)
} else {
ReadError::Failed(line)
}
}
}
}
pub(crate) const DEADLINE: Duration = Duration::from_secs(60);
const QUIET: [(&str, &str); 4] = [
("GH_PROMPT_DISABLED", "1"),
("GH_NO_UPDATE_NOTIFIER", "1"),
("GH_SPINNER_DISABLED", "1"),
("NO_COLOR", "1"),
];
pub(crate) struct GhCli {
path: Option<OsString>,
shell: Option<OsString>,
mise_gh: Option<PathBuf>,
found: Mutex<Option<PathBuf>>,
}
impl Default for GhCli {
fn default() -> Self {
Self::new(|name| std::env::var_os(name))
}
}
impl GhCli {
pub(crate) fn new(var: impl Fn(&str) -> Option<OsString>) -> Self {
let var = |name: &str| var(name).filter(|value| !value.is_empty());
Self {
path: var("PATH"),
shell: var("SHELL"),
mise_gh: mise_shims_dir(&var).map(|shims| {
shims
.join("gh")
.with_extension(std::env::consts::EXE_EXTENSION)
}),
found: Mutex::new(None),
}
}
pub(crate) async fn find(&self) -> Option<PathBuf> {
if let Some(gh) = find_on("gh", self.path.as_deref()) {
return Some(gh);
}
if let Some(shell) = &self.shell {
if let Some(gh) = login_shell_gh(shell).await {
return Some(gh);
}
}
self.mise_gh.clone().filter(|gh| is_executable_file(gh))
}
async fn program(&self) -> Option<PathBuf> {
let remembered = self
.found
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
if remembered.is_some() {
return remembered;
}
let found = self.find().await?;
*self.found.lock().unwrap_or_else(PoisonError::into_inner) = Some(found.clone());
Some(found)
}
async fn read_now(&self, host: &str, plan: &FetchPlan) -> Result<Batch, ReadError> {
let Some(gh) = self.program().await else {
return Err(ReadError::NotInstalled(
"gh is not on the daemon's PATH, nor found by its login shell or among mise's shims"
.to_owned(),
));
};
let query = gh_query::query(plan);
let mut command = Command::new(&gh);
command
.args(["api", "graphql", "--hostname", host, "-f"])
.arg(format!("query={query}"))
.envs(QUIET)
.stdin(Stdio::null())
.kill_on_drop(true);
let output = match command.output().await {
Ok(output) => output,
Err(error) => {
if error.kind() == io::ErrorKind::NotFound {
*self.found.lock().unwrap_or_else(PoisonError::into_inner) = None;
}
return Err(classify(Ended::Unstarted(&error)));
}
};
let stderr = String::from_utf8_lossy(&output.stderr);
if output.stdout.trim_ascii().is_empty() && stderr.trim().is_empty() {
return Err(ReadError::Failed(match output.status.code() {
Some(code) => format!("gh exited with status {code} and printed nothing"),
None => "gh was stopped by a signal and printed nothing".to_owned(),
}));
}
gh_query::parse(plan, &output.stdout, &stderr)
}
}
impl Forge for GhCli {
fn read<'a>(
&'a self,
host: &'a str,
plan: &'a FetchPlan,
) -> Pin<Box<dyn Future<Output = Result<Batch, ReadError>> + Send + 'a>> {
Box::pin(async move {
match tokio::time::timeout(DEADLINE, self.read_now(host, plan)).await {
Ok(read) => read,
Err(_) => {
let seconds = DEADLINE.as_secs();
Err(ReadError::Failed(format!(
"gh didn't answer within {seconds} s"
)))
}
}
})
}
}
fn mise_shims_dir(var: &dyn Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
let shims = if let Some(shims) = var("MISE_SHIMS_DIR") {
PathBuf::from(shims)
} else if let Some(data) = var("MISE_DATA_DIR") {
PathBuf::from(data).join("shims")
} else {
default_mise_data(var)?.join("shims")
};
shims.is_absolute().then_some(shims)
}
fn default_mise_data(var: &dyn Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
let data_home = match var("XDG_DATA_HOME") {
Some(dir) => PathBuf::from(dir),
None if cfg!(windows) => match var("LOCALAPPDATA") {
Some(dir) => PathBuf::from(dir),
None => crate::paths::home_dir_from_env(var)?
.join("AppData")
.join("Local"),
},
None => crate::paths::home_dir_from_env(var)?
.join(".local")
.join("share"),
};
Some(data_home.join("mise"))
}
async fn login_shell_gh(shell: &OsStr) -> Option<PathBuf> {
if cfg!(windows) {
return None;
}
let output = Command::new(shell)
.args(["-l", "-c", "command -v gh"])
.stdin(Stdio::null())
.kill_on_drop(true)
.output()
.await
.ok()?;
let line = output
.stdout
.split(|&byte| byte == b'\n')
.rfind(|line| !line.trim_ascii().is_empty())?;
let gh = PathBuf::from(std::str::from_utf8(line).ok()?.trim());
(gh.is_absolute() && is_executable_file(&gh)).then_some(gh)
}
#[cfg(test)]
#[path = "gh_tests.rs"]
mod tests;