1use std::fmt;
4use std::fmt::Write as _;
5use std::future::Future;
6use std::path::PathBuf;
7use std::pin::Pin;
8use std::str::FromStr;
9
10use url::Url;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum ForgeKind {
15 GitHub,
17 GitLab,
19}
20
21impl ForgeKind {
22 pub fn display_name(self) -> &'static str {
24 match self {
25 Self::GitHub => "GitHub",
26 Self::GitLab => "GitLab",
27 }
28 }
29
30 pub fn cli_name(self) -> &'static str {
32 match self {
33 Self::GitHub => "gh",
34 Self::GitLab => "glab",
35 }
36 }
37
38 pub fn auth_login_command(self) -> &'static str {
40 match self {
41 Self::GitHub => "gh auth login",
42 Self::GitLab => "glab auth login",
43 }
44 }
45
46 pub fn as_str(self) -> &'static str {
48 match self {
49 Self::GitHub => "GitHub",
50 Self::GitLab => "GitLab",
51 }
52 }
53
54 pub fn review_request_name(self) -> &'static str {
56 match self {
57 Self::GitHub => "pull request",
58 Self::GitLab => "merge request",
59 }
60 }
61
62 pub fn review_request_display_name(self) -> String {
64 format!("{} {}", self.display_name(), self.review_request_name())
65 }
66
67 pub fn review_request_short_name(self) -> &'static str {
69 match self {
70 Self::GitHub => "PR",
71 Self::GitLab => "MR",
72 }
73 }
74
75 pub fn supports_review_comments_preview(self) -> bool {
81 match self {
82 Self::GitHub | Self::GitLab => true,
83 }
84 }
85}
86
87pub fn is_gitlab_host(host: &str) -> bool {
89 host == "gitlab.com"
90 || host.ends_with(".gitlab.com")
91 || host.starts_with("gitlab.")
92 || host.contains(".gitlab.")
93}
94
95impl fmt::Display for ForgeKind {
96 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97 formatter.write_str(self.as_str())
98 }
99}
100
101impl FromStr for ForgeKind {
102 type Err = String;
103
104 fn from_str(value: &str) -> Result<Self, Self::Err> {
105 match value {
106 "GitHub" => Ok(Self::GitHub),
107 "GitLab" => Ok(Self::GitLab),
108 _ => Err(format!("Unknown review-request forge: {value}")),
109 }
110 }
111}
112
113#[derive(Clone, Copy, Debug, Eq, PartialEq)]
115pub enum ReviewRequestState {
116 Open,
118 Merged,
120 Closed,
122}
123
124impl ReviewRequestState {
125 pub fn as_str(self) -> &'static str {
127 match self {
128 Self::Open => "Open",
129 Self::Merged => "Merged",
130 Self::Closed => "Closed",
131 }
132 }
133}
134
135impl fmt::Display for ReviewRequestState {
136 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137 formatter.write_str(self.as_str())
138 }
139}
140
141impl FromStr for ReviewRequestState {
142 type Err = String;
143
144 fn from_str(value: &str) -> Result<Self, Self::Err> {
145 match value {
146 "Open" => Ok(Self::Open),
147 "Merged" => Ok(Self::Merged),
148 "Closed" => Ok(Self::Closed),
149 _ => Err(format!("Unknown review-request state: {value}")),
150 }
151 }
152}
153
154#[derive(Clone, Debug, Eq, PartialEq)]
162pub struct ReviewRequestSummary {
163 pub display_id: String,
165 pub forge_kind: ForgeKind,
167 pub source_branch: String,
169 pub state: ReviewRequestState,
171 pub status_summary: Option<String>,
173 pub target_branch: String,
175 pub title: String,
177 pub web_url: String,
179}
180
181#[derive(Clone, Copy, Debug, Eq, PartialEq)]
184pub enum RequestedReviewAudience {
185 Personal,
187 Group,
189}
190
191#[derive(Clone, Debug, Eq, PartialEq)]
194pub struct RequestedReview {
195 pub audience: RequestedReviewAudience,
198 pub display_id: String,
200 pub forge_kind: ForgeKind,
202 pub repository: String,
204 pub status_summary: Option<String>,
206 pub title: String,
208 pub updated_at: Option<String>,
210 pub web_url: String,
212}
213
214pub type ForgeFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
216
217#[derive(Clone, Debug, Eq, PartialEq)]
219pub struct ForgeRemote {
220 pub command_working_directory: Option<PathBuf>,
223 pub forge_kind: ForgeKind,
225 pub host: String,
230 pub namespace: String,
232 pub project: String,
234 pub repo_url: String,
236 pub web_url: String,
238}
239
240impl ForgeRemote {
241 #[must_use]
244 pub fn with_command_working_directory(mut self, working_directory: PathBuf) -> Self {
245 self.command_working_directory = Some(working_directory);
246
247 self
248 }
249
250 pub fn project_path(&self) -> String {
252 format!("{}/{}", self.namespace, self.project)
253 }
254
255 pub fn review_request_creation_url(
263 &self,
264 source_branch: &str,
265 target_branch: &str,
266 ) -> Result<String, ReviewRequestError> {
267 match self.forge_kind {
268 ForgeKind::GitHub => {
269 github_review_request_creation_url(self, source_branch, target_branch)
270 }
271 ForgeKind::GitLab => {
272 gitlab_review_request_creation_url(self, source_branch, target_branch)
273 }
274 }
275 }
276}
277
278#[derive(Clone, Debug, Eq, PartialEq)]
280pub struct ReviewComment {
281 pub author: String,
283 pub body: String,
285}
286
287#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
289pub enum ReviewCommentAnchorSide {
290 File,
292 New,
294 Old,
296}
297
298#[derive(Clone, Debug, Eq, PartialEq)]
304pub struct ReviewCommentThread {
305 pub anchor_side: ReviewCommentAnchorSide,
307 pub comments: Vec<ReviewComment>,
309 pub is_outdated: Option<bool>,
312 pub is_resolved: bool,
314 pub line: Option<u32>,
316 pub path: String,
318 pub start_line: Option<u32>,
320}
321
322#[derive(Clone, Debug, Default, Eq, PartialEq)]
329pub struct ReviewCommentSnapshot {
330 pub pr_level_comments: Vec<ReviewComment>,
333 pub threads: Vec<ReviewCommentThread>,
335}
336
337#[derive(Clone, Debug, Eq, PartialEq)]
339pub struct CreateReviewRequestInput {
340 pub body: Option<String>,
342 pub source_branch: String,
344 pub target_branch: String,
346 pub title: String,
348}
349
350#[derive(Clone, Debug, Eq, PartialEq)]
352pub enum ReviewRequestError {
353 CliNotInstalled { forge_kind: ForgeKind },
355 AuthenticationRequired {
357 forge_kind: ForgeKind,
359 host: String,
361 detail: Option<String>,
363 },
364 HostResolutionFailed { forge_kind: ForgeKind, host: String },
366 UnsupportedRemote { repo_url: String },
368 OperationFailed {
370 forge_kind: ForgeKind,
371 message: String,
372 },
373}
374
375impl ReviewRequestError {
376 pub fn detail_message(&self) -> String {
378 match self {
379 Self::CliNotInstalled { forge_kind } => format!(
380 "{} review requests require the `{}` CLI.\nInstall `{}` and run `{}`, then retry.",
381 forge_kind.display_name(),
382 forge_kind.cli_name(),
383 forge_kind.cli_name(),
384 forge_kind.auth_login_command(),
385 ),
386 Self::AuthenticationRequired {
387 forge_kind,
388 host,
389 detail,
390 } => authentication_required_message(*forge_kind, host, detail.as_deref()),
391 Self::HostResolutionFailed { forge_kind, host } => format!(
392 "{} review requests could not reach `{host}`.\nCheck the repository remote host \
393 and your network or DNS setup, then retry.",
394 forge_kind.display_name(),
395 ),
396 Self::UnsupportedRemote { repo_url } => format!(
397 "Review requests are only supported for GitHub and GitLab remotes.\nThis \
398 repository remote is not supported: `{repo_url}`."
399 ),
400 Self::OperationFailed {
401 forge_kind,
402 message,
403 } => format!(
404 "{} review-request operation failed: {message}",
405 forge_kind.display_name()
406 ),
407 }
408 }
409}
410
411fn authentication_required_message(
414 forge_kind: ForgeKind,
415 host: &str,
416 detail: Option<&str>,
417) -> String {
418 let mut message = format!(
419 "{} review requests require local CLI authentication for `{host}`.\nRun `{}` and retry.",
420 forge_kind.display_name(),
421 forge_kind.auth_login_command(),
422 );
423
424 if let Some(detail) = non_empty_detail(detail) {
425 let _ = write!(
427 message,
428 "\n\nOriginal `{}` error:\n```text\n{detail}",
429 forge_kind.cli_name(),
430 );
431 if !detail.ends_with('\n') {
432 message.push('\n');
433 }
434 message.push_str("```");
435 }
436
437 message
438}
439
440fn non_empty_detail(detail: Option<&str>) -> Option<&str> {
442 detail.and_then(|detail| {
443 let trimmed_detail = detail.trim();
444 (!trimmed_detail.is_empty()).then_some(trimmed_detail)
445 })
446}
447
448fn github_review_request_creation_url(
450 remote: &ForgeRemote,
451 source_branch: &str,
452 target_branch: &str,
453) -> Result<String, ReviewRequestError> {
454 let mut url = parsed_remote_web_url(remote)?;
455 let compare_target = if target_branch.trim().is_empty() {
456 source_branch.to_string()
457 } else {
458 format!("{target_branch}...{source_branch}")
459 };
460
461 {
462 let mut path_segments = url
463 .path_segments_mut()
464 .map_err(|()| invalid_web_url_error(remote))?;
465 path_segments.pop_if_empty();
466 path_segments.push("compare");
467 path_segments.push(&compare_target);
468 }
469
470 url.query_pairs_mut().append_pair("expand", "1");
471
472 Ok(url.into())
473}
474
475fn gitlab_review_request_creation_url(
477 remote: &ForgeRemote,
478 source_branch: &str,
479 target_branch: &str,
480) -> Result<String, ReviewRequestError> {
481 let mut url = parsed_remote_web_url(remote)?;
482
483 {
484 let mut path_segments = url
485 .path_segments_mut()
486 .map_err(|()| invalid_web_url_error(remote))?;
487 path_segments.pop_if_empty();
488 path_segments.push("-");
489 path_segments.push("merge_requests");
490 path_segments.push("new");
491 }
492
493 url.query_pairs_mut()
494 .append_pair("merge_request[source_branch]", source_branch)
495 .append_pair("merge_request[target_branch]", target_branch);
496
497 Ok(url.into())
498}
499
500fn parsed_remote_web_url(remote: &ForgeRemote) -> Result<Url, ReviewRequestError> {
502 Url::parse(&remote.web_url).map_err(|_| invalid_web_url_error(remote))
503}
504
505fn invalid_web_url_error(remote: &ForgeRemote) -> ReviewRequestError {
507 ReviewRequestError::OperationFailed {
508 forge_kind: remote.forge_kind,
509 message: format!(
510 "repository remote is missing a valid web URL: `{}`",
511 remote.web_url
512 ),
513 }
514}
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519
520 #[test]
521 fn authentication_required_message_includes_original_cli_error_detail() {
522 let error = ReviewRequestError::AuthenticationRequired {
524 detail: Some("HTTP 401 Unauthorized. Run `gh auth login`.".to_string()),
525 forge_kind: ForgeKind::GitHub,
526 host: "github.com".to_string(),
527 };
528
529 let message = error.detail_message();
531
532 assert!(message.contains("GitHub review requests require local CLI authentication"));
534 assert!(message.contains("Run `gh auth login` and retry."));
535 assert!(message.contains("Original `gh` error:"));
536 assert!(message.contains("HTTP 401 Unauthorized. Run `gh auth login`."));
537 assert!(message.contains("```text"));
538 }
539
540 #[test]
541 fn authentication_required_message_omits_empty_original_cli_error_detail() {
542 let error = ReviewRequestError::AuthenticationRequired {
544 detail: Some(" \n".to_string()),
545 forge_kind: ForgeKind::GitHub,
546 host: "github.com".to_string(),
547 };
548
549 let message = error.detail_message();
551
552 assert!(message.contains("Run `gh auth login` and retry."));
554 assert!(!message.contains("Original `gh` error:"));
555 }
556
557 #[test]
558 fn review_request_creation_url_returns_github_compare_link() {
559 let remote = ForgeRemote {
561 command_working_directory: None,
562 forge_kind: ForgeKind::GitHub,
563 host: "github.com".to_string(),
564 namespace: "agentty-xyz".to_string(),
565 project: "agentty".to_string(),
566 repo_url: "git@github.com:agentty-xyz/agentty.git".to_string(),
567 web_url: "https://github.com/agentty-xyz/agentty".to_string(),
568 };
569
570 let url = remote
572 .review_request_creation_url("review/custom-branch", "main")
573 .expect("github compare URL should be created");
574
575 assert_eq!(
577 url,
578 "https://github.com/agentty-xyz/agentty/compare/main...review%2Fcustom-branch?expand=1"
579 );
580 }
581
582 #[test]
583 fn review_request_creation_url_rejects_invalid_web_url() {
584 let remote = ForgeRemote {
586 command_working_directory: None,
587 forge_kind: ForgeKind::GitHub,
588 host: "github.com".to_string(),
589 namespace: "agentty-xyz".to_string(),
590 project: "agentty".to_string(),
591 repo_url: "git@github.com:agentty-xyz/agentty.git".to_string(),
592 web_url: "not a url".to_string(),
593 };
594
595 let error = remote
597 .review_request_creation_url("review/custom-branch", "main")
598 .expect_err("invalid web URL should be rejected");
599
600 assert_eq!(
602 error,
603 ReviewRequestError::OperationFailed {
604 forge_kind: ForgeKind::GitHub,
605 message: "repository remote is missing a valid web URL: `not a url`".to_string(),
606 }
607 );
608 }
609
610 #[test]
611 fn forge_kind_from_str_gitlab() {
612 let raw_forge_kind = "GitLab";
614
615 let forge_kind = raw_forge_kind
617 .parse::<ForgeKind>()
618 .expect("gitlab forge kind should parse");
619
620 assert_eq!(forge_kind, ForgeKind::GitLab);
622 assert_eq!(forge_kind.cli_name(), "glab");
623 assert_eq!(forge_kind.review_request_name(), "merge request");
624 assert_eq!(forge_kind.review_request_short_name(), "MR");
625 }
626
627 #[test]
628 fn supports_review_comments_preview_returns_true_for_supported_forges() {
629 assert!(ForgeKind::GitHub.supports_review_comments_preview());
631 assert!(ForgeKind::GitLab.supports_review_comments_preview());
632 }
633
634 #[test]
635 fn review_request_creation_url_returns_gitlab_merge_request_link() {
636 let remote = ForgeRemote {
638 command_working_directory: None,
639 forge_kind: ForgeKind::GitLab,
640 host: "gitlab.com".to_string(),
641 namespace: "agentty-xyz".to_string(),
642 project: "agentty".to_string(),
643 repo_url: "git@gitlab.com:agentty-xyz/agentty.git".to_string(),
644 web_url: "https://gitlab.com/agentty-xyz/agentty".to_string(),
645 };
646
647 let url = remote
649 .review_request_creation_url("review/custom-branch", "main")
650 .expect("gitlab merge-request URL should be created");
651
652 assert_eq!(
654 url,
655 "https://gitlab.com/agentty-xyz/agentty/-/merge_requests/new?merge_request%5Bsource_branch%5D=review%2Fcustom-branch&merge_request%5Btarget_branch%5D=main"
656 );
657 }
658}