codeberg.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
 17#[derive(Debug, Deserialize)]
 18struct CommitDetails {
 19    #[expect(
 20        unused,
 21        reason = "This field was found to be unused with serde library bump; it's left as is due to insufficient context on PO's side, but it *may* be fine to remove"
 22    )]
 23    commit: Commit,
 24    author: Option<User>,
 25}
 26
 27#[derive(Debug, Deserialize)]
 28struct Commit {
 29    #[expect(
 30        unused,
 31        reason = "This field was found to be unused with serde library bump; it's left as is due to insufficient context on PO's side, but it *may* be fine to remove"
 32    )]
 33    author: Author,
 34}
 35
 36#[derive(Debug, Deserialize)]
 37struct Author {
 38    #[expect(
 39        unused,
 40        reason = "This field was found to be unused with serde library bump; it's left as is due to insufficient context on PO's side, but it *may* be fine to remove"
 41    )]
 42    name: String,
 43    #[expect(
 44        unused,
 45        reason = "This field was found to be unused with serde library bump; it's left as is due to insufficient context on PO's side, but it *may* be fine to remove"
 46    )]
 47    email: String,
 48    #[expect(
 49        unused,
 50        reason = "This field was found to be unused with serde library bump; it's left as is due to insufficient context on PO's side, but it *may* be fine to remove"
 51    )]
 52    date: String,
 53}
 54
 55#[derive(Debug, Deserialize)]
 56struct User {
 57    #[expect(
 58        unused,
 59        reason = "This field was found to be unused with serde library bump; it's left as is due to insufficient context on PO's side, but it *may* be fine to remove"
 60    )]
 61    pub login: String,
 62    #[expect(
 63        unused,
 64        reason = "This field was found to be unused with serde library bump; it's left as is due to insufficient context on PO's side, but it *may* be fine to remove"
 65    )]
 66    pub id: u64,
 67    pub avatar_url: String,
 68}
 69
 70pub struct Codeberg;
 71
 72impl Codeberg {
 73    async fn fetch_codeberg_commit_author(
 74        &self,
 75        repo_owner: &str,
 76        repo: &str,
 77        commit: &str,
 78        client: &Arc<dyn HttpClient>,
 79    ) -> Result<Option<User>> {
 80        let url =
 81            format!("https://codeberg.org/api/v1/repos/{repo_owner}/{repo}/git/commits/{commit}");
 82
 83        let mut request = Request::get(&url)
 84            .header("Content-Type", "application/json")
 85            .follow_redirects(http_client::RedirectPolicy::FollowAll);
 86
 87        if let Ok(codeberg_token) = std::env::var("CODEBERG_TOKEN") {
 88            request = request.header("Authorization", format!("Bearer {}", codeberg_token));
 89        }
 90
 91        let mut response = client
 92            .send(request.body(AsyncBody::default())?)
 93            .await
 94            .with_context(|| format!("error fetching Codeberg commit details at {:?}", url))?;
 95
 96        let mut body = Vec::new();
 97        response.body_mut().read_to_end(&mut body).await?;
 98
 99        if response.status().is_client_error() {
100            let text = String::from_utf8_lossy(body.as_slice());
101            bail!(
102                "status error {}, response: {text:?}",
103                response.status().as_u16()
104            );
105        }
106
107        let body_str = std::str::from_utf8(&body)?;
108
109        serde_json::from_str::<CommitDetails>(body_str)
110            .map(|commit| commit.author)
111            .context("failed to deserialize Codeberg commit details")
112    }
113}
114
115#[async_trait]
116impl GitHostingProvider for Codeberg {
117    fn name(&self) -> String {
118        "Codeberg".to_string()
119    }
120
121    fn base_url(&self) -> Url {
122        Url::parse("https://codeberg.org").unwrap()
123    }
124
125    fn supports_avatars(&self) -> bool {
126        true
127    }
128
129    fn format_line_number(&self, line: u32) -> String {
130        format!("L{line}")
131    }
132
133    fn format_line_numbers(&self, start_line: u32, end_line: u32) -> String {
134        format!("L{start_line}-L{end_line}")
135    }
136
137    fn parse_remote_url(&self, url: &str) -> Option<ParsedGitRemote> {
138        let url = RemoteUrl::from_str(url).ok()?;
139
140        let host = url.host_str()?;
141        if host != "codeberg.org" {
142            return None;
143        }
144
145        let mut path_segments = url.path_segments()?;
146        let owner = path_segments.next()?;
147        let repo = path_segments.next()?.trim_end_matches(".git");
148
149        Some(ParsedGitRemote {
150            owner: owner.into(),
151            repo: repo.into(),
152        })
153    }
154
155    fn build_commit_permalink(
156        &self,
157        remote: &ParsedGitRemote,
158        params: BuildCommitPermalinkParams,
159    ) -> Url {
160        let BuildCommitPermalinkParams { sha } = params;
161        let ParsedGitRemote { owner, repo } = remote;
162
163        self.base_url()
164            .join(&format!("{owner}/{repo}/commit/{sha}"))
165            .unwrap()
166    }
167
168    fn build_permalink(&self, remote: ParsedGitRemote, params: BuildPermalinkParams) -> Url {
169        let ParsedGitRemote { owner, repo } = remote;
170        let BuildPermalinkParams {
171            sha,
172            path,
173            selection,
174        } = params;
175
176        let mut permalink = self
177            .base_url()
178            .join(&format!("{owner}/{repo}/src/commit/{sha}/{path}"))
179            .unwrap();
180        permalink.set_fragment(
181            selection
182                .map(|selection| self.line_fragment(&selection))
183                .as_deref(),
184        );
185        permalink
186    }
187
188    async fn commit_author_avatar_url(
189        &self,
190        repo_owner: &str,
191        repo: &str,
192        commit: SharedString,
193        http_client: Arc<dyn HttpClient>,
194    ) -> Result<Option<Url>> {
195        let commit = commit.to_string();
196        let avatar_url = self
197            .fetch_codeberg_commit_author(repo_owner, repo, &commit, &http_client)
198            .await?
199            .map(|author| Url::parse(&author.avatar_url))
200            .transpose()?;
201        Ok(avatar_url)
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use pretty_assertions::assert_eq;
208
209    use super::*;
210
211    #[test]
212    fn test_parse_remote_url_given_ssh_url() {
213        let parsed_remote = Codeberg
214            .parse_remote_url("git@codeberg.org:zed-industries/zed.git")
215            .unwrap();
216
217        assert_eq!(
218            parsed_remote,
219            ParsedGitRemote {
220                owner: "zed-industries".into(),
221                repo: "zed".into(),
222            }
223        );
224    }
225
226    #[test]
227    fn test_parse_remote_url_given_https_url() {
228        let parsed_remote = Codeberg
229            .parse_remote_url("https://codeberg.org/zed-industries/zed.git")
230            .unwrap();
231
232        assert_eq!(
233            parsed_remote,
234            ParsedGitRemote {
235                owner: "zed-industries".into(),
236                repo: "zed".into(),
237            }
238        );
239    }
240
241    #[test]
242    fn test_build_codeberg_permalink() {
243        let permalink = Codeberg.build_permalink(
244            ParsedGitRemote {
245                owner: "zed-industries".into(),
246                repo: "zed".into(),
247            },
248            BuildPermalinkParams {
249                sha: "faa6f979be417239b2e070dbbf6392b909224e0b",
250                path: "crates/editor/src/git/permalink.rs",
251                selection: None,
252            },
253        );
254
255        let expected_url = "https://codeberg.org/zed-industries/zed/src/commit/faa6f979be417239b2e070dbbf6392b909224e0b/crates/editor/src/git/permalink.rs";
256        assert_eq!(permalink.to_string(), expected_url.to_string())
257    }
258
259    #[test]
260    fn test_build_codeberg_permalink_with_single_line_selection() {
261        let permalink = Codeberg.build_permalink(
262            ParsedGitRemote {
263                owner: "zed-industries".into(),
264                repo: "zed".into(),
265            },
266            BuildPermalinkParams {
267                sha: "faa6f979be417239b2e070dbbf6392b909224e0b",
268                path: "crates/editor/src/git/permalink.rs",
269                selection: Some(6..6),
270            },
271        );
272
273        let expected_url = "https://codeberg.org/zed-industries/zed/src/commit/faa6f979be417239b2e070dbbf6392b909224e0b/crates/editor/src/git/permalink.rs#L7";
274        assert_eq!(permalink.to_string(), expected_url.to_string())
275    }
276
277    #[test]
278    fn test_build_codeberg_permalink_with_multi_line_selection() {
279        let permalink = Codeberg.build_permalink(
280            ParsedGitRemote {
281                owner: "zed-industries".into(),
282                repo: "zed".into(),
283            },
284            BuildPermalinkParams {
285                sha: "faa6f979be417239b2e070dbbf6392b909224e0b",
286                path: "crates/editor/src/git/permalink.rs",
287                selection: Some(23..47),
288            },
289        );
290
291        let expected_url = "https://codeberg.org/zed-industries/zed/src/commit/faa6f979be417239b2e070dbbf6392b909224e0b/crates/editor/src/git/permalink.rs#L24-L48";
292        assert_eq!(permalink.to_string(), expected_url.to_string())
293    }
294}