lean_ctx/core/providers/
config.rs1use std::env;
2
3#[derive(Clone)]
4pub struct GitLabConfig {
5 pub host: String,
6 pub token: String,
7 pub project_path: Option<String>,
8}
9
10impl std::fmt::Debug for GitLabConfig {
11 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12 f.debug_struct("GitLabConfig")
13 .field("host", &self.host)
14 .field("token", &"[REDACTED]")
15 .field("project_path", &self.project_path)
16 .finish()
17 }
18}
19
20impl GitLabConfig {
21 pub(crate) fn from_session() -> Result<Self, String> {
22 super::selected_gitlab::config().map_or_else(Self::from_env, Ok)
23 }
24
25 pub fn from_env() -> Result<Self, String> {
26 let token = env::var("LEAN_CTX_GITLAB_TOKEN")
27 .or_else(|_| env::var("GITLAB_TOKEN"))
28 .or_else(|_| env::var("CI_JOB_TOKEN"))
29 .map_err(|_| {
30 "No GitLab token found. Set GITLAB_TOKEN or LEAN_CTX_GITLAB_TOKEN.".to_string()
31 })?;
32
33 let host = env::var("GITLAB_HOST")
34 .or_else(|_| env::var("CI_SERVER_HOST"))
35 .unwrap_or_else(|_| "gitlab.com".to_string());
36
37 let project_path = env::var("CI_PROJECT_PATH")
38 .ok()
39 .or_else(|| detect_project_from_git_remote(&host));
40
41 Ok(Self {
42 host,
43 token,
44 project_path,
45 })
46 }
47
48 pub fn api_url(&self, endpoint: &str) -> String {
49 format!("https://{}/api/v4{}", self.host, endpoint)
50 }
51}
52
53fn detect_project_from_git_remote(host: &str) -> Option<String> {
54 let output = std::process::Command::new("git")
55 .args(["remote", "get-url", "origin"])
56 .output()
57 .ok()?;
58 if !output.status.success() {
59 return None;
60 }
61 let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
62
63 if let Some(rest) = url.strip_prefix(&format!("git@{host}:")) {
65 return Some(rest.trim_end_matches(".git").to_string());
66 }
67 if let Some(rest) = url.strip_prefix(&format!("https://{host}/")) {
69 return Some(rest.trim_end_matches(".git").to_string());
70 }
71 None
72}