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
181pub type ForgeFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
183
184#[derive(Clone, Debug, Eq, PartialEq)]
186pub struct ForgeRemote {
187 pub command_working_directory: Option<PathBuf>,
190 pub forge_kind: ForgeKind,
192 pub host: String,
197 pub namespace: String,
199 pub project: String,
201 pub repo_url: String,
203 pub web_url: String,
205}
206
207impl ForgeRemote {
208 #[must_use]
211 pub fn with_command_working_directory(mut self, working_directory: PathBuf) -> Self {
212 self.command_working_directory = Some(working_directory);
213
214 self
215 }
216
217 pub fn project_path(&self) -> String {
219 format!("{}/{}", self.namespace, self.project)
220 }
221
222 pub fn review_request_creation_url(
230 &self,
231 source_branch: &str,
232 target_branch: &str,
233 ) -> Result<String, ReviewRequestError> {
234 match self.forge_kind {
235 ForgeKind::GitHub => {
236 github_review_request_creation_url(self, source_branch, target_branch)
237 }
238 ForgeKind::GitLab => {
239 gitlab_review_request_creation_url(self, source_branch, target_branch)
240 }
241 }
242 }
243}
244
245#[derive(Clone, Debug, Eq, PartialEq)]
247pub struct ReviewComment {
248 pub author: String,
250 pub body: String,
252}
253
254#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
256pub enum ReviewCommentAnchorSide {
257 File,
259 New,
261 Old,
263}
264
265#[derive(Clone, Debug, Eq, PartialEq)]
271pub struct ReviewCommentThread {
272 pub anchor_side: ReviewCommentAnchorSide,
274 pub comments: Vec<ReviewComment>,
276 pub is_outdated: Option<bool>,
279 pub is_resolved: bool,
281 pub line: Option<u32>,
283 pub path: String,
285 pub start_line: Option<u32>,
287}
288
289#[derive(Clone, Debug, Default, Eq, PartialEq)]
296pub struct ReviewCommentSnapshot {
297 pub pr_level_comments: Vec<ReviewComment>,
300 pub threads: Vec<ReviewCommentThread>,
302}
303
304#[derive(Clone, Debug, Eq, PartialEq)]
306pub struct CreateReviewRequestInput {
307 pub body: Option<String>,
309 pub source_branch: String,
311 pub target_branch: String,
313 pub title: String,
315}
316
317#[derive(Clone, Debug, Eq, PartialEq)]
319pub enum ReviewRequestError {
320 CliNotInstalled { forge_kind: ForgeKind },
322 AuthenticationRequired {
324 forge_kind: ForgeKind,
326 host: String,
328 detail: Option<String>,
330 },
331 HostResolutionFailed { forge_kind: ForgeKind, host: String },
333 UnsupportedRemote { repo_url: String },
335 OperationFailed {
337 forge_kind: ForgeKind,
338 message: String,
339 },
340}
341
342impl ReviewRequestError {
343 pub fn detail_message(&self) -> String {
345 match self {
346 Self::CliNotInstalled { forge_kind } => format!(
347 "{} review requests require the `{}` CLI.\nInstall `{}` and run `{}`, then retry.",
348 forge_kind.display_name(),
349 forge_kind.cli_name(),
350 forge_kind.cli_name(),
351 forge_kind.auth_login_command(),
352 ),
353 Self::AuthenticationRequired {
354 forge_kind,
355 host,
356 detail,
357 } => authentication_required_message(*forge_kind, host, detail.as_deref()),
358 Self::HostResolutionFailed { forge_kind, host } => format!(
359 "{} review requests could not reach `{host}`.\nCheck the repository remote host \
360 and your network or DNS setup, then retry.",
361 forge_kind.display_name(),
362 ),
363 Self::UnsupportedRemote { repo_url } => format!(
364 "Review requests are only supported for GitHub and GitLab remotes.\nThis \
365 repository remote is not supported: `{repo_url}`."
366 ),
367 Self::OperationFailed {
368 forge_kind,
369 message,
370 } => format!(
371 "{} review-request operation failed: {message}",
372 forge_kind.display_name()
373 ),
374 }
375 }
376}
377
378fn authentication_required_message(
381 forge_kind: ForgeKind,
382 host: &str,
383 detail: Option<&str>,
384) -> String {
385 let mut message = format!(
386 "{} review requests require local CLI authentication for `{host}`.\nRun `{}` and retry.",
387 forge_kind.display_name(),
388 forge_kind.auth_login_command(),
389 );
390
391 if let Some(detail) = non_empty_detail(detail) {
392 let _ = write!(
394 message,
395 "\n\nOriginal `{}` error:\n```text\n{detail}",
396 forge_kind.cli_name(),
397 );
398 if !detail.ends_with('\n') {
399 message.push('\n');
400 }
401 message.push_str("```");
402 }
403
404 message
405}
406
407fn non_empty_detail(detail: Option<&str>) -> Option<&str> {
409 detail.and_then(|detail| {
410 let trimmed_detail = detail.trim();
411 (!trimmed_detail.is_empty()).then_some(trimmed_detail)
412 })
413}
414
415fn github_review_request_creation_url(
417 remote: &ForgeRemote,
418 source_branch: &str,
419 target_branch: &str,
420) -> Result<String, ReviewRequestError> {
421 let mut url = parsed_remote_web_url(remote)?;
422 let compare_target = if target_branch.trim().is_empty() {
423 source_branch.to_string()
424 } else {
425 format!("{target_branch}...{source_branch}")
426 };
427
428 {
429 let mut path_segments = url
430 .path_segments_mut()
431 .map_err(|()| invalid_web_url_error(remote))?;
432 path_segments.pop_if_empty();
433 path_segments.push("compare");
434 path_segments.push(&compare_target);
435 }
436
437 url.query_pairs_mut().append_pair("expand", "1");
438
439 Ok(url.into())
440}
441
442fn gitlab_review_request_creation_url(
444 remote: &ForgeRemote,
445 source_branch: &str,
446 target_branch: &str,
447) -> Result<String, ReviewRequestError> {
448 let mut url = parsed_remote_web_url(remote)?;
449
450 {
451 let mut path_segments = url
452 .path_segments_mut()
453 .map_err(|()| invalid_web_url_error(remote))?;
454 path_segments.pop_if_empty();
455 path_segments.push("-");
456 path_segments.push("merge_requests");
457 path_segments.push("new");
458 }
459
460 url.query_pairs_mut()
461 .append_pair("merge_request[source_branch]", source_branch)
462 .append_pair("merge_request[target_branch]", target_branch);
463
464 Ok(url.into())
465}
466
467fn parsed_remote_web_url(remote: &ForgeRemote) -> Result<Url, ReviewRequestError> {
469 Url::parse(&remote.web_url).map_err(|_| invalid_web_url_error(remote))
470}
471
472fn invalid_web_url_error(remote: &ForgeRemote) -> ReviewRequestError {
474 ReviewRequestError::OperationFailed {
475 forge_kind: remote.forge_kind,
476 message: format!(
477 "repository remote is missing a valid web URL: `{}`",
478 remote.web_url
479 ),
480 }
481}
482
483#[cfg(test)]
484mod tests {
485 use super::*;
486
487 #[test]
488 fn authentication_required_message_includes_original_cli_error_detail() {
489 let error = ReviewRequestError::AuthenticationRequired {
491 detail: Some("HTTP 401 Unauthorized. Run `gh auth login`.".to_string()),
492 forge_kind: ForgeKind::GitHub,
493 host: "github.com".to_string(),
494 };
495
496 let message = error.detail_message();
498
499 assert!(message.contains("GitHub review requests require local CLI authentication"));
501 assert!(message.contains("Run `gh auth login` and retry."));
502 assert!(message.contains("Original `gh` error:"));
503 assert!(message.contains("HTTP 401 Unauthorized. Run `gh auth login`."));
504 assert!(message.contains("```text"));
505 }
506
507 #[test]
508 fn authentication_required_message_omits_empty_original_cli_error_detail() {
509 let error = ReviewRequestError::AuthenticationRequired {
511 detail: Some(" \n".to_string()),
512 forge_kind: ForgeKind::GitHub,
513 host: "github.com".to_string(),
514 };
515
516 let message = error.detail_message();
518
519 assert!(message.contains("Run `gh auth login` and retry."));
521 assert!(!message.contains("Original `gh` error:"));
522 }
523
524 #[test]
525 fn review_request_creation_url_returns_github_compare_link() {
526 let remote = ForgeRemote {
528 command_working_directory: None,
529 forge_kind: ForgeKind::GitHub,
530 host: "github.com".to_string(),
531 namespace: "agentty-xyz".to_string(),
532 project: "agentty".to_string(),
533 repo_url: "git@github.com:agentty-xyz/agentty.git".to_string(),
534 web_url: "https://github.com/agentty-xyz/agentty".to_string(),
535 };
536
537 let url = remote
539 .review_request_creation_url("review/custom-branch", "main")
540 .expect("github compare URL should be created");
541
542 assert_eq!(
544 url,
545 "https://github.com/agentty-xyz/agentty/compare/main...review%2Fcustom-branch?expand=1"
546 );
547 }
548
549 #[test]
550 fn review_request_creation_url_rejects_invalid_web_url() {
551 let remote = ForgeRemote {
553 command_working_directory: None,
554 forge_kind: ForgeKind::GitHub,
555 host: "github.com".to_string(),
556 namespace: "agentty-xyz".to_string(),
557 project: "agentty".to_string(),
558 repo_url: "git@github.com:agentty-xyz/agentty.git".to_string(),
559 web_url: "not a url".to_string(),
560 };
561
562 let error = remote
564 .review_request_creation_url("review/custom-branch", "main")
565 .expect_err("invalid web URL should be rejected");
566
567 assert_eq!(
569 error,
570 ReviewRequestError::OperationFailed {
571 forge_kind: ForgeKind::GitHub,
572 message: "repository remote is missing a valid web URL: `not a url`".to_string(),
573 }
574 );
575 }
576
577 #[test]
578 fn forge_kind_from_str_gitlab() {
579 let raw_forge_kind = "GitLab";
581
582 let forge_kind = raw_forge_kind
584 .parse::<ForgeKind>()
585 .expect("gitlab forge kind should parse");
586
587 assert_eq!(forge_kind, ForgeKind::GitLab);
589 assert_eq!(forge_kind.cli_name(), "glab");
590 assert_eq!(forge_kind.review_request_name(), "merge request");
591 assert_eq!(forge_kind.review_request_short_name(), "MR");
592 }
593
594 #[test]
595 fn supports_review_comments_preview_returns_true_for_supported_forges() {
596 assert!(ForgeKind::GitHub.supports_review_comments_preview());
598 assert!(ForgeKind::GitLab.supports_review_comments_preview());
599 }
600
601 #[test]
602 fn review_request_creation_url_returns_gitlab_merge_request_link() {
603 let remote = ForgeRemote {
605 command_working_directory: None,
606 forge_kind: ForgeKind::GitLab,
607 host: "gitlab.com".to_string(),
608 namespace: "agentty-xyz".to_string(),
609 project: "agentty".to_string(),
610 repo_url: "git@gitlab.com:agentty-xyz/agentty.git".to_string(),
611 web_url: "https://gitlab.com/agentty-xyz/agentty".to_string(),
612 };
613
614 let url = remote
616 .review_request_creation_url("review/custom-branch", "main")
617 .expect("gitlab merge-request URL should be created");
618
619 assert_eq!(
621 url,
622 "https://gitlab.com/agentty-xyz/agentty/-/merge_requests/new?merge_request%5Bsource_branch%5D=review%2Fcustom-branch&merge_request%5Btarget_branch%5D=main"
623 );
624 }
625}