1use anyhow::{Context, Result};
2use clap::{Subcommand, ValueEnum};
3use colored::Colorize;
4use tabled::{Table, Tabled};
5
6use super::parse_repo;
7use crate::api::BitbucketClient;
8use crate::cli::pagination::effective_limit;
9use crate::models::{
10 BranchInfo, CreatePullRequestRequest, MergePullRequestRequest, MergeStrategy, PrActivity,
11 PullRequest, PullRequestBranchRef, PullRequestComment, PullRequestState,
12 UpdatePullRequestRequest, UserRef,
13};
14
15#[derive(Subcommand)]
16pub enum PrCommands {
17 List {
19 repo: String,
21
22 #[arg(short, long, value_enum)]
24 state: Vec<PrState>,
25
26 #[arg(short = 'q', long)]
28 query: Option<String>,
29
30 #[arg(long)]
32 sort: Option<String>,
33
34 #[arg(long)]
36 page: Option<u32>,
37
38 #[arg(short, long, default_value = "25")]
40 limit: u32,
41 },
42
43 View {
45 repo: String,
47
48 id: u64,
50
51 #[arg(short, long)]
53 web: bool,
54 },
55
56 Create {
58 repo: String,
60
61 #[arg(short, long)]
63 title: String,
64
65 #[arg(short, long)]
67 source: String,
68
69 #[arg(short, long)]
71 destination: Option<String>,
72
73 #[arg(short = 'b', long)]
75 body: Option<String>,
76
77 #[arg(long)]
79 close_source_branch: bool,
80
81 #[arg(long)]
83 reviewers: Option<String>,
84 },
85
86 Edit {
88 repo: String,
90
91 id: u64,
93
94 #[arg(short, long)]
96 title: Option<String>,
97
98 #[arg(short = 'b', long)]
100 body: Option<String>,
101
102 #[arg(long)]
104 reviewers: Option<String>,
105
106 #[arg(short, long)]
108 destination: Option<String>,
109 },
110
111 Merge {
113 repo: String,
115
116 id: u64,
118
119 #[arg(short, long, value_enum, default_value = "merge-commit")]
121 strategy: MergeStrategyArg,
122
123 #[arg(short, long)]
125 message: Option<String>,
126
127 #[arg(long)]
129 close_source_branch: bool,
130 },
131
132 Approve {
134 repo: String,
136
137 id: u64,
139 },
140
141 Unapprove {
143 repo: String,
145
146 id: u64,
148 },
149
150 RequestChanges {
152 repo: String,
154
155 id: u64,
157 },
158
159 UnrequestChanges {
161 repo: String,
163
164 id: u64,
166 },
167
168 Decline {
170 repo: String,
172
173 id: u64,
175 },
176
177 Checkout {
179 repo: String,
181
182 id: u64,
184 },
185
186 Diff {
188 repo: String,
190
191 id: u64,
193 },
194
195 Comment {
197 repo: String,
199
200 id: u64,
202
203 #[arg(short, long)]
205 body: String,
206
207 #[arg(long)]
209 path: Option<String>,
210
211 #[arg(long, requires = "path")]
213 line: Option<u32>,
214
215 #[arg(long)]
217 parent: Option<u64>,
218 },
219
220 EditComment {
222 repo: String,
224
225 #[arg(value_name = "PR_ID")]
227 id: u64,
228
229 comment_id: u64,
231
232 #[arg(short, long)]
234 body: String,
235 },
236
237 DeleteComment {
239 repo: String,
241
242 #[arg(value_name = "PR_ID")]
244 id: u64,
245
246 comment_id: u64,
248
249 #[arg(short, long)]
251 yes: bool,
252 },
253
254 ResolveComment {
256 repo: String,
258
259 #[arg(value_name = "PR_ID")]
261 id: u64,
262
263 comment_id: u64,
265 },
266
267 UnresolveComment {
269 repo: String,
271
272 #[arg(value_name = "PR_ID")]
274 id: u64,
275
276 comment_id: u64,
278 },
279
280 ListComments {
282 repo: String,
284
285 id: u64,
287
288 #[arg(short, long, default_value = "25")]
290 limit: u32,
291 },
292
293 ViewComment {
295 repo: String,
297
298 #[arg(value_name = "PR_ID")]
300 id: u64,
301
302 comment_id: u64,
304 },
305
306 Pipelines {
308 repo: String,
310
311 id: u64,
313
314 #[arg(short, long, default_value = "100")]
316 scan_limit: u32,
317 },
318
319 Commits {
321 repo: String,
323
324 id: u64,
326
327 #[arg(short, long, default_value = "25")]
329 limit: u32,
330 },
331
332 Statuses {
334 repo: String,
336
337 id: u64,
339 },
340
341 Diffstat {
343 repo: String,
345
346 id: u64,
348
349 #[arg(short, long, default_value = "25")]
351 limit: u32,
352 },
353
354 Task {
356 #[command(subcommand)]
357 command: TaskCommands,
358 },
359
360 Activity {
362 repo: String,
364
365 id: u64,
367
368 #[arg(short, long, default_value = "25")]
370 limit: u32,
371 },
372
373 Patch {
375 repo: String,
377
378 id: u64,
380 },
381}
382
383#[derive(Subcommand)]
385pub enum TaskCommands {
386 List {
388 repo: String,
390
391 id: u64,
393 },
394
395 Add {
397 repo: String,
399
400 id: u64,
402
403 #[arg(short, long)]
405 body: String,
406 },
407
408 Resolve {
410 repo: String,
412
413 #[arg(value_name = "PR_ID")]
415 id: u64,
416
417 task_id: u64,
419 },
420
421 Reopen {
423 repo: String,
425
426 #[arg(value_name = "PR_ID")]
428 id: u64,
429
430 task_id: u64,
432 },
433
434 Delete {
436 repo: String,
438
439 #[arg(value_name = "PR_ID")]
441 id: u64,
442
443 task_id: u64,
445
446 #[arg(short, long)]
448 yes: bool,
449 },
450}
451
452#[derive(ValueEnum, Clone)]
453pub enum PrState {
454 Open,
455 Merged,
456 Declined,
457 Superseded,
458}
459
460impl From<PrState> for PullRequestState {
461 fn from(state: PrState) -> Self {
462 match state {
463 PrState::Open => PullRequestState::Open,
464 PrState::Merged => PullRequestState::Merged,
465 PrState::Declined => PullRequestState::Declined,
466 PrState::Superseded => PullRequestState::Superseded,
467 }
468 }
469}
470
471#[derive(ValueEnum, Clone)]
472pub enum MergeStrategyArg {
473 MergeCommit,
474 Squash,
475 FastForward,
476}
477
478impl From<MergeStrategyArg> for MergeStrategy {
479 fn from(strategy: MergeStrategyArg) -> Self {
480 match strategy {
481 MergeStrategyArg::MergeCommit => MergeStrategy::MergeCommit,
482 MergeStrategyArg::Squash => MergeStrategy::Squash,
483 MergeStrategyArg::FastForward => MergeStrategy::FastForward,
484 }
485 }
486}
487
488#[derive(Tabled)]
489struct PrRow {
490 #[tabled(rename = "ID")]
491 id: u64,
492 #[tabled(rename = "TITLE")]
493 title: String,
494 #[tabled(rename = "AUTHOR")]
495 author: String,
496 #[tabled(rename = "STATE")]
497 state: String,
498 #[tabled(rename = "UPDATED")]
499 updated: String,
500}
501
502#[derive(Tabled)]
503struct PipelineRow {
504 #[tabled(rename = "#")]
505 build: u64,
506 #[tabled(rename = "STATUS")]
507 status: String,
508 #[tabled(rename = "BRANCH")]
509 branch: String,
510 #[tabled(rename = "COMMIT")]
511 commit: String,
512 #[tabled(rename = "TRIGGERED")]
513 triggered: String,
514 #[tabled(rename = "DURATION")]
515 duration: String,
516}
517
518#[derive(Tabled)]
519struct CommitRow {
520 #[tabled(rename = "HASH")]
521 hash: String,
522 #[tabled(rename = "DATE")]
523 date: String,
524 #[tabled(rename = "MESSAGE")]
525 message: String,
526}
527
528#[derive(Tabled)]
529struct StatusRow {
530 #[tabled(rename = "KEY")]
531 key: String,
532 #[tabled(rename = "NAME")]
533 name: String,
534 #[tabled(rename = "STATE")]
535 state: String,
536 #[tabled(rename = "URL")]
537 url: String,
538}
539
540#[derive(Tabled)]
541struct DiffstatRow {
542 #[tabled(rename = "STATUS")]
543 status: String,
544 #[tabled(rename = "FILE")]
545 file: String,
546 #[tabled(rename = "+")]
547 added: String,
548 #[tabled(rename = "-")]
549 removed: String,
550}
551
552#[derive(Tabled)]
553struct TaskRow {
554 #[tabled(rename = "ID")]
555 id: String,
556 #[tabled(rename = "STATE")]
557 state: String,
558 #[tabled(rename = "TASK")]
559 content: String,
560}
561
562#[derive(Tabled)]
563struct CommentRow {
564 #[tabled(rename = "ID")]
565 id: u64,
566 #[tabled(rename = "AUTHOR")]
567 author: String,
568 #[tabled(rename = "CREATED")]
569 created: String,
570 #[tabled(rename = "TYPE")]
571 comment_type: String,
572 #[tabled(rename = "CONTENT")]
573 content: String,
574}
575
576impl PrCommands {
577 pub async fn run(self) -> Result<()> {
578 match self {
579 PrCommands::List {
580 repo,
581 state,
582 query,
583 sort,
584 page,
585 limit,
586 } => {
587 let (workspace, repo_slug) = parse_repo(&repo)?;
588 let client = BitbucketClient::from_stored().await?;
589
590 let states: Vec<PullRequestState> = state.into_iter().map(Into::into).collect();
591 let prs = client
592 .list_pull_requests_filtered(
593 &workspace,
594 &repo_slug,
595 crate::api::pullrequests::PrListFilters {
596 states: &states,
597 query: query.as_deref(),
598 sort: sort.as_deref(),
599 page,
600 pagelen: Some(limit.clamp(1, 100)),
601 },
602 )
603 .await?;
604
605 if super::output_json() {
606 return super::print_json(&prs.values);
607 }
608
609 if prs.values.is_empty() {
610 println!("No pull requests found");
611 return Ok(());
612 }
613
614 let rows: Vec<PrRow> = prs
615 .values
616 .iter()
617 .map(|pr| PrRow {
618 id: pr.id,
619 title: pr.title.chars().take(50).collect(),
620 author: pr.author.display_name.clone(),
621 state: format_state(&pr.state),
622 updated: pr.updated_on.format("%Y-%m-%d").to_string(),
623 })
624 .collect();
625
626 let table = Table::new(rows).to_string();
627 println!("{}", table);
628
629 if prs.next.is_some() {
630 println!(
631 "{} More pull requests available; use --page/--limit to see more.",
632 "ℹ".blue()
633 );
634 }
635
636 Ok(())
637 }
638
639 PrCommands::View { repo, id, web } => {
640 let (workspace, repo_slug) = parse_repo(&repo)?;
641 let client = BitbucketClient::from_stored().await?;
642 let pr = client.get_pull_request(&workspace, &repo_slug, id).await?;
643
644 if web {
645 if let Some(links) = &pr.links {
646 if let Some(html) = &links.html {
647 open::that(&html.href)?;
648 println!("Opened {} in browser", html.href.cyan());
649 return Ok(());
650 }
651 }
652 anyhow::bail!("Could not find PR URL");
653 }
654
655 if super::output_json() {
656 return super::print_json(&pr);
657 }
658
659 println!("{} {} #{}", format_state(&pr.state), pr.title.bold(), pr.id);
660 println!("{}", "─".repeat(60));
661
662 println!(
663 "{} {} → {}",
664 "Branches:".dimmed(),
665 pr.source.branch.name.cyan(),
666 pr.destination.branch.name.green()
667 );
668 println!("{} {}", "Author:".dimmed(), pr.author.display_name);
669 println!(
670 "{} {}",
671 "Created:".dimmed(),
672 pr.created_on.format("%Y-%m-%d %H:%M")
673 );
674 println!(
675 "{} {}",
676 "Updated:".dimmed(),
677 pr.updated_on.format("%Y-%m-%d %H:%M")
678 );
679
680 if let Some(count) = pr.comment_count {
681 println!("{} {}", "Comments:".dimmed(), count);
682 }
683
684 if let Some(tasks) = pr.task_count {
685 if tasks > 0 {
686 println!("{} {}", "Tasks:".dimmed(), tasks);
687 }
688 }
689
690 if let Some(participants) = &pr.participants {
692 let approvals: Vec<_> = participants
693 .iter()
694 .filter(|p| p.approved)
695 .map(|p| p.user.display_name.clone())
696 .collect();
697
698 if !approvals.is_empty() {
699 println!(
700 "{} {}",
701 "Approved by:".dimmed(),
702 approvals.join(", ").green()
703 );
704 }
705 }
706
707 if let Some(description) = &pr.description {
708 if !description.is_empty() {
709 println!();
710 println!("{}", description);
711 }
712 }
713
714 if let Some(links) = &pr.links {
715 if let Some(html) = &links.html {
716 println!();
717 println!("{} {}", "URL:".dimmed(), html.href.cyan());
718 }
719 }
720
721 Ok(())
722 }
723
724 PrCommands::Create {
725 repo,
726 title,
727 source,
728 destination,
729 body,
730 close_source_branch,
731 reviewers,
732 } => {
733 let (workspace, repo_slug) = parse_repo(&repo)?;
734 let client = BitbucketClient::from_stored().await?;
735
736 let request = CreatePullRequestRequest {
737 title,
738 source: PullRequestBranchRef {
739 branch: BranchInfo { name: source },
740 },
741 destination: destination.map(|d| PullRequestBranchRef {
742 branch: BranchInfo { name: d },
743 }),
744 description: body,
745 close_source_branch: Some(close_source_branch),
746 reviewers: reviewers.as_deref().map(parse_reviewers),
747 };
748
749 let pr = client
750 .create_pull_request(&workspace, &repo_slug, &request)
751 .await?;
752
753 if super::output_json() {
754 return super::print_json(&pr);
755 }
756
757 println!("{} Created pull request #{}", "✓".green(), pr.id);
758
759 if let Some(links) = &pr.links {
760 if let Some(html) = &links.html {
761 println!("{} {}", "URL:".dimmed(), html.href.cyan());
762 }
763 }
764
765 Ok(())
766 }
767
768 PrCommands::Edit {
769 repo,
770 id,
771 title,
772 body,
773 reviewers,
774 destination,
775 } => {
776 let (workspace, repo_slug) = parse_repo(&repo)?;
777
778 let request = UpdatePullRequestRequest {
779 title,
780 description: body,
781 reviewers: reviewers.as_deref().map(parse_reviewers),
782 destination: destination.map(|d| PullRequestBranchRef {
783 branch: BranchInfo { name: d },
784 }),
785 };
786
787 if request.is_empty() {
788 anyhow::bail!(
789 "Nothing to edit: pass at least one of --title, --body, --reviewers, or --destination"
790 );
791 }
792
793 let client = BitbucketClient::from_stored().await?;
794 let pr = client
795 .update_pull_request(&workspace, &repo_slug, id, &request)
796 .await?;
797
798 if super::output_json() {
799 return super::print_json(&pr);
800 }
801
802 println!("{} Updated pull request #{}", "✓".green(), pr.id);
803
804 Ok(())
805 }
806
807 PrCommands::Merge {
808 repo,
809 id,
810 strategy,
811 message,
812 close_source_branch,
813 } => {
814 let (workspace, repo_slug) = parse_repo(&repo)?;
815 let client = BitbucketClient::from_stored().await?;
816
817 let request = MergePullRequestRequest {
818 merge_type: Some("pullrequest".to_string()),
819 message,
820 close_source_branch: Some(close_source_branch),
821 merge_strategy: Some(strategy.into()),
822 };
823
824 let pr = client
825 .merge_pull_request(&workspace, &repo_slug, id, Some(&request))
826 .await?;
827
828 if super::output_json() {
829 return super::print_json(&pr);
830 }
831
832 println!("{} Merged pull request #{}", "✓".green(), pr.id);
833
834 Ok(())
835 }
836
837 PrCommands::Approve { repo, id } => {
838 let (workspace, repo_slug) = parse_repo(&repo)?;
839 let client = BitbucketClient::from_stored().await?;
840
841 client
842 .approve_pull_request(&workspace, &repo_slug, id)
843 .await?;
844
845 if super::output_json() {
846 return super::print_json(&serde_json::json!({"ok": true}));
847 }
848
849 println!("{} Approved pull request #{}", "✓".green(), id);
850
851 Ok(())
852 }
853
854 PrCommands::Unapprove { repo, id } => {
855 let (workspace, repo_slug) = parse_repo(&repo)?;
856 let client = BitbucketClient::from_stored().await?;
857
858 client
859 .unapprove_pull_request(&workspace, &repo_slug, id)
860 .await?;
861
862 if super::output_json() {
863 return super::print_json(&serde_json::json!({"ok": true}));
864 }
865
866 println!("{} Removed approval from pull request #{}", "✓".green(), id);
867
868 Ok(())
869 }
870
871 PrCommands::RequestChanges { repo, id } => {
872 let (workspace, repo_slug) = parse_repo(&repo)?;
873 let client = BitbucketClient::from_stored().await?;
874
875 client
876 .request_pr_changes(&workspace, &repo_slug, id)
877 .await?;
878
879 if super::output_json() {
880 return super::print_json(&serde_json::json!({"ok": true}));
881 }
882
883 println!("{} Requested changes on pull request #{}", "✓".green(), id);
884
885 Ok(())
886 }
887
888 PrCommands::UnrequestChanges { repo, id } => {
889 let (workspace, repo_slug) = parse_repo(&repo)?;
890 let client = BitbucketClient::from_stored().await?;
891
892 client
893 .unrequest_pr_changes(&workspace, &repo_slug, id)
894 .await?;
895
896 if super::output_json() {
897 return super::print_json(&serde_json::json!({"ok": true}));
898 }
899
900 println!(
901 "{} Withdrew request for changes on pull request #{}",
902 "✓".green(),
903 id
904 );
905
906 Ok(())
907 }
908
909 PrCommands::Decline { repo, id } => {
910 let (workspace, repo_slug) = parse_repo(&repo)?;
911 let client = BitbucketClient::from_stored().await?;
912
913 let pr = client
914 .decline_pull_request(&workspace, &repo_slug, id)
915 .await?;
916
917 if super::output_json() {
918 return super::print_json(&pr);
919 }
920
921 println!("{} Declined pull request #{}", "✓".green(), id);
922
923 Ok(())
924 }
925
926 PrCommands::Checkout { repo, id } => {
927 let (workspace, repo_slug) = parse_repo(&repo)?;
928 let client = BitbucketClient::from_stored().await?;
929
930 let pr = client.get_pull_request(&workspace, &repo_slug, id).await?;
931 checkout_pr_branch(&pr, &workspace, &repo_slug).await
932 }
933
934 PrCommands::Diff { repo, id } => {
935 let (workspace, repo_slug) = parse_repo(&repo)?;
936 let client = BitbucketClient::from_stored().await?;
937
938 let diff = client.get_pr_diff(&workspace, &repo_slug, id).await?;
939 println!("{}", diff);
940
941 Ok(())
942 }
943
944 PrCommands::Comment {
945 repo,
946 id,
947 body,
948 path,
949 line,
950 parent,
951 } => {
952 let (workspace, repo_slug) = parse_repo(&repo)?;
953 let client = BitbucketClient::from_stored().await?;
954
955 let comment = client
956 .add_pr_comment_full(
957 &workspace,
958 &repo_slug,
959 id,
960 crate::api::pullrequests::PrCommentInput {
961 content: &body,
962 path: path.as_deref(),
963 line,
964 parent,
965 },
966 )
967 .await?;
968
969 if super::output_json() {
970 return super::print_json(&comment);
971 }
972
973 println!("{} Added comment to pull request #{}", "✓".green(), id);
974
975 Ok(())
976 }
977
978 PrCommands::EditComment {
979 repo,
980 id,
981 comment_id,
982 body,
983 } => {
984 let (workspace, repo_slug) = parse_repo(&repo)?;
985 let client = BitbucketClient::from_stored().await?;
986
987 let comment = client
988 .update_pr_comment(&workspace, &repo_slug, id, comment_id, &body)
989 .await?;
990
991 if super::output_json() {
992 return super::print_json(&comment);
993 }
994
995 println!(
996 "{} Updated comment #{} on pull request #{}",
997 "✓".green(),
998 comment_id,
999 id
1000 );
1001
1002 Ok(())
1003 }
1004
1005 PrCommands::DeleteComment {
1006 repo,
1007 id,
1008 comment_id,
1009 yes,
1010 } => {
1011 let (workspace, repo_slug) = parse_repo(&repo)?;
1012
1013 if !yes
1014 && !super::confirm_or_abort(format!(
1015 "Delete comment #{} on PR #{}?",
1016 comment_id, id
1017 ))?
1018 {
1019 return Ok(());
1020 }
1021
1022 let client = BitbucketClient::from_stored().await?;
1023 client
1024 .delete_pr_comment(&workspace, &repo_slug, id, comment_id)
1025 .await?;
1026
1027 if super::output_json() {
1028 return super::print_json(&serde_json::json!({"ok": true}));
1029 }
1030
1031 println!(
1032 "{} Deleted comment #{} from pull request #{}",
1033 "✓".green(),
1034 comment_id,
1035 id
1036 );
1037
1038 Ok(())
1039 }
1040
1041 PrCommands::ResolveComment {
1042 repo,
1043 id,
1044 comment_id,
1045 } => {
1046 let (workspace, repo_slug) = parse_repo(&repo)?;
1047 let client = BitbucketClient::from_stored().await?;
1048
1049 client
1050 .resolve_pr_comment(&workspace, &repo_slug, id, comment_id)
1051 .await?;
1052
1053 if super::output_json() {
1054 return super::print_json(&serde_json::json!({"ok": true}));
1055 }
1056
1057 println!(
1058 "{} Resolved comment thread #{} on pull request #{}",
1059 "✓".green(),
1060 comment_id,
1061 id
1062 );
1063
1064 Ok(())
1065 }
1066
1067 PrCommands::UnresolveComment {
1068 repo,
1069 id,
1070 comment_id,
1071 } => {
1072 let (workspace, repo_slug) = parse_repo(&repo)?;
1073 let client = BitbucketClient::from_stored().await?;
1074
1075 client
1076 .unresolve_pr_comment(&workspace, &repo_slug, id, comment_id)
1077 .await?;
1078
1079 if super::output_json() {
1080 return super::print_json(&serde_json::json!({"ok": true}));
1081 }
1082
1083 println!(
1084 "{} Reopened comment thread #{} on pull request #{}",
1085 "✓".green(),
1086 comment_id,
1087 id
1088 );
1089
1090 Ok(())
1091 }
1092
1093 PrCommands::ListComments { repo, id, limit } => {
1094 let (workspace, repo_slug) = parse_repo(&repo)?;
1095 let client = BitbucketClient::from_stored().await?;
1096
1097 let comments = client
1098 .list_recent_pr_comments(&workspace, &repo_slug, id, limit as usize)
1099 .await?;
1100
1101 if super::output_json() {
1102 return super::print_json(&newest_comments_chronological(
1103 comments,
1104 limit as usize,
1105 ));
1106 }
1107
1108 if comments.is_empty() {
1109 println!("No comments found");
1110 return Ok(());
1111 }
1112
1113 let hit_limit = comments.len() >= limit as usize;
1114 let values = newest_comments_chronological(comments, limit as usize);
1115
1116 let rows: Vec<CommentRow> = values
1117 .iter()
1118 .map(|c| CommentRow {
1119 id: c.id,
1120 author: c.user.display_name.clone(),
1121 created: c.created_on.format("%Y-%m-%d %H:%M").to_string(),
1122 comment_type: if c.inline.is_some() {
1123 "inline".to_string()
1124 } else {
1125 "general".to_string()
1126 },
1127 content: c.content.raw.chars().take(50).collect(),
1128 })
1129 .collect();
1130
1131 let table = Table::new(rows).to_string();
1132 println!("{}", table);
1133
1134 if hit_limit {
1135 println!(
1136 "Showing the {} most recent comments. Use --limit to see more.",
1137 limit
1138 );
1139 }
1140
1141 Ok(())
1142 }
1143
1144 PrCommands::Pipelines {
1145 repo,
1146 id,
1147 scan_limit,
1148 } => {
1149 let (workspace, repo_slug) = parse_repo(&repo)?;
1150 let client = BitbucketClient::from_stored().await?;
1151
1152 let pr = client.get_pull_request(&workspace, &repo_slug, id).await?;
1153 let head_commit = pr
1154 .source
1155 .commit
1156 .as_ref()
1157 .map(|c| c.hash.clone())
1158 .context("PR has no head commit hash")?;
1159
1160 let pipelines = client
1161 .list_pipelines_for_commit(&workspace, &repo_slug, &head_commit, scan_limit)
1162 .await?;
1163
1164 if super::output_json() {
1165 return super::print_json(&pipelines);
1166 }
1167
1168 if pipelines.is_empty() {
1169 println!(
1170 "No pipelines found for PR #{} head commit {} (scanned {} most recent).",
1171 id,
1172 head_commit.chars().take(12).collect::<String>(),
1173 scan_limit.clamp(1, 100)
1174 );
1175 return Ok(());
1176 }
1177
1178 let rows: Vec<PipelineRow> = pipelines
1179 .iter()
1180 .map(|p| {
1181 let duration = match (p.build_seconds_used, &p.state.name) {
1182 (Some(s), _) => super::pipeline::format_duration(s),
1183 (None, crate::models::PipelineStateName::InProgress) => {
1184 "running...".to_string()
1185 }
1186 _ => "-".to_string(),
1187 };
1188
1189 PipelineRow {
1190 build: p.build_number,
1191 status: super::pipeline::format_status(
1192 &p.state.name,
1193 p.state.result.as_ref().map(|r| &r.name),
1194 ),
1195 branch: p.target.ref_name.clone().unwrap_or_else(|| "-".to_string()),
1196 commit: p
1197 .target
1198 .commit
1199 .as_ref()
1200 .map(|c| c.hash.chars().take(12).collect())
1201 .unwrap_or_else(|| "-".to_string()),
1202 triggered: p.created_on.format("%Y-%m-%d %H:%M").to_string(),
1203 duration,
1204 }
1205 })
1206 .collect();
1207
1208 println!("{}", Table::new(rows));
1209
1210 Ok(())
1211 }
1212
1213 PrCommands::ViewComment {
1214 repo,
1215 id,
1216 comment_id,
1217 } => {
1218 let (workspace, repo_slug) = parse_repo(&repo)?;
1219 let client = BitbucketClient::from_stored().await?;
1220
1221 let comment = client
1222 .get_pr_comment(&workspace, &repo_slug, id, comment_id)
1223 .await?;
1224
1225 if super::output_json() {
1226 return super::print_json(&comment);
1227 }
1228
1229 println!("{} #{} on PR #{}", "Comment".bold(), comment.id, id);
1230 println!("{}", "─".repeat(60));
1231
1232 println!("{} {}", "Author:".dimmed(), comment.user.display_name);
1233 println!(
1234 "{} {}",
1235 "Created:".dimmed(),
1236 comment.created_on.format("%Y-%m-%d %H:%M")
1237 );
1238
1239 if let Some(updated) = comment.updated_on {
1240 println!(
1241 "{} {}",
1242 "Updated:".dimmed(),
1243 updated.format("%Y-%m-%d %H:%M")
1244 );
1245 }
1246
1247 if let Some(inline) = &comment.inline {
1248 let line = inline.to.or(inline.from);
1249 let location = match line {
1250 Some(l) => format!("{}:{}", inline.path, l),
1251 None => inline.path.clone(),
1252 };
1253 println!("{} inline", "Type:".dimmed());
1254 println!("{} {}", "File:".dimmed(), location.cyan());
1255 } else {
1256 println!("{} general", "Type:".dimmed());
1257 }
1258
1259 println!();
1260 println!("{}", comment.content.raw);
1261
1262 if let Some(links) = &comment.links {
1263 if let Some(html) = &links.html {
1264 println!();
1265 println!("{} {}", "URL:".dimmed(), html.href.cyan());
1266 }
1267 }
1268
1269 Ok(())
1270 }
1271
1272 PrCommands::Commits { repo, id, limit } => {
1273 let (workspace, repo_slug) = parse_repo(&repo)?;
1274 let client = BitbucketClient::from_stored().await?;
1275
1276 let commits = client
1277 .list_pr_commits(&workspace, &repo_slug, id, Some(limit.clamp(1, 100)))
1278 .await?;
1279
1280 if super::output_json() {
1281 return super::print_json(&commits.values);
1282 }
1283
1284 if commits.values.is_empty() {
1285 println!("No commits found");
1286 return Ok(());
1287 }
1288
1289 let rows: Vec<CommitRow> = commits
1290 .values
1291 .iter()
1292 .map(|c| CommitRow {
1293 hash: c.hash.chars().take(12).collect(),
1294 date: c
1295 .date
1296 .map(|d| d.format("%Y-%m-%d %H:%M").to_string())
1297 .unwrap_or_else(|| "-".to_string()),
1298 message: first_line_truncated(c.message.as_deref().unwrap_or(""), 60),
1299 })
1300 .collect();
1301
1302 println!("{}", Table::new(rows));
1303
1304 if commits.next.is_some() {
1305 println!(
1306 "{} More commits available; use --limit to see more.",
1307 "ℹ".blue()
1308 );
1309 }
1310
1311 Ok(())
1312 }
1313
1314 PrCommands::Statuses { repo, id } => {
1315 let (workspace, repo_slug) = parse_repo(&repo)?;
1316 let client = BitbucketClient::from_stored().await?;
1317
1318 let statuses = client.list_pr_statuses(&workspace, &repo_slug, id).await?;
1319
1320 if super::output_json() {
1321 return super::print_json(&statuses);
1322 }
1323
1324 if statuses.is_empty() {
1325 println!("No build statuses found");
1326 return Ok(());
1327 }
1328
1329 let rows: Vec<StatusRow> = statuses
1330 .iter()
1331 .map(|s| StatusRow {
1332 key: s.key.clone().unwrap_or_else(|| "-".to_string()),
1333 name: s.name.clone().unwrap_or_else(|| "-".to_string()),
1334 state: format_commit_status_state(s.state.as_deref().unwrap_or("-")),
1335 url: s.url.clone().unwrap_or_else(|| "-".to_string()),
1336 })
1337 .collect();
1338
1339 println!("{}", Table::new(rows));
1340
1341 Ok(())
1342 }
1343
1344 PrCommands::Diffstat { repo, id, limit } => {
1345 let (workspace, repo_slug) = parse_repo(&repo)?;
1346 let limit = effective_limit(limit);
1347 let client = BitbucketClient::from_stored().await?;
1348
1349 let diffstat = client
1350 .get_pr_diffstat(&workspace, &repo_slug, id, Some(limit))
1351 .await?;
1352
1353 if super::output_json() {
1354 return super::print_json(&diffstat.values);
1355 }
1356
1357 if diffstat.values.is_empty() {
1358 println!("No changes found");
1359 return Ok(());
1360 }
1361
1362 let rows: Vec<DiffstatRow> = diffstat
1363 .values
1364 .iter()
1365 .map(|e| {
1366 let file = e
1367 .new
1368 .as_ref()
1369 .and_then(|f| f.path.clone())
1370 .or_else(|| e.old.as_ref().and_then(|f| f.path.clone()))
1371 .unwrap_or_else(|| "-".to_string());
1372
1373 DiffstatRow {
1374 status: e.status.clone().unwrap_or_else(|| "-".to_string()),
1375 file,
1376 added: e
1377 .lines_added
1378 .map(|n| n.to_string())
1379 .unwrap_or_else(|| "-".to_string()),
1380 removed: e
1381 .lines_removed
1382 .map(|n| n.to_string())
1383 .unwrap_or_else(|| "-".to_string()),
1384 }
1385 })
1386 .collect();
1387
1388 println!("{}", Table::new(rows));
1389
1390 let total_added: u64 = diffstat.values.iter().filter_map(|e| e.lines_added).sum();
1391 let total_removed: u64 =
1392 diffstat.values.iter().filter_map(|e| e.lines_removed).sum();
1393 println!(
1394 "{} files changed, {} insertions(+), {} deletions(-)",
1395 diffstat.values.len(),
1396 total_added.to_string().green(),
1397 total_removed.to_string().red()
1398 );
1399
1400 if diffstat.next.is_some() {
1401 println!(
1402 "{} More changed files available; use --limit to see more.",
1403 "ℹ".blue()
1404 );
1405 }
1406
1407 Ok(())
1408 }
1409
1410 PrCommands::Task { command } => command.run().await,
1411
1412 PrCommands::Activity { repo, id, limit } => {
1413 let (workspace, repo_slug) = parse_repo(&repo)?;
1414 let client = BitbucketClient::from_stored().await?;
1415
1416 let activity = client
1417 .list_pr_activity(&workspace, &repo_slug, id, Some(limit.clamp(1, 100)))
1418 .await?;
1419
1420 if super::output_json() {
1421 return super::print_json(&activity.values);
1422 }
1423
1424 if activity.values.is_empty() {
1425 println!("No activity found");
1426 return Ok(());
1427 }
1428
1429 for entry in &activity.values {
1430 println!("{}", format_activity_line(entry));
1431 }
1432
1433 if activity.next.is_some() {
1434 println!(
1435 "{} More activity available; use --limit to see more.",
1436 "ℹ".blue()
1437 );
1438 }
1439
1440 Ok(())
1441 }
1442
1443 PrCommands::Patch { repo, id } => {
1444 let (workspace, repo_slug) = parse_repo(&repo)?;
1445 let client = BitbucketClient::from_stored().await?;
1446
1447 let patch = client.get_pr_patch(&workspace, &repo_slug, id).await?;
1448 println!("{}", patch);
1449
1450 Ok(())
1451 }
1452 }
1453 }
1454}
1455
1456impl TaskCommands {
1457 pub async fn run(self) -> Result<()> {
1458 match self {
1459 TaskCommands::List { repo, id } => {
1460 let (workspace, repo_slug) = parse_repo(&repo)?;
1461 let client = BitbucketClient::from_stored().await?;
1462
1463 let tasks = client.list_pr_tasks(&workspace, &repo_slug, id).await?;
1464
1465 if super::output_json() {
1466 return super::print_json(&tasks);
1467 }
1468
1469 if tasks.is_empty() {
1470 println!("No tasks found");
1471 return Ok(());
1472 }
1473
1474 let rows: Vec<TaskRow> = tasks
1475 .iter()
1476 .map(|t| TaskRow {
1477 id: t
1478 .id
1479 .map(|i| i.to_string())
1480 .unwrap_or_else(|| "-".to_string()),
1481 state: match t.state.as_deref() {
1482 Some("RESOLVED") => "RESOLVED".green().to_string(),
1483 Some("UNRESOLVED") => "UNRESOLVED".yellow().to_string(),
1484 Some(other) => other.to_string(),
1485 None => "-".to_string(),
1486 },
1487 content: first_line_truncated(
1488 t.content
1489 .as_ref()
1490 .and_then(|c| c.raw.as_deref())
1491 .unwrap_or(""),
1492 60,
1493 ),
1494 })
1495 .collect();
1496
1497 println!("{}", Table::new(rows));
1498
1499 Ok(())
1500 }
1501
1502 TaskCommands::Add { repo, id, body } => {
1503 let (workspace, repo_slug) = parse_repo(&repo)?;
1504 let client = BitbucketClient::from_stored().await?;
1505
1506 let task = client
1507 .add_pr_task(&workspace, &repo_slug, id, &body)
1508 .await?;
1509
1510 if super::output_json() {
1511 return super::print_json(&task);
1512 }
1513
1514 match task.id {
1515 Some(task_id) => println!(
1516 "{} Added task #{} to pull request #{}",
1517 "✓".green(),
1518 task_id,
1519 id
1520 ),
1521 None => println!("{} Added task to pull request #{}", "✓".green(), id),
1522 }
1523
1524 Ok(())
1525 }
1526
1527 TaskCommands::Resolve { repo, id, task_id } => {
1528 let (workspace, repo_slug) = parse_repo(&repo)?;
1529 let client = BitbucketClient::from_stored().await?;
1530
1531 let task = client
1532 .update_pr_task(&workspace, &repo_slug, id, task_id, None, Some("RESOLVED"))
1533 .await?;
1534
1535 if super::output_json() {
1536 return super::print_json(&task);
1537 }
1538
1539 println!(
1540 "{} Resolved task #{} on pull request #{}",
1541 "✓".green(),
1542 task_id,
1543 id
1544 );
1545
1546 Ok(())
1547 }
1548
1549 TaskCommands::Reopen { repo, id, task_id } => {
1550 let (workspace, repo_slug) = parse_repo(&repo)?;
1551 let client = BitbucketClient::from_stored().await?;
1552
1553 let task = client
1554 .update_pr_task(
1555 &workspace,
1556 &repo_slug,
1557 id,
1558 task_id,
1559 None,
1560 Some("UNRESOLVED"),
1561 )
1562 .await?;
1563
1564 if super::output_json() {
1565 return super::print_json(&task);
1566 }
1567
1568 println!(
1569 "{} Reopened task #{} on pull request #{}",
1570 "✓".green(),
1571 task_id,
1572 id
1573 );
1574
1575 Ok(())
1576 }
1577
1578 TaskCommands::Delete {
1579 repo,
1580 id,
1581 task_id,
1582 yes,
1583 } => {
1584 let (workspace, repo_slug) = parse_repo(&repo)?;
1585
1586 if !yes
1587 && !super::confirm_or_abort(format!("Delete task #{} on PR #{}?", task_id, id))?
1588 {
1589 return Ok(());
1590 }
1591
1592 let client = BitbucketClient::from_stored().await?;
1593 client
1594 .delete_pr_task(&workspace, &repo_slug, id, task_id)
1595 .await?;
1596
1597 if super::output_json() {
1598 return super::print_json(&serde_json::json!({"ok": true}));
1599 }
1600
1601 println!(
1602 "{} Deleted task #{} from pull request #{}",
1603 "✓".green(),
1604 task_id,
1605 id
1606 );
1607
1608 Ok(())
1609 }
1610 }
1611 }
1612}
1613
1614fn format_state(state: &PullRequestState) -> String {
1615 match state {
1616 PullRequestState::Open => "OPEN".green().to_string(),
1617 PullRequestState::Merged => "MERGED".purple().to_string(),
1618 PullRequestState::Declined => "DECLINED".red().to_string(),
1619 PullRequestState::Superseded => "SUPERSEDED".yellow().to_string(),
1620 }
1621}
1622
1623fn format_commit_status_state(state: &str) -> String {
1624 match state {
1625 "SUCCESSFUL" => state.green().to_string(),
1626 "FAILED" => state.red().to_string(),
1627 "INPROGRESS" => state.yellow().to_string(),
1628 "STOPPED" => state.dimmed().to_string(),
1629 _ => state.to_string(),
1630 }
1631}
1632
1633fn parse_reviewers(spec: &str) -> Vec<UserRef> {
1637 spec.split(',')
1638 .map(str::trim)
1639 .filter(|s| !s.is_empty())
1640 .map(reviewer_ref)
1641 .collect()
1642}
1643
1644fn reviewer_ref(token: &str) -> UserRef {
1651 if looks_like_account_id(token) {
1652 UserRef {
1653 uuid: Some(token.to_string()),
1654 username: None,
1655 }
1656 } else {
1657 UserRef {
1658 uuid: None,
1659 username: Some(token.to_string()),
1660 }
1661 }
1662}
1663
1664fn looks_like_account_id(token: &str) -> bool {
1667 token.starts_with('{') || token.contains(':') || is_uuid(token)
1668}
1669
1670fn is_uuid(token: &str) -> bool {
1672 const GROUPS: [usize; 5] = [8, 4, 4, 4, 12];
1673
1674 let mut parts = token.split('-');
1675 for &len in &GROUPS {
1676 match parts.next() {
1677 Some(part) if part.len() == len && part.bytes().all(|b| b.is_ascii_hexdigit()) => {}
1678 _ => return false,
1679 }
1680 }
1681 parts.next().is_none()
1682}
1683
1684fn remote_matches_repo(url: &str, workspace: &str, repo_slug: &str) -> bool {
1690 let lowered = url.trim().to_lowercase();
1691 let trimmed = lowered.trim_end_matches('/');
1692 let trimmed = trimmed.strip_suffix(".git").unwrap_or(trimmed);
1693
1694 let expected = format!("{}/{}", workspace.to_lowercase(), repo_slug.to_lowercase());
1695 trimmed.ends_with(&format!("/{}", expected)) || trimmed.ends_with(&format!(":{}", expected))
1696}
1697
1698async fn checkout_pr_branch(pr: &PullRequest, workspace: &str, repo_slug: &str) -> Result<()> {
1705 let branch = &pr.source.branch.name;
1706
1707 let output = std::process::Command::new("git")
1710 .args(["remote", "get-url", "origin"])
1711 .output()
1712 .context("Failed to read the 'origin' remote URL")?;
1713
1714 if !output.status.success() {
1715 anyhow::bail!(
1716 "Could not determine the 'origin' remote URL — is the current directory a git repository with an 'origin' remote?"
1717 );
1718 }
1719
1720 let origin_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
1721 if !remote_matches_repo(&origin_url, workspace, repo_slug) {
1722 anyhow::bail!(
1723 "The 'origin' remote ({}) does not point at {}/{}",
1724 origin_url,
1725 workspace,
1726 repo_slug
1727 );
1728 }
1729
1730 if let Some(source_repo) = &pr.source.repository {
1733 let target = format!("{}/{}", workspace, repo_slug);
1734 if !source_repo.full_name.eq_ignore_ascii_case(&target) {
1735 anyhow::bail!(
1736 "PR #{} comes from fork '{}' — add the fork as a remote and fetch manually",
1737 pr.id,
1738 source_repo.full_name
1739 );
1740 }
1741 }
1742
1743 println!("Fetching and checking out branch {}...", branch.cyan());
1744
1745 let status = std::process::Command::new("git")
1747 .args(["fetch", "origin", branch])
1748 .status()
1749 .context("Failed to fetch branch")?;
1750
1751 if !status.success() {
1752 anyhow::bail!("git fetch failed");
1753 }
1754
1755 let status = std::process::Command::new("git")
1757 .args(["checkout", branch])
1758 .status()
1759 .context("Failed to checkout branch")?;
1760
1761 if status.success() {
1762 let ff_status = std::process::Command::new("git")
1765 .args(["merge", "--ff-only", &format!("origin/{}", branch)])
1766 .status()
1767 .context("Failed to fast-forward branch")?;
1768
1769 if ff_status.success() {
1770 println!("{} Checked out branch {}", "✓".green(), branch);
1771 } else {
1772 println!(
1773 "{} Checked out branch {}, but it has diverged from origin/{} and could not be fast-forwarded; merge or rebase manually.",
1774 "⚠".yellow(),
1775 branch,
1776 branch
1777 );
1778 }
1779 } else {
1780 let status = std::process::Command::new("git")
1782 .args(["checkout", "-b", branch, &format!("origin/{}", branch)])
1783 .status()
1784 .context("Failed to create tracking branch")?;
1785
1786 if status.success() {
1787 println!("{} Created and checked out branch {}", "✓".green(), branch);
1788 } else {
1789 anyhow::bail!("git checkout failed");
1790 }
1791 }
1792
1793 Ok(())
1794}
1795
1796fn first_line_truncated(text: &str, max_chars: usize) -> String {
1798 text.lines()
1799 .next()
1800 .unwrap_or("")
1801 .chars()
1802 .take(max_chars)
1803 .collect()
1804}
1805
1806fn activity_date(value: &serde_json::Value, pointer: &str) -> String {
1808 value
1809 .pointer(pointer)
1810 .and_then(|v| v.as_str())
1811 .map(|d| d.chars().take(16).collect::<String>().replace('T', " "))
1812 .unwrap_or_else(|| "-".to_string())
1813}
1814
1815fn format_activity_line(entry: &PrActivity) -> String {
1817 fn str_at<'a>(value: &'a serde_json::Value, pointer: &'a str) -> Option<&'a str> {
1818 value.pointer(pointer).and_then(|v| v.as_str())
1819 }
1820
1821 if let Some(comment) = &entry.comment {
1822 format!(
1823 "[{}] comment: {} — {}",
1824 activity_date(comment, "/created_on"),
1825 str_at(comment, "/user/display_name").unwrap_or("unknown"),
1826 first_line_truncated(str_at(comment, "/content/raw").unwrap_or(""), 60)
1827 )
1828 } else if let Some(approval) = &entry.approval {
1829 format!(
1830 "[{}] approval: approved by {}",
1831 activity_date(approval, "/date"),
1832 str_at(approval, "/user/display_name").unwrap_or("unknown")
1833 )
1834 } else if let Some(changes_requested) = &entry.changes_requested {
1835 format!(
1836 "[{}] changes-requested: by {}",
1837 activity_date(changes_requested, "/date"),
1838 str_at(changes_requested, "/user/display_name").unwrap_or("unknown")
1839 )
1840 } else if let Some(update) = &entry.update {
1841 format!(
1842 "[{}] update: {} by {}",
1843 activity_date(update, "/date"),
1844 str_at(update, "/state").unwrap_or("updated"),
1845 str_at(update, "/author/display_name").unwrap_or("unknown")
1846 )
1847 } else {
1848 "unrecognized activity entry".to_string()
1849 }
1850}
1851
1852fn newest_comments_chronological(
1855 mut comments: Vec<PullRequestComment>,
1856 limit: usize,
1857) -> Vec<PullRequestComment> {
1858 comments.sort_by_key(|c| std::cmp::Reverse(c.created_on));
1859 comments.truncate(limit);
1860 comments.reverse();
1861 comments
1862}
1863
1864#[cfg(test)]
1865mod tests {
1866 use super::{
1867 first_line_truncated, format_activity_line, format_commit_status_state,
1868 newest_comments_chronological, parse_reviewers, remote_matches_repo, reviewer_ref,
1869 };
1870 use crate::models::{CommentContent, PrActivity, PullRequestComment, User};
1871 use chrono::{DateTime, Utc};
1872
1873 fn ts(s: &str) -> DateTime<Utc> {
1874 s.parse().unwrap()
1875 }
1876
1877 fn comment(id: u64, created_on: DateTime<Utc>) -> PullRequestComment {
1878 PullRequestComment {
1879 id,
1880 content: CommentContent {
1881 raw: format!("comment {}", id),
1882 markup: None,
1883 html: None,
1884 },
1885 user: User {
1886 uuid: "{user-uuid}".to_string(),
1887 username: None,
1888 display_name: "Test User".to_string(),
1889 account_id: None,
1890 user_type: "user".to_string(),
1891 links: None,
1892 },
1893 created_on,
1894 updated_on: None,
1895 deleted: None,
1896 inline: None,
1897 parent: None,
1898 links: None,
1899 }
1900 }
1901
1902 #[test]
1903 fn keeps_the_newest_comments_in_ascending_display_order() {
1904 let t1 = ts("2024-01-01T00:00:00Z");
1905 let t2 = ts("2024-01-02T00:00:00Z");
1906 let t3 = ts("2024-01-03T00:00:00Z");
1907 let input = vec![comment(3, t3), comment(1, t1), comment(2, t2)];
1908
1909 let result = newest_comments_chronological(input, 2);
1910
1911 let times: Vec<DateTime<Utc>> = result.iter().map(|c| c.created_on).collect();
1912 assert_eq!(times, vec![t2, t3]);
1913 }
1914
1915 #[test]
1916 fn limit_larger_than_input_returns_all_in_ascending_order() {
1917 let t1 = ts("2024-01-01T00:00:00Z");
1918 let t2 = ts("2024-01-02T00:00:00Z");
1919 let t3 = ts("2024-01-03T00:00:00Z");
1920 let input = vec![comment(3, t3), comment(1, t1), comment(2, t2)];
1921
1922 let result = newest_comments_chronological(input, 10);
1923
1924 let times: Vec<DateTime<Utc>> = result.iter().map(|c| c.created_on).collect();
1925 assert_eq!(times, vec![t1, t2, t3]);
1926 }
1927
1928 #[test]
1929 fn remote_matches_repo_accepts_https_urls() {
1930 assert!(remote_matches_repo(
1931 "https://bitbucket.org/acme/my-repo",
1932 "acme",
1933 "my-repo"
1934 ));
1935 assert!(remote_matches_repo(
1936 "https://user@bitbucket.org/acme/my-repo.git",
1937 "acme",
1938 "my-repo"
1939 ));
1940 }
1941
1942 #[test]
1943 fn remote_matches_repo_accepts_ssh_urls() {
1944 assert!(remote_matches_repo(
1945 "git@bitbucket.org:acme/my-repo.git",
1946 "acme",
1947 "my-repo"
1948 ));
1949 assert!(remote_matches_repo(
1950 "ssh://git@bitbucket.org/acme/my-repo.git",
1951 "acme",
1952 "my-repo"
1953 ));
1954 }
1955
1956 #[test]
1957 fn remote_matches_repo_tolerates_case_and_trailing_slash() {
1958 assert!(remote_matches_repo(
1959 "https://bitbucket.org/Acme/My-Repo.git/",
1960 "acme",
1961 "my-repo"
1962 ));
1963 assert!(remote_matches_repo(
1964 "git@bitbucket.org:ACME/MY-REPO",
1965 "Acme",
1966 "My-Repo"
1967 ));
1968 }
1969
1970 #[test]
1971 fn remote_matches_repo_rejects_other_repos() {
1972 assert!(!remote_matches_repo(
1973 "https://bitbucket.org/acme/other-repo.git",
1974 "acme",
1975 "my-repo"
1976 ));
1977 assert!(!remote_matches_repo(
1978 "git@bitbucket.org:someone-else/my-repo.git",
1979 "acme",
1980 "my-repo"
1981 ));
1982 assert!(!remote_matches_repo(
1984 "https://bitbucket.org/other-acme/my-repo",
1985 "acme",
1986 "my-repo"
1987 ));
1988 assert!(!remote_matches_repo("", "acme", "my-repo"));
1989 }
1990
1991 #[test]
1992 fn parse_reviewers_splits_trims_and_skips_empty_segments() {
1993 let reviewers = parse_reviewers(" alice , bob,,charlie ");
1994
1995 let usernames: Vec<Option<String>> = reviewers.iter().map(|r| r.username.clone()).collect();
1996 assert_eq!(
1997 usernames,
1998 vec![
1999 Some("alice".to_string()),
2000 Some("bob".to_string()),
2001 Some("charlie".to_string())
2002 ]
2003 );
2004 assert!(reviewers.iter().all(|r| r.uuid.is_none()));
2005 }
2006
2007 #[test]
2008 fn reviewer_ref_classifies_uuid_and_username_tokens() {
2009 let braced = reviewer_ref("{4d9e8f2a-1234-5678-9abc-def012345678}");
2011 assert_eq!(
2012 braced.uuid.as_deref(),
2013 Some("{4d9e8f2a-1234-5678-9abc-def012345678}")
2014 );
2015 assert!(braced.username.is_none());
2016
2017 let uuid = reviewer_ref("4d9e8f2a-1234-5678-9abc-def012345678");
2019 assert_eq!(
2020 uuid.uuid.as_deref(),
2021 Some("4d9e8f2a-1234-5678-9abc-def012345678")
2022 );
2023 assert!(uuid.username.is_none());
2024
2025 let account = reviewer_ref("557058:e5f8d5c1-0000-1111-2222-333344445555");
2027 assert_eq!(
2028 account.uuid.as_deref(),
2029 Some("557058:e5f8d5c1-0000-1111-2222-333344445555")
2030 );
2031 assert!(account.username.is_none());
2032
2033 let username = reviewer_ref("alice");
2035 assert_eq!(username.username.as_deref(), Some("alice"));
2036 assert!(username.uuid.is_none());
2037
2038 let dashed = reviewer_ref("my-cool-user");
2040 assert_eq!(dashed.username.as_deref(), Some("my-cool-user"));
2041 assert!(dashed.uuid.is_none());
2042 }
2043
2044 #[test]
2045 fn format_commit_status_state_preserves_state_text() {
2046 for state in ["SUCCESSFUL", "FAILED", "INPROGRESS", "STOPPED"] {
2047 assert!(
2048 format_commit_status_state(state).contains(state),
2049 "state text {state} should be preserved",
2050 );
2051 }
2052 }
2053
2054 #[test]
2055 fn first_line_truncated_keeps_only_the_first_line() {
2056 assert_eq!(first_line_truncated("one\ntwo", 60), "one");
2057 assert_eq!(first_line_truncated("abcdef", 3), "abc");
2058 assert_eq!(first_line_truncated("", 10), "");
2059 }
2060
2061 fn empty_activity() -> PrActivity {
2062 PrActivity {
2063 update: None,
2064 approval: None,
2065 comment: None,
2066 changes_requested: None,
2067 }
2068 }
2069
2070 #[test]
2071 fn format_activity_line_renders_each_entry_type() {
2072 let update = PrActivity {
2073 update: Some(serde_json::json!({
2074 "date": "2024-05-01T10:20:30+00:00",
2075 "state": "OPEN",
2076 "author": { "display_name": "Alice" }
2077 })),
2078 ..empty_activity()
2079 };
2080 assert_eq!(
2081 format_activity_line(&update),
2082 "[2024-05-01 10:20] update: OPEN by Alice"
2083 );
2084
2085 let approval = PrActivity {
2086 approval: Some(serde_json::json!({
2087 "date": "2024-05-02T11:00:00+00:00",
2088 "user": { "display_name": "Bob" }
2089 })),
2090 ..empty_activity()
2091 };
2092 assert_eq!(
2093 format_activity_line(&approval),
2094 "[2024-05-02 11:00] approval: approved by Bob"
2095 );
2096
2097 let comment = PrActivity {
2098 comment: Some(serde_json::json!({
2099 "created_on": "2024-05-03T09:15:00+00:00",
2100 "user": { "display_name": "Carol" },
2101 "content": { "raw": "Looks good\nSecond line ignored" }
2102 })),
2103 ..empty_activity()
2104 };
2105 assert_eq!(
2106 format_activity_line(&comment),
2107 "[2024-05-03 09:15] comment: Carol — Looks good"
2108 );
2109
2110 let changes_requested = PrActivity {
2111 changes_requested: Some(serde_json::json!({
2112 "date": "2024-05-04T08:00:00+00:00",
2113 "user": { "display_name": "Dave" }
2114 })),
2115 ..empty_activity()
2116 };
2117 assert_eq!(
2118 format_activity_line(&changes_requested),
2119 "[2024-05-04 08:00] changes-requested: by Dave"
2120 );
2121
2122 assert_eq!(
2123 format_activity_line(&empty_activity()),
2124 "unrecognized activity entry"
2125 );
2126 }
2127}