1use std::{fmt, process::Command};
2
3use anyhow::{Context, Result, anyhow, bail};
4
5use crate::git;
6use crate::settings;
7
8mod github;
9mod gitlab;
10mod json;
11
12use github::GitHubProvider;
13use gitlab::GitLabProvider;
14
15#[derive(Debug, Clone, Copy, Eq, PartialEq)]
16pub enum ProviderKind {
17 GitHub,
18 GitLab,
19}
20
21impl ProviderKind {
22 fn parse(value: &str) -> Option<Self> {
23 match value.to_ascii_lowercase().as_str() {
24 "github" | "gh" => Some(Self::GitHub),
25 "gitlab" | "glab" => Some(Self::GitLab),
26 _ => None,
27 }
28 }
29}
30
31impl fmt::Display for ProviderKind {
32 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
33 match self {
34 Self::GitHub => write!(formatter, "github"),
35 Self::GitLab => write!(formatter, "gitlab"),
36 }
37 }
38}
39
40#[derive(Debug, Eq, PartialEq)]
41pub struct DetectedProvider {
42 pub kind: ProviderKind,
43 pub source: ProviderSource,
44}
45
46#[derive(Debug, Eq, PartialEq)]
47pub enum ProviderSource {
48 Config,
49 Remote { remote: String, url: String },
50}
51
52impl fmt::Display for ProviderSource {
53 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match self {
55 Self::Config => write!(formatter, "config"),
56 Self::Remote { remote, url } => write!(formatter, "remote {remote} ({url})"),
57 }
58 }
59}
60
61#[derive(Debug, Eq, PartialEq)]
62pub enum ReviewState {
63 Open,
64 Merged,
65 Closed,
66 Unknown(String),
67}
68
69#[derive(Debug, Eq, PartialEq)]
70pub struct ReviewRequest {
71 pub id: String,
72 pub branch: String,
73 pub base: String,
74 pub state: ReviewState,
75 pub url: String,
76 pub title: String,
77}
78
79pub trait ReviewProvider {
80 fn review_for_branch(&self, branch: &str) -> Result<Option<ReviewRequest>>;
81
82 fn create_review(&self, branch: &str, base: &str) -> Result<String>;
83
84 fn update_review_base(&self, review: &ReviewRequest, base: &str) -> Result<String>;
85
86 fn review_body(&self, review: &ReviewRequest) -> Result<String>;
87
88 fn update_review_body(&self, review: &ReviewRequest, body: &str) -> Result<String>;
89
90 fn merge_review(&self, review: &ReviewRequest, strategy: &str) -> Result<String>;
92}
93
94pub fn detect_provider() -> Result<DetectedProvider> {
95 if let Some(value) = git::config_get(settings::PROVIDER_KEY)? {
96 let Some(kind) = ProviderKind::parse(&value) else {
97 bail!("unsupported stk.provider value {value:?}; expected github or gitlab");
98 };
99
100 return Ok(DetectedProvider {
101 kind,
102 source: ProviderSource::Config,
103 });
104 }
105
106 let remote = settings::remote()?;
107 let Some(url) = git::remote_url(&remote)? else {
108 bail!("could not detect provider: remote {remote:?} does not exist");
109 };
110
111 let Some(kind) = detect_provider_from_url(&url) else {
112 bail!("could not detect provider from remote {remote} ({url})");
113 };
114
115 Ok(DetectedProvider {
116 kind,
117 source: ProviderSource::Remote { remote, url },
118 })
119}
120
121fn detect_provider_from_url(url: &str) -> Option<ProviderKind> {
122 let normalized = url.to_ascii_lowercase();
123
124 if normalized.contains("github.com:") || normalized.contains("github.com/") {
125 Some(ProviderKind::GitHub)
126 } else if normalized.contains("gitlab.com:") || normalized.contains("gitlab.com/") {
127 Some(ProviderKind::GitLab)
128 } else {
129 None
130 }
131}
132
133pub(crate) fn review_provider(kind: ProviderKind) -> Box<dyn ReviewProvider> {
134 match kind {
135 ProviderKind::GitHub => Box::new(GitHubProvider),
136 ProviderKind::GitLab => Box::new(GitLabProvider),
137 }
138}
139
140fn command_output(program: &str, args: &[&str]) -> Result<String> {
141 let output = Command::new(program)
142 .args(args)
143 .output()
144 .with_context(|| format!("failed to run {program}"))?;
145
146 if output.status.success() {
147 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
148 } else {
149 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
150 if stderr.is_empty() {
151 Err(anyhow!("{program} exited with status {}", output.status))
152 } else {
153 Err(anyhow!("{program} failed: {stderr}"))
154 }
155 }
156}
157
158impl fmt::Display for ReviewState {
159 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
160 match self {
161 Self::Open => write!(formatter, "open"),
162 Self::Merged => write!(formatter, "merged"),
163 Self::Closed => write!(formatter, "closed"),
164 Self::Unknown(state) => write!(formatter, "{state}"),
165 }
166 }
167}
168
169impl ReviewRequest {
170 pub(crate) fn id_value(&self) -> &str {
171 self.id
172 .strip_prefix('#')
173 .or_else(|| self.id.strip_prefix('!'))
174 .unwrap_or(&self.id)
175 }
176}