Skip to repository content670 lines · 21.0 KB · rust
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T05:36:02.776Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
github.rs
1use std::str::FromStr;
2use std::sync::{Arc, LazyLock};
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 regex::Regex;
10use serde::Deserialize;
11use url::Url;
12use urlencoding::encode;
13
14use git::{
15 BuildCommitPermalinkParams, BuildPermalinkParams, GitHostingProvider, ParsedGitRemote,
16 PullRequest, RemoteUrl,
17};
18
19use crate::get_host_from_git_remote_url;
20
21fn pull_request_number_regex() -> &'static Regex {
22 static PULL_REQUEST_NUMBER_REGEX: LazyLock<Regex> =
23 LazyLock::new(|| Regex::new(r"\(#(\d+)\)$").unwrap());
24 &PULL_REQUEST_NUMBER_REGEX
25}
26
27#[derive(Debug, Deserialize)]
28struct CommitDetails {
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 commit: Commit,
34 author: Option<User>,
35}
36
37#[derive(Debug, Deserialize)]
38struct Commit {
39 #[expect(
40 unused,
41 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"
42 )]
43 author: Author,
44}
45
46#[derive(Debug, Deserialize)]
47struct Author {
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 email: 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 id: u64,
62 pub avatar_url: String,
63}
64
65#[derive(Debug)]
66pub struct Github {
67 name: String,
68 base_url: Url,
69}
70
71fn normalize_author_email(email: &str) -> &str {
72 email.trim_start_matches('<').trim_end_matches('>')
73}
74
75fn build_cdn_avatar_url(email: &str) -> Result<Url> {
76 let email = normalize_author_email(email);
77 Url::parse(&format!(
78 "https://avatars.githubusercontent.com/u/e?email={}&s=128",
79 encode(email)
80 ))
81 .context("failed to construct avatar URL")
82}
83
84fn build_cdn_avatar_url_for_author_email(email: &str) -> Result<Option<Url>> {
85 let email = normalize_author_email(email);
86 if email.ends_with("[bot]@users.noreply.github.com") {
87 return Ok(None);
88 }
89
90 build_cdn_avatar_url(email).map(Some)
91}
92
93impl Github {
94 pub fn new(name: impl Into<String>, base_url: Url) -> Self {
95 Self {
96 name: name.into(),
97 base_url,
98 }
99 }
100
101 pub fn public_instance() -> Self {
102 Self::new("GitHub", Url::parse("https://github.com").unwrap())
103 }
104
105 pub fn from_remote_url(remote_url: &str) -> Result<Self> {
106 let host = get_host_from_git_remote_url(remote_url)?;
107 if host == "github.com" {
108 bail!("the GitHub instance is not self-hosted");
109 }
110
111 // TODO: detecting self hosted instances by checking whether "github" is in the url or not
112 // is not very reliable. See https://github.com/zed-industries/zed/issues/26393 for more
113 // information.
114 if !host.contains("github") {
115 bail!("not a GitHub URL");
116 }
117
118 Ok(Self::new(
119 "GitHub Self-Hosted",
120 Url::parse(&format!("https://{}", host))?,
121 ))
122 }
123
124 async fn fetch_github_commit_author(
125 &self,
126 repo_owner: &str,
127 repo: &str,
128 commit: &str,
129 client: &Arc<dyn HttpClient>,
130 ) -> Result<Option<User>> {
131 let Some(host) = self.base_url.host_str() else {
132 bail!("failed to get host from github base url");
133 };
134 let url = format!("https://api.{host}/repos/{repo_owner}/{repo}/commits/{commit}");
135
136 let mut request = Request::get(&url)
137 .header("Content-Type", "application/json")
138 .follow_redirects(http_client::RedirectPolicy::FollowAll);
139
140 if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
141 request = request.header("Authorization", format!("Bearer {}", github_token));
142 }
143
144 let mut response = client
145 .send(request.body(AsyncBody::default())?)
146 .await
147 .with_context(|| format!("error fetching GitHub commit details at {:?}", url))?;
148
149 let mut body = Vec::new();
150 response.body_mut().read_to_end(&mut body).await?;
151
152 if response.status().is_client_error() {
153 let text = String::from_utf8_lossy(body.as_slice());
154 bail!(
155 "status error {}, response: {text:?}",
156 response.status().as_u16()
157 );
158 }
159
160 let body_str = std::str::from_utf8(&body)?;
161
162 serde_json::from_str::<CommitDetails>(body_str)
163 .map(|commit| commit.author)
164 .context("failed to deserialize GitHub commit details")
165 }
166}
167
168#[async_trait]
169impl GitHostingProvider for Github {
170 fn name(&self) -> String {
171 self.name.clone()
172 }
173
174 fn base_url(&self) -> Url {
175 self.base_url.clone()
176 }
177
178 fn supports_avatars(&self) -> bool {
179 // Avatars are not supported for self-hosted GitHub instances
180 // See tracking issue: https://github.com/zed-industries/zed/issues/11043
181 &self.name == "GitHub"
182 }
183
184 fn format_line_number(&self, line: u32) -> String {
185 format!("L{line}")
186 }
187
188 fn format_line_numbers(&self, start_line: u32, end_line: u32) -> String {
189 format!("L{start_line}-L{end_line}")
190 }
191
192 fn parse_remote_url(&self, url: &str) -> Option<ParsedGitRemote> {
193 let url = RemoteUrl::from_str(url).ok()?;
194
195 let host = url.host_str()?;
196 if host != self.base_url.host_str()? {
197 return None;
198 }
199
200 let mut path_segments = url.path_segments()?;
201 let mut owner = path_segments.next()?;
202 if owner.is_empty() {
203 owner = path_segments.next()?;
204 }
205
206 let repo = path_segments.next()?.trim_end_matches(".git");
207
208 Some(ParsedGitRemote {
209 owner: owner.into(),
210 repo: repo.into(),
211 })
212 }
213
214 fn build_commit_permalink(
215 &self,
216 remote: &ParsedGitRemote,
217 params: BuildCommitPermalinkParams,
218 ) -> Url {
219 let BuildCommitPermalinkParams { sha } = params;
220 let ParsedGitRemote { owner, repo } = remote;
221
222 self.base_url()
223 .join(&format!("{owner}/{repo}/commit/{sha}"))
224 .unwrap()
225 }
226
227 fn build_permalink(&self, remote: ParsedGitRemote, params: BuildPermalinkParams) -> Url {
228 let ParsedGitRemote { owner, repo } = remote;
229 let BuildPermalinkParams {
230 sha,
231 path,
232 selection,
233 } = params;
234
235 let mut permalink = self
236 .base_url()
237 .join(&format!("{owner}/{repo}/blob/{sha}/{path}"))
238 .unwrap();
239 if path.ends_with(".md") {
240 permalink.set_query(Some("plain=1"));
241 }
242 permalink.set_fragment(
243 selection
244 .map(|selection| self.line_fragment(&selection))
245 .as_deref(),
246 );
247 permalink
248 }
249
250 fn build_create_pull_request_url(
251 &self,
252 remote: &ParsedGitRemote,
253 source_branch: &str,
254 ) -> Option<Url> {
255 let ParsedGitRemote { owner, repo } = remote;
256 let encoded_source = encode(source_branch);
257
258 self.base_url()
259 .join(&format!("{owner}/{repo}/pull/new/{encoded_source}"))
260 .ok()
261 }
262
263 fn extract_pull_request(&self, remote: &ParsedGitRemote, message: &str) -> Option<PullRequest> {
264 let line = message.lines().next()?;
265 let capture = pull_request_number_regex().captures(line)?;
266 let number = capture.get(1)?.as_str().parse::<u32>().ok()?;
267
268 let mut url = self.base_url();
269 let path = format!("/{}/{}/pull/{}", remote.owner, remote.repo, number);
270 url.set_path(&path);
271
272 Some(PullRequest { number, url })
273 }
274
275 async fn commit_author_avatar_url(
276 &self,
277 repo_owner: &str,
278 repo: &str,
279 commit: SharedString,
280 author_email: Option<SharedString>,
281 http_client: Arc<dyn HttpClient>,
282 ) -> Result<Option<Url>> {
283 if let Some(email) = author_email
284 && let Some(avatar_url) = build_cdn_avatar_url_for_author_email(&email)?
285 {
286 return Ok(Some(avatar_url));
287 }
288
289 let commit = commit.to_string();
290 let avatar_url = self
291 .fetch_github_commit_author(repo_owner, repo, &commit, &http_client)
292 .await?
293 .map(|author| -> Result<Url, url::ParseError> {
294 let mut url = Url::parse(&author.avatar_url)?;
295 url.set_query(Some("size=128"));
296 Ok(url)
297 })
298 .transpose()?;
299 Ok(avatar_url)
300 }
301}
302
303#[cfg(test)]
304mod tests {
305 use git::repository::repo_path;
306 use indoc::indoc;
307 use pretty_assertions::assert_eq;
308
309 use super::*;
310
311 #[test]
312 fn test_remote_url_with_root_slash() {
313 let remote_url = "git@github.com:/zed-industries/zed";
314 let parsed_remote = Github::public_instance()
315 .parse_remote_url(remote_url)
316 .unwrap();
317
318 assert_eq!(
319 parsed_remote,
320 ParsedGitRemote {
321 owner: "zed-industries".into(),
322 repo: "zed".into(),
323 }
324 );
325 }
326
327 #[test]
328 fn test_invalid_self_hosted_remote_url() {
329 let remote_url = "git@github.com:zed-industries/zed.git";
330 let github = Github::from_remote_url(remote_url);
331 assert!(github.is_err());
332 }
333
334 #[test]
335 fn test_from_remote_url_ssh() {
336 let remote_url = "git@github.my-enterprise.com:zed-industries/zed.git";
337 let github = Github::from_remote_url(remote_url).unwrap();
338
339 assert!(!github.supports_avatars());
340 assert_eq!(github.name, "GitHub Self-Hosted".to_string());
341 assert_eq!(
342 github.base_url,
343 Url::parse("https://github.my-enterprise.com").unwrap()
344 );
345 }
346
347 #[test]
348 fn test_from_remote_url_https() {
349 let remote_url = "https://github.my-enterprise.com/zed-industries/zed.git";
350 let github = Github::from_remote_url(remote_url).unwrap();
351
352 assert!(!github.supports_avatars());
353 assert_eq!(github.name, "GitHub Self-Hosted".to_string());
354 assert_eq!(
355 github.base_url,
356 Url::parse("https://github.my-enterprise.com").unwrap()
357 );
358 }
359
360 #[test]
361 fn test_parse_remote_url_given_self_hosted_ssh_url() {
362 let remote_url = "git@github.my-enterprise.com:zed-industries/zed.git";
363 let parsed_remote = Github::from_remote_url(remote_url)
364 .unwrap()
365 .parse_remote_url(remote_url)
366 .unwrap();
367
368 assert_eq!(
369 parsed_remote,
370 ParsedGitRemote {
371 owner: "zed-industries".into(),
372 repo: "zed".into(),
373 }
374 );
375 }
376
377 #[test]
378 fn test_parse_remote_url_given_self_hosted_https_url_with_subgroup() {
379 let remote_url = "https://github.my-enterprise.com/zed-industries/zed.git";
380 let parsed_remote = Github::from_remote_url(remote_url)
381 .unwrap()
382 .parse_remote_url(remote_url)
383 .unwrap();
384
385 assert_eq!(
386 parsed_remote,
387 ParsedGitRemote {
388 owner: "zed-industries".into(),
389 repo: "zed".into(),
390 }
391 );
392 }
393
394 #[test]
395 fn test_parse_remote_url_given_ssh_url() {
396 let parsed_remote = Github::public_instance()
397 .parse_remote_url("git@github.com:zed-industries/zed.git")
398 .unwrap();
399
400 assert_eq!(
401 parsed_remote,
402 ParsedGitRemote {
403 owner: "zed-industries".into(),
404 repo: "zed".into(),
405 }
406 );
407 }
408
409 #[test]
410 fn test_parse_remote_url_given_https_url() {
411 let parsed_remote = Github::public_instance()
412 .parse_remote_url("https://github.com/zed-industries/zed.git")
413 .unwrap();
414
415 assert_eq!(
416 parsed_remote,
417 ParsedGitRemote {
418 owner: "zed-industries".into(),
419 repo: "zed".into(),
420 }
421 );
422 }
423
424 #[test]
425 fn test_parse_remote_url_given_https_url_with_username() {
426 let parsed_remote = Github::public_instance()
427 .parse_remote_url("https://jlannister@github.com/some-org/some-repo.git")
428 .unwrap();
429
430 assert_eq!(
431 parsed_remote,
432 ParsedGitRemote {
433 owner: "some-org".into(),
434 repo: "some-repo".into(),
435 }
436 );
437 }
438
439 #[test]
440 fn test_build_github_permalink_from_ssh_url() {
441 let remote = ParsedGitRemote {
442 owner: "zed-industries".into(),
443 repo: "zed".into(),
444 };
445 let permalink = Github::public_instance().build_permalink(
446 remote,
447 BuildPermalinkParams::new(
448 "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
449 &repo_path("crates/editor/src/git/permalink.rs"),
450 None,
451 ),
452 );
453
454 let expected_url = "https://github.com/zed-industries/zed/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs";
455 assert_eq!(permalink.to_string(), expected_url.to_string())
456 }
457
458 #[test]
459 fn test_build_github_permalink() {
460 let permalink = Github::public_instance().build_permalink(
461 ParsedGitRemote {
462 owner: "zed-industries".into(),
463 repo: "zed".into(),
464 },
465 BuildPermalinkParams::new(
466 "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
467 &repo_path("crates/zed/src/main.rs"),
468 None,
469 ),
470 );
471
472 let expected_url = "https://github.com/zed-industries/zed/blob/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs";
473 assert_eq!(permalink.to_string(), expected_url.to_string())
474 }
475
476 #[test]
477 fn test_build_github_permalink_with_single_line_selection() {
478 let permalink = Github::public_instance().build_permalink(
479 ParsedGitRemote {
480 owner: "zed-industries".into(),
481 repo: "zed".into(),
482 },
483 BuildPermalinkParams::new(
484 "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
485 &repo_path("crates/editor/src/git/permalink.rs"),
486 Some(6..6),
487 ),
488 );
489
490 let expected_url = "https://github.com/zed-industries/zed/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs#L7";
491 assert_eq!(permalink.to_string(), expected_url.to_string())
492 }
493
494 #[test]
495 fn test_build_github_permalink_with_multi_line_selection() {
496 let permalink = Github::public_instance().build_permalink(
497 ParsedGitRemote {
498 owner: "zed-industries".into(),
499 repo: "zed".into(),
500 },
501 BuildPermalinkParams::new(
502 "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
503 &repo_path("crates/editor/src/git/permalink.rs"),
504 Some(23..47),
505 ),
506 );
507
508 let expected_url = "https://github.com/zed-industries/zed/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs#L24-L48";
509 assert_eq!(permalink.to_string(), expected_url.to_string())
510 }
511
512 #[test]
513 fn test_build_github_create_pr_url() {
514 let remote = ParsedGitRemote {
515 owner: "zed-industries".into(),
516 repo: "zed".into(),
517 };
518
519 let provider = Github::public_instance();
520
521 let url = provider
522 .build_create_pull_request_url(&remote, "feature/something cool")
523 .expect("url should be constructed");
524
525 assert_eq!(
526 url.as_str(),
527 "https://github.com/zed-industries/zed/pull/new/feature%2Fsomething%20cool"
528 );
529 }
530
531 #[test]
532 fn test_github_pull_requests() {
533 let remote = ParsedGitRemote {
534 owner: "zed-industries".into(),
535 repo: "zed".into(),
536 };
537
538 let github = Github::public_instance();
539 let message = "This does not contain a pull request";
540 assert!(github.extract_pull_request(&remote, message).is_none());
541
542 // Pull request number at end of first line
543 let message = indoc! {r#"
544 project panel: do not expand collapsed worktrees on "collapse all entries" (#10687)
545
546 Fixes #10597
547
548 Release Notes:
549
550 - Fixed "project panel: collapse all entries" expanding collapsed worktrees.
551 "#
552 };
553
554 assert_eq!(
555 github
556 .extract_pull_request(&remote, message)
557 .unwrap()
558 .url
559 .as_str(),
560 "https://github.com/zed-industries/zed/pull/10687"
561 );
562
563 // Pull request number in middle of line, which we want to ignore
564 let message = indoc! {r#"
565 Follow-up to #10687 to fix problems
566
567 See the original PR, this is a fix.
568 "#
569 };
570 assert_eq!(github.extract_pull_request(&remote, message), None);
571 }
572
573 /// Regression test for issue #39875
574 #[test]
575 fn test_git_permalink_url_escaping() {
576 let permalink = Github::public_instance().build_permalink(
577 ParsedGitRemote {
578 owner: "zed-industries".into(),
579 repo: "nonexistent".into(),
580 },
581 BuildPermalinkParams::new(
582 "3ef1539900037dd3601be7149b2b39ed6d0ce3db",
583 &repo_path("app/blog/[slug]/page.tsx"),
584 Some(7..7),
585 ),
586 );
587
588 let expected_url = "https://github.com/zed-industries/nonexistent/blob/3ef1539900037dd3601be7149b2b39ed6d0ce3db/app/blog/%5Bslug%5D/page.tsx#L8";
589 assert_eq!(permalink.to_string(), expected_url.to_string())
590 }
591
592 #[test]
593 fn test_build_create_pull_request_url() {
594 let remote = ParsedGitRemote {
595 owner: "zed-industries".into(),
596 repo: "zed".into(),
597 };
598
599 let github = Github::public_instance();
600 let url = github
601 .build_create_pull_request_url(&remote, "feature/new-feature")
602 .unwrap();
603
604 assert_eq!(
605 url.as_str(),
606 "https://github.com/zed-industries/zed/pull/new/feature%2Fnew-feature"
607 );
608
609 let base_url = Url::parse("https://github.zed.com").unwrap();
610 let github = Github::new("GitHub Self-Hosted", base_url);
611 let url = github
612 .build_create_pull_request_url(&remote, "feature/new-feature")
613 .expect("should be able to build pull request url");
614
615 assert_eq!(
616 url.as_str(),
617 "https://github.zed.com/zed-industries/zed/pull/new/feature%2Fnew-feature"
618 );
619 }
620
621 #[test]
622 fn test_build_cdn_avatar_url_simple_email() {
623 let url = build_cdn_avatar_url("user@example.com").unwrap();
624 assert_eq!(
625 url.as_str(),
626 "https://avatars.githubusercontent.com/u/e?email=user%40example.com&s=128"
627 );
628 }
629
630 #[test]
631 fn test_build_cdn_avatar_url_with_angle_brackets() {
632 let url = build_cdn_avatar_url("<user@example.com>").unwrap();
633 assert_eq!(
634 url.as_str(),
635 "https://avatars.githubusercontent.com/u/e?email=user%40example.com&s=128"
636 );
637 }
638
639 #[test]
640 fn test_build_cdn_avatar_url_with_special_chars() {
641 let url = build_cdn_avatar_url("user+tag@example.com").unwrap();
642 assert_eq!(
643 url.as_str(),
644 "https://avatars.githubusercontent.com/u/e?email=user%2Btag%40example.com&s=128"
645 );
646 }
647
648 #[test]
649 fn test_build_cdn_avatar_url_for_author_email_skips_bot_noreply_emails() {
650 for email in [
651 "41898282+github-actions[bot]@users.noreply.github.com",
652 "<41898282+github-actions[bot]@users.noreply.github.com>",
653 ] {
654 assert_eq!(build_cdn_avatar_url_for_author_email(email).unwrap(), None);
655 }
656 }
657
658 #[test]
659 fn test_build_cdn_avatar_url_for_author_email_uses_user_noreply_emails() {
660 let url = build_cdn_avatar_url_for_author_email("12345+octocat@users.noreply.github.com")
661 .unwrap()
662 .unwrap();
663
664 assert_eq!(
665 url.as_str(),
666 "https://avatars.githubusercontent.com/u/e?email=12345%2Boctocat%40users.noreply.github.com&s=128"
667 );
668 }
669}
670