gitea.rs

  1use std::str::FromStr;
  2use std::sync::Arc;
  3
  4use anyhow::{Context as _, Result, bail};
  5use async_trait::async_trait;
  6use futures::AsyncReadExt;
  7use gpui::SharedString;
  8use http_client::{AsyncBody, HttpClient, HttpRequestExt, Request};
  9use serde::Deserialize;
 10use url::Url;
 11
 12use git::{
 13    BuildCommitPermalinkParams, BuildPermalinkParams, GitHostingProvider, ParsedGitRemote,
 14    RemoteUrl,
 15};
 16
 17use crate::get_host_from_git_remote_url;
 18
 19#[derive(Debug, Deserialize)]
 20struct CommitDetails {
 21    author: Option<User>,
 22}
 23
 24#[derive(Debug, Deserialize)]
 25struct User {
 26    pub avatar_url: String,
 27}
 28
 29pub struct Gitea {
 30    name: String,
 31    base_url: Url,
 32}
 33
 34impl Gitea {
 35    pub fn new(name: impl Into<String>, base_url: Url) -> Self {
 36        Self {
 37            name: name.into(),
 38            base_url,
 39        }
 40    }
 41
 42    pub fn public_instance() -> Self {
 43        Self::new("Gitea", Url::parse("https://gitea.com").unwrap())
 44    }
 45
 46    pub fn from_remote_url(remote_url: &str) -> Result<Self> {
 47        let host = get_host_from_git_remote_url(remote_url)?;
 48        if host == "gitea.com" {
 49            bail!("the Gitea instance is not self-hosted");
 50        }
 51
 52        // TODO: detecting self hosted instances by checking whether "gitea" is in the url or not
 53        // is not very reliable. See https://github.com/zed-industries/zed/issues/26393 for more
 54        // information.
 55        if !host.contains("gitea") {
 56            bail!("not a Gitea URL");
 57        }
 58
 59        Ok(Self::new(
 60            "Gitea Self-Hosted",
 61            Url::parse(&format!("https://{}", host))?,
 62        ))
 63    }
 64
 65    async fn fetch_gitea_commit_author(
 66        &self,
 67        repo_owner: &str,
 68        repo: &str,
 69        commit: &str,
 70        client: &Arc<dyn HttpClient>,
 71    ) -> Result<Option<User>> {
 72        let Some(host) = self.base_url.host_str() else {
 73            bail!("failed to get host from gitea base url");
 74        };
 75        let url = format!(
 76            "https://{host}/api/v1/repos/{repo_owner}/{repo}/git/commits/{commit}?stat=false&verification=false&files=false"
 77        );
 78
 79        let request = Request::get(&url)
 80            .header("Content-Type", "application/json")
 81            .follow_redirects(http_client::RedirectPolicy::FollowAll);
 82
 83        let mut response = client
 84            .send(request.body(AsyncBody::default())?)
 85            .await
 86            .with_context(|| format!("error fetching Gitea commit details at {:?}", url))?;
 87
 88        let mut body = Vec::new();
 89        response.body_mut().read_to_end(&mut body).await?;
 90
 91        if response.status().is_client_error() {
 92            let text = String::from_utf8_lossy(body.as_slice());
 93            bail!(
 94                "status error {}, response: {text:?}",
 95                response.status().as_u16()
 96            );
 97        }
 98
 99        let body_str = std::str::from_utf8(&body)?;
100
101        serde_json::from_str::<CommitDetails>(body_str)
102            .map(|commit| commit.author)
103            .context("failed to deserialize Gitea commit details")
104    }
105}
106
107#[async_trait]
108impl GitHostingProvider for Gitea {
109    fn name(&self) -> String {
110        self.name.clone()
111    }
112
113    fn base_url(&self) -> Url {
114        self.base_url.clone()
115    }
116
117    fn supports_avatars(&self) -> bool {
118        true
119    }
120
121    fn format_line_number(&self, line: u32) -> String {
122        format!("L{line}")
123    }
124
125    fn format_line_numbers(&self, start_line: u32, end_line: u32) -> String {
126        format!("L{start_line}-L{end_line}")
127    }
128
129    fn parse_remote_url(&self, url: &str) -> Option<ParsedGitRemote> {
130        let url = RemoteUrl::from_str(url).ok()?;
131
132        let host = url.host_str()?;
133        if host != self.base_url.host_str()? {
134            return None;
135        }
136
137        let mut path_segments = url.path_segments()?;
138        let owner = path_segments.next()?;
139        let repo = path_segments.next()?.trim_end_matches(".git");
140
141        Some(ParsedGitRemote {
142            owner: owner.into(),
143            repo: repo.into(),
144        })
145    }
146
147    fn build_commit_permalink(
148        &self,
149        remote: &ParsedGitRemote,
150        params: BuildCommitPermalinkParams,
151    ) -> Url {
152        let BuildCommitPermalinkParams { sha } = params;
153        let ParsedGitRemote { owner, repo } = remote;
154
155        self.base_url()
156            .join(&format!("{owner}/{repo}/commit/{sha}"))
157            .unwrap()
158    }
159
160    fn build_permalink(&self, remote: ParsedGitRemote, params: BuildPermalinkParams) -> Url {
161        let ParsedGitRemote { owner, repo } = remote;
162        let BuildPermalinkParams {
163            sha,
164            path,
165            selection,
166        } = params;
167
168        let mut permalink = self
169            .base_url()
170            .join(&format!("{owner}/{repo}/src/commit/{sha}/{path}"))
171            .unwrap();
172        permalink.set_fragment(
173            selection
174                .map(|selection| self.line_fragment(&selection))
175                .as_deref(),
176        );
177        permalink
178    }
179
180    async fn commit_author_avatar_url(
181        &self,
182        repo_owner: &str,
183        repo: &str,
184        commit: SharedString,
185        http_client: Arc<dyn HttpClient>,
186    ) -> Result<Option<Url>> {
187        let commit = commit.to_string();
188        let avatar_url = self
189            .fetch_gitea_commit_author(repo_owner, repo, &commit, &http_client)
190            .await?
191            .map(|author| -> Result<Url, url::ParseError> {
192                let mut url = Url::parse(&author.avatar_url)?;
193                if let Some(host) = url.host_str() {
194                    let size_query = if host.contains("gravatar") || host.contains("libravatar") {
195                        Some("s=128")
196                    } else if self
197                        .base_url
198                        .host_str()
199                        .is_some_and(|base_host| host.contains(base_host))
200                    {
201                        Some("size=128")
202                    } else {
203                        None
204                    };
205                    url.set_query(size_query);
206                }
207                Ok(url)
208            })
209            .transpose()?;
210        Ok(avatar_url)
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use git::repository::repo_path;
217    use pretty_assertions::assert_eq;
218
219    use super::*;
220
221    #[test]
222    fn test_parse_remote_url_given_ssh_url() {
223        let parsed_remote = Gitea::public_instance()
224            .parse_remote_url("git@gitea.com:zed-industries/zed.git")
225            .unwrap();
226
227        assert_eq!(
228            parsed_remote,
229            ParsedGitRemote {
230                owner: "zed-industries".into(),
231                repo: "zed".into(),
232            }
233        );
234    }
235
236    #[test]
237    fn test_parse_remote_url_given_https_url() {
238        let parsed_remote = Gitea::public_instance()
239            .parse_remote_url("https://gitea.com/zed-industries/zed.git")
240            .unwrap();
241
242        assert_eq!(
243            parsed_remote,
244            ParsedGitRemote {
245                owner: "zed-industries".into(),
246                repo: "zed".into(),
247            }
248        );
249    }
250
251    #[test]
252    fn test_parse_remote_url_given_self_hosted_ssh_url() {
253        let remote_url = "git@gitea.my-enterprise.com:zed-industries/zed.git";
254
255        let parsed_remote = Gitea::from_remote_url(remote_url)
256            .unwrap()
257            .parse_remote_url(remote_url)
258            .unwrap();
259
260        assert_eq!(
261            parsed_remote,
262            ParsedGitRemote {
263                owner: "zed-industries".into(),
264                repo: "zed".into(),
265            }
266        );
267    }
268
269    #[test]
270    fn test_parse_remote_url_given_self_hosted_https_url() {
271        let remote_url = "https://gitea.my-enterprise.com/zed-industries/zed.git";
272        let parsed_remote = Gitea::from_remote_url(remote_url)
273            .unwrap()
274            .parse_remote_url(remote_url)
275            .unwrap();
276
277        assert_eq!(
278            parsed_remote,
279            ParsedGitRemote {
280                owner: "zed-industries".into(),
281                repo: "zed".into(),
282            }
283        );
284    }
285
286    #[test]
287    fn test_build_codeberg_permalink() {
288        let permalink = Gitea::public_instance().build_permalink(
289            ParsedGitRemote {
290                owner: "zed-industries".into(),
291                repo: "zed".into(),
292            },
293            BuildPermalinkParams::new(
294                "faa6f979be417239b2e070dbbf6392b909224e0b",
295                &repo_path("crates/editor/src/git/permalink.rs"),
296                None,
297            ),
298        );
299
300        let expected_url = "https://gitea.com/zed-industries/zed/src/commit/faa6f979be417239b2e070dbbf6392b909224e0b/crates/editor/src/git/permalink.rs";
301        assert_eq!(permalink.to_string(), expected_url.to_string())
302    }
303
304    #[test]
305    fn test_build_codeberg_permalink_with_single_line_selection() {
306        let permalink = Gitea::public_instance().build_permalink(
307            ParsedGitRemote {
308                owner: "zed-industries".into(),
309                repo: "zed".into(),
310            },
311            BuildPermalinkParams::new(
312                "faa6f979be417239b2e070dbbf6392b909224e0b",
313                &repo_path("crates/editor/src/git/permalink.rs"),
314                Some(6..6),
315            ),
316        );
317
318        let expected_url = "https://gitea.com/zed-industries/zed/src/commit/faa6f979be417239b2e070dbbf6392b909224e0b/crates/editor/src/git/permalink.rs#L7";
319        assert_eq!(permalink.to_string(), expected_url.to_string())
320    }
321
322    #[test]
323    fn test_build_codeberg_permalink_with_multi_line_selection() {
324        let permalink = Gitea::public_instance().build_permalink(
325            ParsedGitRemote {
326                owner: "zed-industries".into(),
327                repo: "zed".into(),
328            },
329            BuildPermalinkParams::new(
330                "faa6f979be417239b2e070dbbf6392b909224e0b",
331                &repo_path("crates/editor/src/git/permalink.rs"),
332                Some(23..47),
333            ),
334        );
335
336        let expected_url = "https://gitea.com/zed-industries/zed/src/commit/faa6f979be417239b2e070dbbf6392b909224e0b/crates/editor/src/git/permalink.rs#L24-L48";
337        assert_eq!(permalink.to_string(), expected_url.to_string())
338    }
339
340    #[test]
341    fn test_build_gitea_self_hosted_permalink_from_ssh_url() {
342        let gitea =
343            Gitea::from_remote_url("git@gitea.some-enterprise.com:zed-industries/zed.git").unwrap();
344        let permalink = gitea.build_permalink(
345            ParsedGitRemote {
346                owner: "zed-industries".into(),
347                repo: "zed".into(),
348            },
349            BuildPermalinkParams::new(
350                "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
351                &repo_path("crates/editor/src/git/permalink.rs"),
352                None,
353            ),
354        );
355
356        let expected_url = "https://gitea.some-enterprise.com/zed-industries/zed/src/commit/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs";
357        assert_eq!(permalink.to_string(), expected_url.to_string())
358    }
359
360    #[test]
361    fn test_build_gitea_self_hosted_permalink_from_https_url() {
362        let gitea =
363            Gitea::from_remote_url("https://gitea-instance.big-co.com/zed-industries/zed.git")
364                .unwrap();
365        let permalink = gitea.build_permalink(
366            ParsedGitRemote {
367                owner: "zed-industries".into(),
368                repo: "zed".into(),
369            },
370            BuildPermalinkParams::new(
371                "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
372                &repo_path("crates/zed/src/main.rs"),
373                None,
374            ),
375        );
376
377        let expected_url = "https://gitea-instance.big-co.com/zed-industries/zed/src/commit/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs";
378        assert_eq!(permalink.to_string(), expected_url.to_string())
379    }
380}