use std::{
collections::BTreeMap,
ffi::{OsStr, OsString},
path::{Component, Path, PathBuf},
};
use rho_protocol::{
methods::{
ForgeStatusParams, GhAccount, GhAuth, GhFoundBy, GhState, GhStatus, GhTokenSource,
HostPath, FORGE_STATUS,
},
Caller, ClientEnvironment, RpcError,
};
use serde::Deserialize;
use super::{
blocking, failed, gh_command, host_path, log_call, supervised_output, var, within_deadline,
Machine, Origin, LOGIN_SHELL_DEADLINE,
};
use crate::{
app::pull_requests::{login_shell_gh, GhCli},
executable::{find_on, is_executable_file},
};
pub(super) const TOO_OLD: &str = "This gh can't list its accounts as JSON (gh auth status --json). Update it to a newer release.";
pub(super) async fn status(
machine: &Machine,
caller: Caller,
params: ForgeStatusParams,
) -> Result<GhStatus, RpcError> {
let setting = params.gh.filter(|gh| !gh.is_empty());
tracing::info_span!("forge_status", gh = setting.as_deref())
.in_scope(|| log_call(&caller, FORGE_STATUS, []));
within_deadline(async {
let (environment, origin) = machine.login_environment_and_origin().await;
let (gh, found_by) = match setting {
Some(setting) => (set_program(&setting, &environment), GhFoundBy::Setting),
None => match find(&environment, origin).await? {
Some(found) => found,
None => return Ok(GhStatus::Missing),
},
};
let path = host_path(&gh)?;
let state = state_of(gh, &environment).await?;
Ok(GhStatus::Found {
found_by,
path,
state,
})
})
.await
}
async fn find(
environment: &ClientEnvironment,
origin: Origin,
) -> Result<Option<(PathBuf, GhFoundBy)>, RpcError> {
let cli = GhCli::new(|name| var(environment, name).map(OsString::from));
if let Some(gh) = cli.on_path() {
return Ok(Some((gh, GhFoundBy::Path)));
}
let shell = var(environment, "SHELL").filter(|shell| !shell.is_empty());
if let (Origin::Fallback, Some(shell)) = (origin, shell) {
let asked = login_shell_gh(OsStr::new(shell), Some(environment));
match tokio::time::timeout(LOGIN_SHELL_DEADLINE, asked).await {
Ok(Some(gh)) => return Ok(Some((gh, GhFoundBy::LoginShell))),
Ok(None) => {}
Err(_) => {
return Err(failed(format!(
"The login shell, {shell}, didn't say where gh is within {} s (LOGIN_SHELL_DEADLINE).",
LOGIN_SHELL_DEADLINE.as_secs()
)))
}
}
}
Ok(cli.among_mise().map(|gh| (gh, GhFoundBy::Mise)))
}
fn set_program(setting: &str, environment: &ClientEnvironment) -> PathBuf {
if let Some(gh) = find_on(setting, var(environment, "PATH").map(OsStr::new)) {
return gh;
}
let path = Path::new(setting);
let mut parts = path.components();
let rest = match parts.next() {
Some(Component::Normal(first)) if first == "~" => parts.as_path(),
_ => path,
};
let home = crate::paths::home_dir_from_env(|name| var(environment, name).map(OsString::from));
match home {
Some(home) if rest.is_relative() => home.join(rest),
_ => rest.to_path_buf(),
}
}
async fn state_of(gh: PathBuf, environment: &ClientEnvironment) -> Result<GhState, RpcError> {
let broken = |why: String| Ok(GhState::Broken { why });
let program = gh.clone();
if !blocking(move || is_executable_file(&program)).await? {
return broken("There's no program there.".to_owned());
}
let mut command = gh_command(&gh, environment);
command.arg("--version");
let version = match supervised_output(&mut command).await {
Err(error) => return broken(format!("Couldn't run it: {error}")),
Ok(output) if !output.status.success() => {
let said = [output.stdout, output.stderr].concat();
let said = String::from_utf8_lossy(&said);
return broken(match said.trim() {
"" => format!("It exited with {}.", output.status),
said => said.to_owned(),
});
}
Ok(output) => version_number(&String::from_utf8_lossy(&output.stdout)),
};
let mut command = gh_command(&gh, environment);
command.args(["auth", "status", "--json", "hosts"]);
let listed = match supervised_output(&mut command).await {
Err(error) => return broken(format!("Couldn't run it: {error}")),
Ok(output) => output.stdout,
};
let Some(accounts) = accounts(&listed) else {
return broken(TOO_OLD.to_owned());
};
Ok(GhState::Ready { version, accounts })
}
fn version_number(version: &str) -> String {
let first = version.lines().next().unwrap_or_default();
first
.strip_prefix("gh version ")
.and_then(|rest| rest.split_whitespace().next())
.unwrap_or(first)
.to_owned()
}
#[derive(Deserialize)]
struct AuthStatus {
hosts: BTreeMap<String, Vec<AuthAccount>>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AuthAccount {
state: String,
#[serde(default)]
error: Option<String>,
#[serde(default)]
active: bool,
host: String,
#[serde(default)]
login: String,
#[serde(default)]
token_source: Option<String>,
#[serde(default)]
scopes: Option<String>,
#[serde(default)]
git_protocol: Option<String>,
}
fn accounts(listed: &[u8]) -> Option<Vec<GhAccount>> {
let status: AuthStatus = serde_json::from_slice(listed).ok()?;
Some(status.hosts.into_values().flatten().map(account).collect())
}
fn account(listed: AuthAccount) -> GhAccount {
let auth = if listed.state == "success" {
GhAuth::SignedIn
} else {
let why = listed.error.unwrap_or(listed.state);
if why.contains("401") || why.contains("Bad credentials") {
GhAuth::Refused {
why: "GitHub refused its token.".to_owned(),
}
} else {
let line = why.lines().next().unwrap_or_default().trim();
GhAuth::Unreachable {
why: line.to_owned(),
}
}
};
GhAccount::new(listed.host, listed.login, listed.active, auth).with_details(
listed.git_protocol,
listed.token_source.as_deref().and_then(token_source),
listed.scopes.filter(|scopes| !scopes.is_empty()),
)
}
fn token_source(source: &str) -> Option<GhTokenSource> {
let variable = source
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
match source {
"" => None,
"keyring" => Some(GhTokenSource::Keyring),
_ if variable => Some(GhTokenSource::Variable {
name: source.to_owned(),
}),
_ => Some(GhTokenSource::File {
path: HostPath::new(source),
}),
}
}