pets_tools 0.2.0

MusKitty multi-repo source management CLI — one command to clone, build, test, push, and publish 9 independent crate repositories
//! Token detection — checks environment on startup.

/// Token status for a single credential.
#[derive(Clone)]
pub struct TokenStatus {
    pub name: &'static str,
    pub label: &'static str,
    pub present: bool,
}

/// Run at startup before any command. Checks if required tokens are loaded
/// and prints a summary. Returns false if critical tokens are missing for
/// operations that require auth.
pub fn check_on_startup(action_needs_auth: bool) {
    let tokens = [
        TokenStatus {
            name: "CRATES_GIT_TOKEN",
            label: "crate repos (muskitty-dev)",
            present: false,
        },
        TokenStatus {
            name: "MAIN_GIT_TOKEN",
            label: "main repo (Ink-dark)",
            present: false,
        },
        TokenStatus {
            name: "CARGO_REGISTRY_TOKEN",
            label: "crates.io publish",
            present: false,
        },
    ];
    eprint!(
        "{}",
        describe_tokens(
            &tokens,
            |name| std::env::var(name).is_ok(),
            action_needs_auth
        )
    );
}

/// Render the token status summary as a string. Pure function — the caller
/// decides how to detect each token, which keeps this testable without mutating
/// the environment.
pub fn describe_tokens(
    tokens: &[TokenStatus],
    env_has: impl Fn(&str) -> bool,
    action_needs_auth: bool,
) -> String {
    let mut tokens = tokens.to_vec();
    for t in &mut tokens {
        t.present = env_has(t.name);
    }

    let all_ok = tokens.iter().all(|t| t.present);
    let any_missing = tokens.iter().any(|t| !t.present);
    let mut out = String::new();

    if all_ok {
        // All good, just a quiet note
        out.push_str("\x1b[36m[pets] tokens: ✓ all 3 loaded\x1b[0m\n");
    } else if any_missing {
        out.push_str("\x1b[33m[pets] token status:\x1b[0m\n");
        for t in &tokens {
            if t.present {
                out.push_str(&format!("  \x1b[32m✓ {}\x1b[0m — {}\n", t.name, t.label));
            } else {
                out.push_str(&format!(
                    "  \x1b[31m✗ {}\x1b[0m — {} (missing)\n",
                    t.name, t.label
                ));
            }
        }

        if action_needs_auth {
            out.push('\n');
            out.push_str(
                "\x1b[33m  Run '. .\\env.ps1' to load tokens, or set env vars manually.\x1b[0m\n",
            );
        }
    }
    out
}

/// Get the token value for a given token_key from repos.toml.
/// "main" → MAIN_GIT_TOKEN, "crates" → CRATES_GIT_TOKEN
#[allow(dead_code)]
pub fn get_token(token_key: &str) -> Option<String> {
    let env_var = match token_key {
        "main" => "MAIN_GIT_TOKEN",
        _ => "CRATES_GIT_TOKEN",
    };
    std::env::var(env_var).ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tokens() -> Vec<TokenStatus> {
        vec![
            TokenStatus {
                name: "CRATES_GIT_TOKEN",
                label: "crate repos",
                present: false,
            },
            TokenStatus {
                name: "MAIN_GIT_TOKEN",
                label: "main repo",
                present: false,
            },
            TokenStatus {
                name: "CARGO_REGISTRY_TOKEN",
                label: "publish",
                present: false,
            },
        ]
    }

    #[test]
    fn all_present_prints_quiet_success() {
        let out = describe_tokens(&tokens(), |_| true, false);
        assert!(out.contains("[pets] tokens: ✓ all 3 loaded"));
        assert!(!out.contains("missing"));
    }

    #[test]
    fn missing_lists_each_token_state() {
        let out = describe_tokens(&tokens(), |name| name == "CRATES_GIT_TOKEN", false);
        assert!(out.contains("[pets] token status:"));
        assert!(out.contains("✓ CRATES_GIT_TOKEN"));
        assert!(out.contains("✗ MAIN_GIT_TOKEN"));
        assert!(out.contains("(missing)"));
        // No auth advice when the action does not need tokens.
        assert!(!out.contains("env.ps1"));
    }

    #[test]
    fn missing_with_auth_action_advises_env_ps1() {
        let out = describe_tokens(&tokens(), |_| false, true);
        assert!(out.contains("env.ps1"));
    }
}