gitlab.rs

  1use std::str::FromStr;
  2
  3use anyhow::{Result, bail};
  4use url::Url;
  5
  6use git::{
  7    BuildCommitPermalinkParams, BuildPermalinkParams, GitHostingProvider, ParsedGitRemote,
  8    RemoteUrl,
  9};
 10
 11use crate::get_host_from_git_remote_url;
 12
 13#[derive(Debug)]
 14pub struct Gitlab {
 15    name: String,
 16    base_url: Url,
 17}
 18
 19impl Gitlab {
 20    pub fn new(name: impl Into<String>, base_url: Url) -> Self {
 21        Self {
 22            name: name.into(),
 23            base_url,
 24        }
 25    }
 26
 27    pub fn public_instance() -> Self {
 28        Self::new("GitLab", Url::parse("https://gitlab.com").unwrap())
 29    }
 30
 31    pub fn from_remote_url(remote_url: &str) -> Result<Self> {
 32        let host = get_host_from_git_remote_url(remote_url)?;
 33        if host == "gitlab.com" {
 34            bail!("the GitLab instance is not self-hosted");
 35        }
 36
 37        // TODO: detecting self hosted instances by checking whether "gitlab" is in the url or not
 38        // is not very reliable. See https://github.com/zed-industries/zed/issues/26393 for more
 39        // information.
 40        if !host.contains("gitlab") {
 41            bail!("not a GitLab URL");
 42        }
 43
 44        Ok(Self::new(
 45            "GitLab Self-Hosted",
 46            Url::parse(&format!("https://{}", host))?,
 47        ))
 48    }
 49}
 50
 51impl GitHostingProvider for Gitlab {
 52    fn name(&self) -> String {
 53        self.name.clone()
 54    }
 55
 56    fn base_url(&self) -> Url {
 57        self.base_url.clone()
 58    }
 59
 60    fn supports_avatars(&self) -> bool {
 61        false
 62    }
 63
 64    fn format_line_number(&self, line: u32) -> String {
 65        format!("L{line}")
 66    }
 67
 68    fn format_line_numbers(&self, start_line: u32, end_line: u32) -> String {
 69        format!("L{start_line}-{end_line}")
 70    }
 71
 72    fn parse_remote_url(&self, url: &str) -> Option<ParsedGitRemote> {
 73        let url = RemoteUrl::from_str(url).ok()?;
 74
 75        let host = url.host_str()?;
 76        if host != self.base_url.host_str()? {
 77            return None;
 78        }
 79
 80        let mut path_segments = url.path_segments()?.collect::<Vec<_>>();
 81        let repo = path_segments.pop()?.trim_end_matches(".git");
 82        let owner = path_segments.join("/");
 83
 84        Some(ParsedGitRemote {
 85            owner: owner.into(),
 86            repo: repo.into(),
 87        })
 88    }
 89
 90    fn build_commit_permalink(
 91        &self,
 92        remote: &ParsedGitRemote,
 93        params: BuildCommitPermalinkParams,
 94    ) -> Url {
 95        let BuildCommitPermalinkParams { sha } = params;
 96        let ParsedGitRemote { owner, repo } = remote;
 97
 98        self.base_url()
 99            .join(&format!("{owner}/{repo}/-/commit/{sha}"))
100            .unwrap()
101    }
102
103    fn build_permalink(&self, remote: ParsedGitRemote, params: BuildPermalinkParams) -> Url {
104        let ParsedGitRemote { owner, repo } = remote;
105        let BuildPermalinkParams {
106            sha,
107            path,
108            selection,
109        } = params;
110
111        let mut permalink = self
112            .base_url()
113            .join(&format!("{owner}/{repo}/-/blob/{sha}/{path}"))
114            .unwrap();
115        if path.ends_with(".md") {
116            permalink.set_query(Some("plain=1"));
117        }
118        permalink.set_fragment(
119            selection
120                .map(|selection| self.line_fragment(&selection))
121                .as_deref(),
122        );
123        permalink
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use pretty_assertions::assert_eq;
130
131    use super::*;
132
133    #[test]
134    fn test_invalid_self_hosted_remote_url() {
135        let remote_url = "https://gitlab.com/zed-industries/zed.git";
136        let github = Gitlab::from_remote_url(remote_url);
137        assert!(github.is_err());
138    }
139
140    #[test]
141    fn test_parse_remote_url_given_ssh_url() {
142        let parsed_remote = Gitlab::public_instance()
143            .parse_remote_url("git@gitlab.com:zed-industries/zed.git")
144            .unwrap();
145
146        assert_eq!(
147            parsed_remote,
148            ParsedGitRemote {
149                owner: "zed-industries".into(),
150                repo: "zed".into(),
151            }
152        );
153    }
154
155    #[test]
156    fn test_parse_remote_url_given_https_url() {
157        let parsed_remote = Gitlab::public_instance()
158            .parse_remote_url("https://gitlab.com/zed-industries/zed.git")
159            .unwrap();
160
161        assert_eq!(
162            parsed_remote,
163            ParsedGitRemote {
164                owner: "zed-industries".into(),
165                repo: "zed".into(),
166            }
167        );
168    }
169
170    #[test]
171    fn test_parse_remote_url_given_self_hosted_ssh_url() {
172        let remote_url = "git@gitlab.my-enterprise.com:zed-industries/zed.git";
173
174        let parsed_remote = Gitlab::from_remote_url(remote_url)
175            .unwrap()
176            .parse_remote_url(remote_url)
177            .unwrap();
178
179        assert_eq!(
180            parsed_remote,
181            ParsedGitRemote {
182                owner: "zed-industries".into(),
183                repo: "zed".into(),
184            }
185        );
186    }
187
188    #[test]
189    fn test_parse_remote_url_given_self_hosted_https_url_with_subgroup() {
190        let remote_url = "https://gitlab.my-enterprise.com/group/subgroup/zed.git";
191        let parsed_remote = Gitlab::from_remote_url(remote_url)
192            .unwrap()
193            .parse_remote_url(remote_url)
194            .unwrap();
195
196        assert_eq!(
197            parsed_remote,
198            ParsedGitRemote {
199                owner: "group/subgroup".into(),
200                repo: "zed".into(),
201            }
202        );
203    }
204
205    #[test]
206    fn test_build_gitlab_permalink() {
207        let permalink = Gitlab::public_instance().build_permalink(
208            ParsedGitRemote {
209                owner: "zed-industries".into(),
210                repo: "zed".into(),
211            },
212            BuildPermalinkParams {
213                sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
214                path: "crates/editor/src/git/permalink.rs",
215                selection: None,
216            },
217        );
218
219        let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs";
220        assert_eq!(permalink.to_string(), expected_url.to_string())
221    }
222
223    #[test]
224    fn test_build_gitlab_permalink_with_single_line_selection() {
225        let permalink = Gitlab::public_instance().build_permalink(
226            ParsedGitRemote {
227                owner: "zed-industries".into(),
228                repo: "zed".into(),
229            },
230            BuildPermalinkParams {
231                sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
232                path: "crates/editor/src/git/permalink.rs",
233                selection: Some(6..6),
234            },
235        );
236
237        let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs#L7";
238        assert_eq!(permalink.to_string(), expected_url.to_string())
239    }
240
241    #[test]
242    fn test_build_gitlab_permalink_with_multi_line_selection() {
243        let permalink = Gitlab::public_instance().build_permalink(
244            ParsedGitRemote {
245                owner: "zed-industries".into(),
246                repo: "zed".into(),
247            },
248            BuildPermalinkParams {
249                sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
250                path: "crates/editor/src/git/permalink.rs",
251                selection: Some(23..47),
252            },
253        );
254
255        let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs#L24-48";
256        assert_eq!(permalink.to_string(), expected_url.to_string())
257    }
258
259    #[test]
260    fn test_build_gitlab_self_hosted_permalink_from_ssh_url() {
261        let gitlab =
262            Gitlab::from_remote_url("git@gitlab.some-enterprise.com:zed-industries/zed.git")
263                .unwrap();
264        let permalink = gitlab.build_permalink(
265            ParsedGitRemote {
266                owner: "zed-industries".into(),
267                repo: "zed".into(),
268            },
269            BuildPermalinkParams {
270                sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
271                path: "crates/editor/src/git/permalink.rs",
272                selection: None,
273            },
274        );
275
276        let expected_url = "https://gitlab.some-enterprise.com/zed-industries/zed/-/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs";
277        assert_eq!(permalink.to_string(), expected_url.to_string())
278    }
279
280    #[test]
281    fn test_build_gitlab_self_hosted_permalink_from_https_url() {
282        let gitlab =
283            Gitlab::from_remote_url("https://gitlab-instance.big-co.com/zed-industries/zed.git")
284                .unwrap();
285        let permalink = gitlab.build_permalink(
286            ParsedGitRemote {
287                owner: "zed-industries".into(),
288                repo: "zed".into(),
289            },
290            BuildPermalinkParams {
291                sha: "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
292                path: "crates/zed/src/main.rs",
293                selection: None,
294            },
295        );
296
297        let expected_url = "https://gitlab-instance.big-co.com/zed-industries/zed/-/blob/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs";
298        assert_eq!(permalink.to_string(), expected_url.to_string())
299    }
300}