use std::{
ffi::{OsStr, OsString},
future::Future,
io,
path::{Path, PathBuf},
pin::Pin,
process::{ExitStatus, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
Mutex, PoisonError,
},
time::Duration,
};
use rho_protocol::{methods::FORGE_DEADLINE_SECS, ClientEnvironment, GhFoundBy};
use tokio::process::Command;
use super::{
gh_query,
model::{Batch, FetchPlan},
};
use crate::{
executable::{find_on, is_executable_file},
process_tree::supervised_output,
};
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 = gh_said(why).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) fn gh_said(why: &str) -> &str {
let line = why.lines().map(str::trim).find(|line| !line.is_empty());
let line = line.unwrap_or_default();
line.strip_prefix("gh: ").unwrap_or(line)
}
pub(crate) fn gh_failure(stderr: &[u8], status: ExitStatus) -> String {
let said = String::from_utf8_lossy(stderr);
match gh_said(&said) {
"" => match status.code() {
Some(code) => format!("gh exited with status {code} and said nothing."),
None => "gh was stopped by a signal and said nothing.".to_owned(),
},
said => said.to_owned(),
}
}
pub(crate) const DEADLINE: Duration = Duration::from_secs(FORGE_DEADLINE_SECS);
const LOGIN_SHELL_DEADLINE: Duration = Duration::from_secs(30);
const QUIET: [(&str, &str); 4] = [
("GH_PROMPT_DISABLED", "1"),
("GH_NO_UPDATE_NOTIFIER", "1"),
("GH_SPINNER_DISABLED", "1"),
("NO_COLOR", "1"),
];
pub(crate) fn quiet_gh(command: &mut Command) -> &mut Command {
command.envs(QUIET).stdin(Stdio::null()).kill_on_drop(true)
}
pub(crate) struct GhCli {
path: Option<OsString>,
shell: Option<OsString>,
mise_gh: Option<PathBuf>,
shell_hung: AtomicBool,
found: Mutex<Option<PathBuf>>,
}
impl GhCli {
pub(crate) fn for_daemon() -> Self {
let cli = Self::new(|name| std::env::var_os(name));
#[cfg(unix)]
let cli = if cli.shell.is_some() {
cli
} else {
match crate::daemon::login_account() {
Ok(account) => cli.or_login_shell(account.shell.into()),
Err(error) => {
tracing::warn!(
"pull request reads can't ask the login shell for gh: {error:#}"
);
cli
}
}
};
cli
}
#[cfg(unix)]
fn or_login_shell(mut self, shell: OsString) -> Self {
self.shell.get_or_insert(shell);
self
}
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)
}),
shell_hung: AtomicBool::new(false),
found: Mutex::new(None),
}
}
pub(crate) async fn find(&self) -> Option<(PathBuf, GhFoundBy)> {
if let Some(gh) = self.on_path() {
return Some((gh, GhFoundBy::Path));
}
let shell = self.shell.as_ref();
if let Some(shell) = shell.filter(|_| !self.shell_hung.load(Ordering::Relaxed)) {
match tokio::time::timeout(LOGIN_SHELL_DEADLINE, login_shell_gh(shell, None)).await {
Ok(Some(gh)) => return Some((gh, GhFoundBy::LoginShell)),
Ok(None) => {}
Err(_) => {
self.shell_hung.store(true, Ordering::Relaxed);
tracing::warn!(
shell = %Path::new(shell).display(),
"the login shell didn't say where gh is within {} s (LOGIN_SHELL_DEADLINE), so pull request reads stop asking it until the daemon restarts",
LOGIN_SHELL_DEADLINE.as_secs()
);
}
}
}
self.among_mise().map(|gh| (gh, GhFoundBy::Mise))
}
pub(crate) fn on_path(&self) -> Option<PathBuf> {
find_on("gh", self.path.as_deref())
}
pub(crate) fn among_mise(&self) -> Option<PathBuf> {
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);
quiet_gh(&mut command)
.args(["api", "graphql", "--hostname", host, "-f"])
.arg(format!("query={query}"));
let output = match supervised_output(&mut command).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(gh_failure(&output.stderr, output.status)));
}
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"))
}
pub(crate) async fn login_shell_gh(
shell: &OsStr,
environment: Option<&ClientEnvironment>,
) -> Option<PathBuf> {
if cfg!(windows) {
return None;
}
let mut command = Command::new(shell);
if let Some(environment) = environment {
command.env_clear().envs(environment.iter());
}
command
.args(["-l", "-c", "command -v gh"])
.stdin(Stdio::null())
.kill_on_drop(true);
let output = supervised_output(&mut command).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;