use std::path::Path;
use std::process::{Command, ExitStatus, Stdio};
pub const MISSING: &str = "the GitHub CLI (gh) is not installed; install it from https://cli.github.com, then run gh auth login";
pub const SIGNED_OUT: &str = "the GitHub CLI (gh) is not signed in; run gh auth login";
const AUTH_REQUIRED: i32 = 4;
pub fn spawn_error(e: &std::io::Error, cwd: Option<&Path>) -> String {
if e.kind() == std::io::ErrorKind::NotFound && cwd.is_none_or(Path::is_dir) {
String::from(MISSING)
} else {
format!("could not run gh: {e}")
}
}
pub fn signed_out(status: ExitStatus) -> bool {
status.code() == Some(AUTH_REQUIRED)
}
pub fn unusable(why: &str) -> bool {
why == MISSING || why == SIGNED_OUT
}
const TOKEN_VARS: [&str; 4] = [
"GH_TOKEN",
"GITHUB_TOKEN",
"GH_ENTERPRISE_TOKEN",
"GITHUB_ENTERPRISE_TOKEN",
];
fn succeeds(program: &str, args: &[&str]) -> Result<bool, String> {
let mut cmd = Command::new(program);
cmd.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
crate::review_ops::spawn_retrying_busy(&mut cmd)
.and_then(|mut child| child.wait())
.map(|status| status.success())
.map_err(|e| spawn_error(&e, None))
}
pub fn check_ready(program: &str) -> Result<(), String> {
let env_token = || {
TOKEN_VARS
.iter()
.any(|v| std::env::var_os(v).is_some_and(|t| !t.is_empty()))
};
if succeeds(program, &["auth", "token"])? || env_token() {
return Ok(());
}
if any_host_signed_in(program)? {
Ok(())
} else {
Err(String::from(SIGNED_OUT))
}
}
fn any_host_signed_in(program: &str) -> Result<bool, String> {
let mut cmd = Command::new(program);
cmd.args(["auth", "status"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let out = crate::review_ops::spawn_retrying_busy(&mut cmd)
.and_then(|child| child.wait_with_output())
.map_err(|e| spawn_error(&e, None))?;
let says = |b: &[u8]| String::from_utf8_lossy(b).contains("Logged in to");
Ok(out.status.success() || says(&out.stdout) || says(&out.stderr))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_gh_says_how_to_get_it() {
let dir = tempfile::tempdir().unwrap();
let gh = dir.path().join("gh");
assert_eq!(check_ready(&gh.display().to_string()), Err(MISSING.into()));
let e = std::io::Error::from(std::io::ErrorKind::NotFound);
assert_eq!(spawn_error(&e, Some(dir.path())), MISSING);
assert!(unusable(MISSING) && unusable(SIGNED_OUT));
}
#[test]
fn a_vanished_folder_is_not_a_missing_gh() {
let dir = tempfile::tempdir().unwrap();
let e = std::io::Error::from(std::io::ErrorKind::NotFound);
let why = spawn_error(&e, Some(&dir.path().join("gone")));
assert!(why.starts_with("could not run gh:"), "{why}");
assert!(!unusable(&why));
}
#[cfg(unix)]
#[test]
fn a_gh_signed_in_elsewhere_than_its_default_host_is_ready() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let gh = dir.path().join("gh");
let log = dir.path().join("log");
let script = format!(
"#!/bin/sh\necho \"$*\" >> '{}'\n[ \"$2\" = token ] && exit 1\nexit 0\n",
log.display()
);
std::fs::write(&gh, script).unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(check_ready(&gh.display().to_string()), Ok(()));
let asked = std::fs::read_to_string(&log).unwrap();
assert!(asked.starts_with("auth token\n"), "offline first: {asked}");
}
#[cfg(unix)]
#[test]
fn a_stale_host_beside_a_signed_in_one_is_ready() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let fake = |name: &str, status: &str| {
let gh = dir.path().join(name);
let script = format!(
"#!/bin/sh\n[ \"$2\" = token ] && exit 1\nprintf '%s\\n' {status}\nexit 1\n"
);
std::fs::write(&gh, script).unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
gh.display().to_string()
};
let mixed = fake(
"mixed",
"'X Failed to log in to github.com account old' 'Logged in to ghe.example.com account me'",
);
assert_eq!(any_host_signed_in(&mixed), Ok(true));
let stale = fake("stale", "'X Failed to log in to github.com account old'");
assert_eq!(any_host_signed_in(&stale), Ok(false));
}
#[test]
fn gh_exit_code_4_means_signed_out() {
let status = |code: &str| {
Command::new("/bin/sh")
.args(["-c", &format!("exit {code}")])
.status()
.unwrap()
};
assert!(signed_out(status("4")));
assert!(!signed_out(status("1")));
}
}