git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
use crate::model::Config;
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::process::{Command, ExitStatus};
use std::sync::Mutex;
use std::time::Duration;

const USERNAME_KEY: &str = "credential.https://github.com.username";

/// For `git credential fill`: never ask on the terminal or open a Credential Manager window.
const CREDENTIAL_ENV: [(&str, &str); 2] =
    [("GIT_TERMINAL_PROMPT", "0"), ("GCM_INTERACTIVE", "never")];
const CREDENTIAL_TIMEOUT: Duration = Duration::from_secs(20);

#[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,
}

/// Global git values as they were before the first account was activated.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Original {
    pub name: Option<String>,
    pub email: Option<String>,
    pub username: Option<String>,
}

/// First problem with a candidate account, or None when it can be saved.
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
}

/// Points the global git identity at the named account, remembering the old values first.
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();
    // Values in place right now: a failed switch puts exactly these back.
    let before = read_global();
    if fresh {
        config.original = Some(before.clone());
    }
    // A blank display name would leave git with no usable name, so fall back to the login.
    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());
    // Save now, so a crash or closed window after the switch still leaves the snapshot on disk.
    crate::config::save(config)
}

/// Restores the global git values saved by `activate`, if any.
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(())
}

/// GitHub usernames that Git Credential Manager has a saved login for. Empty if it cannot run.
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);

/// Drops the cached `stored_logins` so the next call asks Credential Manager again.
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()
}

/// Opens the browser to sign `username` in to GitHub; Credential Manager stores the login.
/// Call only with the TUI suspended, because the browser flow prints to the terminal.
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(())
}

/// Signs in to GitHub as `username`, then fills the account from GitHub's profile.
/// Call only with the TUI suspended.
pub fn sign_in_new(label: &str, username: &str) -> Result<Account> {
    login(username)?;
    Ok(account_from(label, &fetch_profile(username)?))
}

/// Checks that the login Credential Manager returns for `username` really is that GitHub account.
/// fetch_profile bails when GitHub reports a different login, so a wrong token stops the push.
pub fn verify_login(username: &str) -> Result<()> {
    fetch_profile(username).map(|_| ())
}

/// Re-fetches name and email from GitHub, keeping the label.
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(())
}

/// Reads the signed-in user's profile from the GitHub API. The token lives only for this request.
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")
}

/// The password Credential Manager holds for `username`. Never put this in an error or a log.
/// Never prompts: no terminal prompt, no Credential Manager login window, and a 20 s limit, so a
/// missing login fails fast instead of starting an interactive sign-in on the main thread.
fn token_for(username: &str) -> Result<String> {
    let request = format!("protocol=https\nhost=github.com\nusername={username}\n\n");
    let opts = crate::git::Opts {
        stdin: Some(request.as_bytes()),
        env: &CREDENTIAL_ENV,
        timeout: Some(CREDENTIAL_TIMEOUT),
        ..crate::git::Opts::default()
    };
    let output = crate::git::git_raw(&["credential", "fill"], &opts)
        .context("could not read git credential")?;
    let missing = || anyhow!("no saved GitHub login for {username}");
    if !output.ok() {
        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 {
    // One spawn for all three keys; exit 1 (nothing matched) or failure leaves everything None.
    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(),
    }
}

/// Parses `key value` lines; for repeated keys the last value wins, like `--get`.
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
}

/// Runs `git config --global ...` with output captured so nothing prints onto the TUI.
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) => {
            // --replace-all so keys that hold several values restore cleanly.
            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)?;
            // Exit code 5 means the key was already unset.
            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 missing_token_fails_fast_without_prompting() {
        assert!(CREDENTIAL_ENV.contains(&("GIT_TERMINAL_PROMPT", "0")));
        assert!(CREDENTIAL_ENV.contains(&("GCM_INTERACTIVE", "never")));
        // An isolated config has no credential helper: git would prompt, and must not.
        let repo = crate::testutil::TempRepo::new(0);
        let started = std::time::Instant::now();
        let error = repo.run(|| token_for("nobody-gct-test")).unwrap_err();
        assert!(
            error.to_string().contains("no saved GitHub login"),
            "{error}"
        );
        assert!(started.elapsed() < CREDENTIAL_TIMEOUT);
    }

    #[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());
    }
}