gitswitch 0.1.0

Switch between GitHub accounts (git identity + gh auth) on the fly
//! Thin wrappers around `git config --global`.

use std::process::Command;

use anyhow::{Context, Result, bail};

/// Set the global commit identity.
pub fn set_identity(name: &str, email: &str) -> Result<()> {
    set_global("user.name", name)?;
    set_global("user.email", email)?;
    Ok(())
}

/// Read the current global identity, if both are set.
pub fn get_identity() -> (Option<String>, Option<String>) {
    (get_global("user.name"), get_global("user.email"))
}

fn set_global(key: &str, value: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["config", "--global", key, value])
        .output()
        .context("failed to run `git` (is git installed?)")?;
    if !output.status.success() {
        bail!(
            "git config --global {key} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

fn get_global(key: &str) -> Option<String> {
    let output = Command::new("git")
        .args(["config", "--global", "--get", key])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if value.is_empty() { None } else { Some(value) }
}