Skip to main content

ward/config/
auth.rs

1use anyhow::{Context, Result};
2
3/// Resolve a GitHub token for API authentication.
4///
5/// Priority:
6/// 1. `GH_TOKEN` environment variable
7/// 2. `GITHUB_TOKEN` environment variable
8/// 3. `gh auth token` command output
9pub fn resolve_token() -> Result<String> {
10    if let Ok(token) = std::env::var("GH_TOKEN") {
11        tracing::debug!("Using token from GH_TOKEN");
12        return Ok(token);
13    }
14
15    if let Ok(token) = std::env::var("GITHUB_TOKEN") {
16        tracing::debug!("Using token from GITHUB_TOKEN");
17        return Ok(token);
18    }
19
20    let output = std::process::Command::new("gh")
21        .args(["auth", "token"])
22        .output()
23        .context("Failed to run 'gh auth token' - is the GitHub CLI installed?")?;
24
25    if !output.status.success() {
26        anyhow::bail!(
27            "gh auth token failed: {}",
28            String::from_utf8_lossy(&output.stderr)
29        );
30    }
31
32    let token = String::from_utf8(output.stdout)
33        .context("Invalid UTF-8 from gh auth token")?
34        .trim()
35        .to_owned();
36
37    if token.is_empty() {
38        anyhow::bail!("gh auth token returned empty - run 'gh auth login' first");
39    }
40
41    tracing::debug!("Using token from gh auth token");
42    Ok(token)
43}