Skip to main content

git_stk/providers/
mod.rs

1use std::time::Duration;
2use std::{fmt, process::Command};
3
4use anyhow::{Context, Result, anyhow, bail};
5
6use crate::git;
7use crate::settings;
8
9/// How long to keep polling a "no checks / no pipeline yet" result before
10/// concluding there genuinely are none. A just-pushed branch's checks take a
11/// moment to register, so concluding too early would either merge without
12/// waiting or report a false failure.
13pub(super) const CHECK_GRACE_POLLS: u32 = 6;
14
15/// Delay between `wait_for_checks` polls.
16pub(super) fn check_poll_interval() -> Duration {
17    Duration::from_secs(5)
18}
19
20mod demo;
21mod github;
22mod gitlab;
23mod json;
24
25use demo::DemoProvider;
26use github::GitHubProvider;
27use gitlab::GitLabProvider;
28
29#[derive(Debug, Clone, Copy, Eq, PartialEq)]
30pub enum ProviderKind {
31    GitHub,
32    GitLab,
33    /// Offline stand-in: reviews in `.git`, merges as local squashes. Only
34    /// ever selected explicitly via `stk.provider = demo`.
35    Demo,
36}
37
38impl ProviderKind {
39    fn parse(value: &str) -> Option<Self> {
40        match value.to_ascii_lowercase().as_str() {
41            "github" | "gh" => Some(Self::GitHub),
42            "gitlab" | "glab" => Some(Self::GitLab),
43            "demo" => Some(Self::Demo),
44            _ => None,
45        }
46    }
47}
48
49impl fmt::Display for ProviderKind {
50    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            Self::GitHub => write!(formatter, "github"),
53            Self::GitLab => write!(formatter, "gitlab"),
54            Self::Demo => write!(formatter, "demo"),
55        }
56    }
57}
58
59#[derive(Debug, Eq, PartialEq)]
60pub struct DetectedProvider {
61    pub kind: ProviderKind,
62    pub source: ProviderSource,
63}
64
65#[derive(Debug, Eq, PartialEq)]
66pub enum ProviderSource {
67    Config,
68    Remote { remote: String, url: String },
69}
70
71impl fmt::Display for ProviderSource {
72    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self {
74            Self::Config => write!(formatter, "config"),
75            Self::Remote { remote, url } => write!(formatter, "remote {remote} ({url})"),
76        }
77    }
78}
79
80#[derive(Debug, Eq, PartialEq)]
81pub enum ReviewState {
82    Open,
83    Merged,
84    Closed,
85    Unknown(String),
86}
87
88#[derive(Debug, Eq, PartialEq)]
89pub struct ReviewRequest {
90    pub id: String,
91    pub branch: String,
92    pub base: String,
93    pub state: ReviewState,
94    pub url: String,
95    pub title: String,
96    pub draft: bool,
97}
98
99pub trait ReviewProvider {
100    fn review_for_branch(&self, branch: &str) -> Result<Option<ReviewRequest>>;
101
102    /// Like review_for_branch, but also finds closed reviews. Kept separate
103    /// so flows that act on a review (submit, sync, cleanup) never mistake a
104    /// dead review for a live one; only the stack-notes ledger wants closed
105    /// state, to restyle the entry rather than drop it.
106    fn review_for_branch_including_closed(&self, branch: &str) -> Result<Option<ReviewRequest>>;
107
108    /// Open a review for the branch; with `draft`, as a draft.
109    fn create_review(&self, branch: &str, base: &str, draft: bool) -> Result<String>;
110
111    fn update_review_base(&self, review: &ReviewRequest, base: &str) -> Result<String>;
112
113    fn review_body(&self, review: &ReviewRequest) -> Result<String>;
114
115    fn update_review_body(&self, review: &ReviewRequest, body: &str) -> Result<String>;
116
117    /// Merge the review with the given strategy: squash, rebase, or merge.
118    /// With `auto`, schedule the merge for when required checks pass
119    /// instead of merging now.
120    fn merge_review(&self, review: &ReviewRequest, strategy: &str, auto: bool) -> Result<String>;
121
122    /// Block until the review's checks settle. Ok(true) when they pass (or
123    /// there are none), Ok(false) when something failed.
124    fn wait_for_checks(&self, review: &ReviewRequest) -> Result<bool>;
125
126    /// Mark a draft review as ready for review.
127    fn mark_ready(&self, review: &ReviewRequest) -> Result<String>;
128
129    /// Open the review in the user's browser.
130    fn open_review(&self, review: &ReviewRequest) -> Result<String>;
131}
132
133pub fn detect_provider() -> Result<DetectedProvider> {
134    if let Some(value) = git::config_get(settings::PROVIDER_KEY)? {
135        let Some(kind) = ProviderKind::parse(&value) else {
136            bail!("unsupported stk.provider value {value:?}; expected github or gitlab");
137        };
138
139        return Ok(DetectedProvider {
140            kind,
141            source: ProviderSource::Config,
142        });
143    }
144
145    let remote = settings::remote()?;
146    let Some(url) = git::remote_url(&remote)? else {
147        bail!("could not detect provider: remote {remote:?} does not exist");
148    };
149
150    let gitlab_host = settings::gitlab_host()?;
151    let Some(kind) = detect_provider_from_url(&url, gitlab_host.as_deref()) else {
152        bail!("could not detect provider from remote {remote} ({url})");
153    };
154
155    Ok(DetectedProvider {
156        kind,
157        source: ProviderSource::Remote { remote, url },
158    })
159}
160
161/// Recognize a host in a remote URL, in either `host:owner/repo` (SSH) or
162/// `host/owner/repo` (HTTPS) form. A configured `stk.gitlab.host` widens
163/// GitLab detection to a self-hosted instance.
164fn detect_provider_from_url(url: &str, gitlab_host: Option<&str>) -> Option<ProviderKind> {
165    let normalized = url.to_ascii_lowercase();
166    let hosts = |host: &str| {
167        normalized.contains(&format!("{host}:")) || normalized.contains(&format!("{host}/"))
168    };
169
170    if hosts("github.com") {
171        Some(ProviderKind::GitHub)
172    } else if hosts("gitlab.com")
173        || gitlab_host.is_some_and(|host| hosts(&host.to_ascii_lowercase()))
174    {
175        Some(ProviderKind::GitLab)
176    } else {
177        None
178    }
179}
180
181pub(crate) fn review_provider(kind: ProviderKind) -> Box<dyn ReviewProvider> {
182    match kind {
183        ProviderKind::GitHub => Box::new(GitHubProvider),
184        ProviderKind::GitLab => Box::new(GitLabProvider),
185        ProviderKind::Demo => Box::new(DemoProvider),
186    }
187}
188
189fn command_output(program: &str, args: &[&str]) -> Result<String> {
190    let output = Command::new(program)
191        .args(args)
192        .output()
193        .with_context(|| format!("failed to run {program}"))?;
194
195    if output.status.success() {
196        Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
197    } else {
198        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
199        if stderr.is_empty() {
200            Err(anyhow!("{program} exited with status {}", output.status))
201        } else {
202            Err(anyhow!("{program} failed: {stderr}"))
203        }
204    }
205}
206
207impl fmt::Display for ReviewState {
208    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
209        match self {
210            Self::Open => write!(formatter, "open"),
211            Self::Merged => write!(formatter, "merged"),
212            Self::Closed => write!(formatter, "closed"),
213            Self::Unknown(state) => write!(formatter, "{state}"),
214        }
215    }
216}
217
218impl ReviewRequest {
219    pub(crate) fn id_value(&self) -> &str {
220        self.id
221            .strip_prefix('#')
222            .or_else(|| self.id.strip_prefix('!'))
223            .unwrap_or(&self.id)
224    }
225
226    /// "Title (#12)", or just the id when there is no title.
227    pub fn label(&self) -> String {
228        label(&self.title, &self.id)
229    }
230}
231
232/// The display label for a review: "Title (#12)", or the bare id.
233pub(crate) fn label(title: &str, id: &str) -> String {
234    if title.is_empty() {
235        id.to_owned()
236    } else {
237        format!("{title} ({id})")
238    }
239}