Skip to main content

lean_ctx/core/providers/
github.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! GitHub context provider — issues, pull requests, actions.
4//!
5//! Follows the same pattern as `gitlab.rs` but targets the GitHub REST API v3.
6//! Implements `ContextProvider` for the registry.
7
8use super::cache;
9use super::provider_trait::{ContextProvider, ProviderParams};
10use super::{ProviderItem, ProviderResult};
11
12const DEFAULT_PER_PAGE: usize = 20;
13const CACHE_TTL_SECS: u64 = 120;
14
15// ---------------------------------------------------------------------------
16// Config
17// ---------------------------------------------------------------------------
18
19#[derive(Debug, Clone)]
20pub struct GitHubConfig {
21    pub token: String,
22    pub owner: Option<String>,
23    pub repo: Option<String>,
24    pub api_base: String,
25}
26
27impl GitHubConfig {
28    pub fn from_env() -> Result<Self, String> {
29        let token = std::env::var("GITHUB_TOKEN")
30            .or_else(|_| std::env::var("GH_TOKEN"))
31            .or_else(|_| std::env::var("LEAN_CTX_GITHUB_TOKEN"))
32            .map_err(|_| {
33                "No GitHub token found. Set GITHUB_TOKEN or LEAN_CTX_GITHUB_TOKEN.".to_string()
34            })?;
35
36        let api_base = std::env::var("GITHUB_API_URL")
37            .unwrap_or_else(|_| "https://api.github.com".to_string());
38
39        let (owner, repo) = detect_owner_repo();
40
41        Ok(Self {
42            token,
43            owner,
44            repo,
45            api_base,
46        })
47    }
48
49    pub fn repo_slug(&self) -> Option<String> {
50        match (&self.owner, &self.repo) {
51            (Some(o), Some(r)) => Some(format!("{o}/{r}")),
52            _ => None,
53        }
54    }
55
56    fn api_url(&self, endpoint: &str) -> String {
57        format!("{}{endpoint}", self.api_base)
58    }
59}
60
61fn detect_owner_repo() -> (Option<String>, Option<String>) {
62    if let Ok(full) = std::env::var("GITHUB_REPOSITORY")
63        && let Some((owner, repo)) = full.split_once('/')
64    {
65        return (Some(owner.to_string()), Some(repo.to_string()));
66    }
67    if let (Ok(o), Ok(r)) = (
68        std::env::var("GITHUB_REPOSITORY_OWNER"),
69        std::env::var("GITHUB_REPO"),
70    ) {
71        return (Some(o), Some(r));
72    }
73
74    for remote in &["origin", "github", "upstream"] {
75        let output = match std::process::Command::new("git")
76            .args(["remote", "get-url", remote])
77            .output()
78        {
79            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
80            _ => continue,
81        };
82        let result = parse_github_remote(&output);
83        if result.0.is_some() {
84            return result;
85        }
86    }
87    (None, None)
88}
89
90fn parse_github_remote(url: &str) -> (Option<String>, Option<String>) {
91    // SSH: git@github.com:owner/repo.git
92    if let Some(rest) = url.strip_prefix("git@github.com:") {
93        let clean = rest.trim_end_matches(".git");
94        if let Some((owner, repo)) = clean.split_once('/') {
95            return (Some(owner.to_string()), Some(repo.to_string()));
96        }
97    }
98
99    // HTTPS: https://github.com/owner/repo.git
100    if let Some(rest) = url
101        .strip_prefix("https://github.com/")
102        .or_else(|| url.strip_prefix("http://github.com/"))
103    {
104        let clean = rest.trim_end_matches(".git");
105        if let Some((owner, repo)) = clean.split_once('/') {
106            return (Some(owner.to_string()), Some(repo.to_string()));
107        }
108    }
109
110    (None, None)
111}
112
113// ---------------------------------------------------------------------------
114// API calls
115// ---------------------------------------------------------------------------
116
117fn api_get(config: &GitHubConfig, endpoint: &str) -> Result<String, String> {
118    let url = config.api_url(endpoint);
119    let token = format!("Bearer {}", config.token);
120    super::hardened_http::provider_get_with_headers(
121        "github",
122        &url,
123        &[
124            ("Authorization", &token),
125            ("Accept", "application/vnd.github+json"),
126            ("X-GitHub-Api-Version", "2022-11-28"),
127        ],
128    )
129    .into_body()
130    .map_err(|e| format!("GitHub API error: {e}"))
131}
132
133// ---------------------------------------------------------------------------
134// Resource handlers
135// ---------------------------------------------------------------------------
136
137pub fn list_issues(
138    config: &GitHubConfig,
139    state: Option<&str>,
140    limit: Option<usize>,
141) -> Result<ProviderResult, String> {
142    let slug = config
143        .repo_slug()
144        .ok_or("No GitHub repo configured. Set GITHUB_REPOSITORY or configure git remote.")?;
145
146    let per_page = limit.unwrap_or(DEFAULT_PER_PAGE).min(100);
147    let state_param = state.unwrap_or("open");
148
149    let endpoint = format!(
150        "/repos/{slug}/issues?per_page={per_page}&state={state_param}&sort=updated&direction=desc"
151    );
152
153    let cache_key = cache::request_cache_key(
154        "github",
155        &config.api_url(&endpoint),
156        Some(config.token.as_str()),
157    );
158    if let Some(cached) = cache::get_cached(&cache_key)
159        && let Ok(result) = serde_json::from_str::<ProviderResult>(&cached)
160    {
161        return Ok(result);
162    }
163
164    let body = api_get(config, &endpoint)?;
165    let items: Vec<serde_json::Value> =
166        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {e}"))?;
167
168    let result = ProviderResult {
169        provider: "github".to_string(),
170        resource_type: "issues".to_string(),
171        total_count: None,
172        truncated: items.len() >= per_page,
173        items: items
174            .iter()
175            .filter(|v| v.get("pull_request").is_none_or(serde_json::Value::is_null))
176            .map(parse_issue)
177            .collect(),
178    };
179
180    if let Ok(json) = serde_json::to_string(&result) {
181        cache::set_cached(&cache_key, &json, CACHE_TTL_SECS);
182    }
183    Ok(result)
184}
185
186pub fn list_pull_requests(
187    config: &GitHubConfig,
188    state: Option<&str>,
189    limit: Option<usize>,
190) -> Result<ProviderResult, String> {
191    let slug = config.repo_slug().ok_or("No GitHub repo configured.")?;
192
193    let per_page = limit.unwrap_or(DEFAULT_PER_PAGE).min(100);
194    let state_param = state.unwrap_or("open");
195
196    let endpoint = format!(
197        "/repos/{slug}/pulls?per_page={per_page}&state={state_param}&sort=updated&direction=desc"
198    );
199
200    let cache_key = cache::request_cache_key(
201        "github",
202        &config.api_url(&endpoint),
203        Some(config.token.as_str()),
204    );
205    if let Some(cached) = cache::get_cached(&cache_key)
206        && let Ok(result) = serde_json::from_str::<ProviderResult>(&cached)
207    {
208        return Ok(result);
209    }
210
211    let body = api_get(config, &endpoint)?;
212    let items: Vec<serde_json::Value> =
213        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {e}"))?;
214
215    let result = ProviderResult {
216        provider: "github".to_string(),
217        resource_type: "pull_requests".to_string(),
218        total_count: None,
219        truncated: items.len() >= per_page,
220        items: items.iter().map(parse_pr).collect(),
221    };
222
223    if let Ok(json) = serde_json::to_string(&result) {
224        cache::set_cached(&cache_key, &json, CACHE_TTL_SECS);
225    }
226    Ok(result)
227}
228
229pub fn list_actions(
230    config: &GitHubConfig,
231    status: Option<&str>,
232    limit: Option<usize>,
233) -> Result<ProviderResult, String> {
234    let slug = config.repo_slug().ok_or("No GitHub repo configured.")?;
235
236    let per_page = limit.unwrap_or(DEFAULT_PER_PAGE).min(30);
237    let mut endpoint = format!("/repos/{slug}/actions/runs?per_page={per_page}");
238    if let Some(s) = status {
239        endpoint.push_str(&format!("&status={s}"));
240    }
241
242    let body = api_get(config, &endpoint)?;
243    let json: serde_json::Value =
244        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {e}"))?;
245
246    let runs = json["workflow_runs"]
247        .as_array()
248        .cloned()
249        .unwrap_or_default();
250
251    Ok(ProviderResult {
252        provider: "github".to_string(),
253        resource_type: "actions".to_string(),
254        total_count: json["total_count"].as_u64().map(|n| n as usize),
255        truncated: runs.len() >= per_page,
256        items: runs
257            .iter()
258            .map(|r| ProviderItem {
259                id: r["id"].as_u64().unwrap_or(0).to_string(),
260                title: r["name"].as_str().unwrap_or("").to_string(),
261                state: r["conclusion"]
262                    .as_str()
263                    .or_else(|| r["status"].as_str())
264                    .map(String::from),
265                author: r["actor"]["login"].as_str().map(String::from),
266                created_at: r["created_at"].as_str().map(String::from),
267                updated_at: r["updated_at"].as_str().map(String::from),
268                url: r["html_url"].as_str().map(String::from),
269                labels: Vec::new(),
270                body: None,
271                ..Default::default()
272            })
273            .collect(),
274    })
275}
276
277// ---------------------------------------------------------------------------
278// Parsers
279// ---------------------------------------------------------------------------
280
281fn parse_issue(v: &serde_json::Value) -> ProviderItem {
282    ProviderItem {
283        id: v["number"].as_u64().unwrap_or(0).to_string(),
284        title: v["title"].as_str().unwrap_or("").to_string(),
285        state: v["state"].as_str().map(String::from),
286        author: v["user"]["login"].as_str().map(String::from),
287        created_at: v["created_at"].as_str().map(String::from),
288        updated_at: v["updated_at"].as_str().map(String::from),
289        url: v["html_url"].as_str().map(String::from),
290        labels: v["labels"]
291            .as_array()
292            .map(|arr| {
293                arr.iter()
294                    .filter_map(|l| l["name"].as_str().map(String::from))
295                    .collect()
296            })
297            .unwrap_or_default(),
298        body: v["body"].as_str().map(String::from),
299        ..Default::default()
300    }
301}
302
303fn parse_pr(v: &serde_json::Value) -> ProviderItem {
304    ProviderItem {
305        id: v["number"].as_u64().unwrap_or(0).to_string(),
306        title: v["title"].as_str().unwrap_or("").to_string(),
307        state: v["state"].as_str().map(String::from),
308        author: v["user"]["login"].as_str().map(String::from),
309        created_at: v["created_at"].as_str().map(String::from),
310        updated_at: v["updated_at"].as_str().map(String::from),
311        url: v["html_url"].as_str().map(String::from),
312        labels: v["labels"]
313            .as_array()
314            .map(|arr| {
315                arr.iter()
316                    .filter_map(|l| l["name"].as_str().map(String::from))
317                    .collect()
318            })
319            .unwrap_or_default(),
320        body: v["body"].as_str().map(String::from),
321        ..Default::default()
322    }
323}
324
325// ---------------------------------------------------------------------------
326// ContextProvider trait impl
327// ---------------------------------------------------------------------------
328
329pub struct GitHubProvider {
330    config: Result<GitHubConfig, String>,
331}
332
333impl GitHubProvider {
334    pub fn new() -> Self {
335        Self {
336            config: GitHubConfig::from_env(),
337        }
338    }
339
340    /// Construct with an explicit config, bypassing env discovery. Used by the
341    /// hosted team server's managed connectors so each scheduled run carries its
342    /// own credential without mutating process-global env (which would race
343    /// across connectors).
344    #[must_use]
345    pub fn with_config(config: GitHubConfig) -> Self {
346        Self { config: Ok(config) }
347    }
348}
349
350impl Default for GitHubProvider {
351    fn default() -> Self {
352        Self::new()
353    }
354}
355
356impl ContextProvider for GitHubProvider {
357    fn id(&self) -> &'static str {
358        "github"
359    }
360
361    fn display_name(&self) -> &'static str {
362        "GitHub"
363    }
364
365    fn supported_actions(&self) -> &[&str] {
366        &["issues", "pull_requests", "actions"]
367    }
368
369    fn execute(&self, action: &str, params: &ProviderParams) -> Result<ProviderResult, String> {
370        let config = self.config.as_ref().map_err(std::clone::Clone::clone)?;
371        match action {
372            "issues" => list_issues(config, params.state.as_deref(), params.limit),
373            "pull_requests" => list_pull_requests(config, params.state.as_deref(), params.limit),
374            "actions" => list_actions(config, params.state.as_deref(), params.limit),
375            _ => Err(format!("Unknown GitHub action: {action}")),
376        }
377    }
378
379    fn cache_ttl_secs(&self) -> u64 {
380        CACHE_TTL_SECS
381    }
382
383    fn is_available(&self) -> bool {
384        self.config.is_ok()
385    }
386}
387
388// ---------------------------------------------------------------------------
389// Tests
390// ---------------------------------------------------------------------------
391
392#[cfg(test)]
393mod tests {
394    use super::{GitHubProvider, parse_github_remote};
395    use crate::core::providers::provider_trait::ContextProvider;
396
397    #[test]
398    fn parse_github_remote_ssh() {
399        let (owner, repo) = parse_github_remote("git@github.com:yvgude/lean-ctx.git");
400        assert_eq!(owner.as_deref(), Some("yvgude"));
401        assert_eq!(repo.as_deref(), Some("lean-ctx"));
402    }
403
404    #[test]
405    fn parse_github_remote_https() {
406        let (owner, repo) = parse_github_remote("https://github.com/yvgude/lean-ctx.git");
407        assert_eq!(owner.as_deref(), Some("yvgude"));
408        assert_eq!(repo.as_deref(), Some("lean-ctx"));
409    }
410
411    #[test]
412    fn parse_github_remote_no_match() {
413        let (owner, repo) = parse_github_remote("git@gitlab.com:foo/bar.git");
414        assert!(owner.is_none());
415        assert!(repo.is_none());
416    }
417
418    #[test]
419    fn provider_unavailable_without_token() {
420        let _env_lock = crate::core::data_dir::test_env_lock();
421        crate::test_env::remove_var("GITHUB_TOKEN");
422        crate::test_env::remove_var("GH_TOKEN");
423        crate::test_env::remove_var("LEAN_CTX_GITHUB_TOKEN");
424        let provider = GitHubProvider::new();
425        assert!(!provider.is_available());
426    }
427
428    #[test]
429    fn provider_reports_correct_id_and_actions() {
430        let provider = GitHubProvider::new();
431        assert_eq!(provider.id(), "github");
432        assert_eq!(provider.display_name(), "GitHub");
433        assert!(provider.supported_actions().contains(&"issues"));
434        assert!(provider.supported_actions().contains(&"pull_requests"));
435        assert!(provider.supported_actions().contains(&"actions"));
436    }
437}