use crate::model::Config;
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::sync::Mutex;
use std::time::Duration;
use std::process::{Command, ExitStatus, Stdio};
const USERNAME_KEY: &str = "credential.https://github.com.username";
#[derive(Clone, Debug, Deserialize)]
pub struct Profile {
pub login: String,
pub id: u64,
pub name: Option<String>,
pub email: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Account {
pub label: String,
pub name: String,
pub email: String,
pub github_username: String,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Original {
pub name: Option<String>,
pub email: Option<String>,
pub username: Option<String>,
}
pub fn problem(candidate: &Account, others: &[Account]) -> Option<String> {
if candidate.label.trim().is_empty() {
return Some("label is required".into());
}
if others.iter().any(|a| a.label == candidate.label) {
return Some(format!("label {} is already used", candidate.label));
}
let email = &candidate.email;
if email.trim().is_empty() {
return Some("email is required".into());
}
if email.matches('@').count() != 1 || email.chars().any(char::is_whitespace) {
return Some("email must contain one '@' and no spaces".into());
}
if let Some(other) = others.iter().find(|a| a.email.eq_ignore_ascii_case(email)) {
return Some(format!("email already used by {}", other.label));
}
let username = &candidate.github_username;
if username.is_empty() {
return Some("GitHub username is required".into());
}
if username.len() > 39
|| !username
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-')
{
return Some(
"GitHub username may only use letters, digits or '-' (max 39 characters)".into(),
);
}
if let Some(other) = others
.iter()
.find(|a| a.github_username.eq_ignore_ascii_case(username))
{
return Some(format!("GitHub username already used by {}", other.label));
}
None
}
pub fn activate(config: &mut Config, label: &str) -> Result<()> {
let account = config
.accounts
.iter()
.find(|a| a.label == label)
.cloned()
.ok_or_else(|| anyhow!("no account named {label}"))?;
let fresh = config.original.is_none();
let before = read_global();
if fresh {
config.original = Some(before.clone());
}
let name = if account.name.trim().is_empty() {
account.github_username.as_str()
} else {
account.name.as_str()
};
let applied = git_set("user.name", name)
.and_then(|_| git_set("user.email", &account.email))
.and_then(|_| git_set(USERNAME_KEY, &account.github_username));
if let Err(error) = applied {
restore("user.name", before.name.as_deref()).ok();
restore("user.email", before.email.as_deref()).ok();
restore(USERNAME_KEY, before.username.as_deref()).ok();
if fresh {
config.original = None;
}
return Err(error);
}
config.active_account = Some(label.to_string());
crate::config::save(config)
}
pub fn deactivate(config: &mut Config) -> Result<()> {
if let Some(original) = config.original.clone() {
restore("user.name", original.name.as_deref())?;
restore("user.email", original.email.as_deref())?;
restore(USERNAME_KEY, original.username.as_deref())?;
config.original = None;
}
config.active_account = None;
Ok(())
}
pub fn stored_logins() -> Vec<String> {
if let Some(cached) = LOGINS.lock().ok().and_then(|g| g.clone()) {
return cached;
}
let fresh = load_logins();
if let Ok(mut guard) = LOGINS.lock() {
*guard = Some(fresh.clone());
}
fresh
}
static LOGINS: Mutex<Option<Vec<String>>> = Mutex::new(None);
pub fn invalidate_logins() {
if let Ok(mut guard) = LOGINS.lock() {
*guard = None;
}
}
fn load_logins() -> Vec<String> {
Command::new("git")
.args(["credential-manager", "github", "list"])
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| {
String::from_utf8_lossy(&output.stdout)
.lines()
.map(|line| line.trim().to_string())
.filter(|line| !line.is_empty())
.collect()
})
.unwrap_or_default()
}
pub fn login(username: &str) -> Result<()> {
let finished = browser_login(&["--username", username])?.success();
invalidate_logins();
if !finished {
bail!("GitHub sign-in for {username} did not finish");
}
Ok(())
}
pub fn sign_in_new(label: &str, username: &str) -> Result<Account> {
login(username)?;
Ok(account_from(label, &fetch_profile(username)?))
}
pub fn verify_login(username: &str) -> Result<()> {
fetch_profile(username).map(|_| ())
}
pub fn refresh(account: &mut Account) -> Result<()> {
let fresh = account_from(&account.label, &fetch_profile(&account.github_username)?);
account.name = fresh.name;
account.email = fresh.email;
Ok(())
}
pub fn fetch_profile(username: &str) -> Result<Profile> {
let token = token_for(username)?;
ureq::AgentBuilder::new()
.timeout(Duration::from_secs(15))
.build()
.get("https://api.github.com/user")
.set("Authorization", &format!("Bearer {token}"))
.set("User-Agent", "gct")
.set("Accept", "application/vnd.github+json")
.set("X-GitHub-Api-Version", "2022-11-28")
.call()
.context("GitHub profile request failed")?
.into_string()
.context("GitHub profile could not be read")
.and_then(|body| {
let profile: Profile =
serde_json::from_str(&body).context("GitHub returned an unexpected profile")?;
if !profile.login.eq_ignore_ascii_case(username) {
bail!(
"GitHub returned {} but {username} was requested; sign in again with the right account",
profile.login
);
}
Ok(profile)
})
}
fn account_from(label: &str, profile: &Profile) -> Account {
let name = profile.name.clone().filter(|name| !name.trim().is_empty());
let email = profile
.email
.clone()
.filter(|email| !email.trim().is_empty());
Account {
label: label.into(),
name: name.unwrap_or_else(|| profile.login.clone()),
email: email.unwrap_or_else(|| {
format!("{}+{}@users.noreply.github.com", profile.id, profile.login)
}),
github_username: profile.login.clone(),
}
}
fn browser_login(extra: &[&str]) -> Result<ExitStatus> {
Command::new("git")
.args(["credential-manager", "github", "login"])
.args(extra)
.arg("--browser")
.status()
.context("could not start Git Credential Manager")
}
fn token_for(username: &str) -> Result<String> {
let mut child = Command::new("git")
.args(["credential", "fill"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("could not start git credential")?;
let request = format!("protocol=https\nhost=github.com\nusername={username}\n\n");
child
.stdin
.take()
.context("could not reach git credential")?
.write_all(request.as_bytes())
.context("could not reach git credential")?;
let output = child
.wait_with_output()
.context("could not read git credential")?;
let missing = || anyhow!("no saved GitHub login for {username}");
if !output.status.success() {
return Err(missing());
}
String::from_utf8_lossy(&output.stdout)
.lines()
.find_map(|line| line.strip_prefix("password="))
.map(|token| token.trim().to_string())
.filter(|token| !token.is_empty())
.ok_or_else(missing)
}
fn read_global() -> Original {
let output = Command::new("git")
.args([
"config",
"--global",
"--get-regexp",
r"^(user\.name|user\.email|credential\.https://github\.com\.username)$",
])
.output();
match output {
Ok(out) if out.status.success() => parse_global(&String::from_utf8_lossy(&out.stdout)),
_ => Original::default(),
}
}
fn parse_global(text: &str) -> Original {
let mut found = Original::default();
for line in text.lines() {
let (key, value) = line.split_once(' ').unwrap_or((line, ""));
let value = value.trim();
let value = (!value.is_empty()).then(|| value.to_string());
match key {
"user.name" => found.name = value,
"user.email" => found.email = value,
USERNAME_KEY => found.username = value,
_ => {}
}
}
found
}
fn git_config(args: &[&str], action: &str, key: &str) -> Result<std::process::Output> {
Command::new("git")
.args(["config", "--global"])
.args(args)
.output()
.with_context(|| format!("could not {action} {key}"))
}
fn config_failed(action: &str, key: &str, output: &std::process::Output) -> anyhow::Error {
let detail = String::from_utf8_lossy(&output.stderr);
let detail = detail.trim();
if detail.is_empty() {
anyhow!("could not {action} {key}")
} else {
anyhow!("could not {action} {key}: {detail}")
}
}
fn git_set(key: &str, value: &str) -> Result<()> {
let output = git_config(&[key, value], "set", key)?;
if !output.status.success() {
return Err(config_failed("set", key, &output));
}
Ok(())
}
fn restore(key: &str, value: Option<&str>) -> Result<()> {
match value {
Some(value) => {
let output = git_config(&["--replace-all", key, value], "set", key)?;
if !output.status.success() {
return Err(config_failed("set", key, &output));
}
Ok(())
}
None => {
let output = git_config(&["--unset", key], "unset", key)?;
if output.status.success() || output.status.code() == Some(5) {
Ok(())
} else {
Err(config_failed("unset", key, &output))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_global_lines_last_wins() {
let text = "user.name Ann Lee\nuser.email a@b.c\nuser.email d@e.f\ncredential.https://github.com.username ann\n";
let o = parse_global(text);
assert_eq!(o.name.as_deref(), Some("Ann Lee"));
assert_eq!(o.email.as_deref(), Some("d@e.f"));
assert_eq!(o.username.as_deref(), Some("ann"));
}
#[test]
fn empty_value_is_none() {
let o = parse_global("user.name\nuser.email \n");
assert!(o.name.is_none() && o.email.is_none() && o.username.is_none());
}
}