1use std::collections::HashSet;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result};
5use clap::{Subcommand, ValueEnum};
6use colored::Colorize;
7use tabled::{Table, Tabled};
8
9use super::{confirm_or_abort, parse_repo};
10use crate::api::BitbucketClient;
11use crate::api::issues::{IssueListFilters, IssueUpdate};
12use crate::cli::pagination::{MAX_LIMIT, effective_limit as capped_limit};
13use crate::models::{
14 ComponentName, CreateIssueRequest, IssueAttachment, IssueChange, IssueComment,
15 IssueContentRequest, IssueKind, IssueMetaItem, IssuePriority, IssueState, MilestoneName,
16 UserAccountId, VersionName,
17};
18
19#[derive(Subcommand)]
20pub enum IssueCommands {
21 List {
23 repo: String,
25
26 #[arg(short, long, value_enum)]
28 state: Option<IssueStateArg>,
29
30 #[arg(short, long, value_enum)]
32 kind: Option<IssueKindArg>,
33
34 #[arg(short, long, value_enum)]
36 priority: Option<IssuePriorityArg>,
37
38 #[arg(long)]
40 assignee: Option<String>,
41
42 #[arg(long)]
44 reporter: Option<String>,
45
46 #[arg(short, long)]
48 query: Option<String>,
49
50 #[arg(long)]
52 sort: Option<String>,
53
54 #[arg(long)]
56 page: Option<u32>,
57
58 #[arg(short, long, default_value = "25")]
60 limit: u32,
61 },
62
63 View {
65 repo: String,
67
68 id: u64,
70
71 #[arg(short, long)]
73 comments: bool,
74
75 #[arg(short, long)]
77 web: bool,
78 },
79
80 #[command(disable_version_flag = true)]
82 Create {
83 repo: String,
85
86 #[arg(short, long)]
88 title: String,
89
90 #[arg(short = 'b', long)]
92 body: Option<String>,
93
94 #[arg(short, long, value_enum, default_value = "bug")]
96 kind: IssueKindArg,
97
98 #[arg(short, long, value_enum, default_value = "major")]
100 priority: IssuePriorityArg,
101
102 #[arg(short, long)]
104 assignee: Option<String>,
105
106 #[arg(short, long)]
108 component: Option<String>,
109
110 #[arg(short, long)]
112 milestone: Option<String>,
113
114 #[arg(long)]
116 version: Option<String>,
117 },
118
119 Edit {
121 repo: String,
123
124 id: u64,
126
127 #[arg(short, long)]
129 title: Option<String>,
130
131 #[arg(short = 'b', long)]
133 body: Option<String>,
134
135 #[arg(short, long, value_enum)]
137 kind: Option<IssueKindArg>,
138
139 #[arg(short, long, value_enum)]
141 priority: Option<IssuePriorityArg>,
142
143 #[arg(short, long)]
145 assignee: Option<String>,
146
147 #[arg(short, long, value_enum)]
149 state: Option<IssueStateArg>,
150 },
151
152 Delete {
154 repo: String,
156
157 id: u64,
159
160 #[arg(short, long)]
162 yes: bool,
163 },
164
165 Comment {
167 repo: String,
169
170 id: u64,
172
173 #[arg(short, long)]
175 body: String,
176 },
177
178 Comments {
180 repo: String,
182
183 id: u64,
185
186 #[arg(short, long, default_value = "25")]
188 limit: u32,
189 },
190
191 EditComment {
193 repo: String,
195
196 id: u64,
198
199 comment_id: u64,
201
202 #[arg(short, long)]
204 body: String,
205 },
206
207 DeleteComment {
209 repo: String,
211
212 id: u64,
214
215 comment_id: u64,
217
218 #[arg(short, long)]
220 yes: bool,
221 },
222
223 Changes {
225 repo: String,
227
228 id: u64,
230
231 #[arg(short, long, default_value = "25")]
233 limit: u32,
234 },
235
236 Vote {
238 repo: String,
240
241 id: u64,
243 },
244
245 Unvote {
247 repo: String,
249
250 id: u64,
252 },
253
254 Watch {
256 repo: String,
258
259 id: u64,
261 },
262
263 Unwatch {
265 repo: String,
267
268 id: u64,
270 },
271
272 Components {
274 repo: String,
276 },
277
278 Milestones {
280 repo: String,
282 },
283
284 Versions {
286 repo: String,
288 },
289
290 Attachment {
292 #[command(subcommand)]
293 command: AttachmentCommands,
294 },
295
296 Close {
298 repo: String,
300
301 id: u64,
303 },
304
305 Reopen {
307 repo: String,
309
310 id: u64,
312 },
313}
314
315#[derive(Subcommand)]
316pub enum AttachmentCommands {
317 List {
319 repo: String,
321
322 id: u64,
324 },
325
326 Add {
328 repo: String,
330
331 id: u64,
333
334 #[arg(required = true)]
336 files: Vec<PathBuf>,
337 },
338
339 Delete {
341 repo: String,
343
344 id: u64,
346
347 path: String,
349
350 #[arg(short, long)]
352 yes: bool,
353 },
354}
355
356#[derive(ValueEnum, Clone)]
357pub enum IssueStateArg {
358 New,
359 Open,
360 Resolved,
361 OnHold,
362 Invalid,
363 Duplicate,
364 Wontfix,
365 Closed,
366}
367
368impl From<IssueStateArg> for IssueState {
369 fn from(state: IssueStateArg) -> Self {
370 match state {
371 IssueStateArg::New => IssueState::New,
372 IssueStateArg::Open => IssueState::Open,
373 IssueStateArg::Resolved => IssueState::Resolved,
374 IssueStateArg::OnHold => IssueState::OnHold,
375 IssueStateArg::Invalid => IssueState::Invalid,
376 IssueStateArg::Duplicate => IssueState::Duplicate,
377 IssueStateArg::Wontfix => IssueState::Wontfix,
378 IssueStateArg::Closed => IssueState::Closed,
379 }
380 }
381}
382
383#[derive(ValueEnum, Clone)]
384pub enum IssueKindArg {
385 Bug,
386 Enhancement,
387 Proposal,
388 Task,
389}
390
391impl From<IssueKindArg> for IssueKind {
392 fn from(kind: IssueKindArg) -> Self {
393 match kind {
394 IssueKindArg::Bug => IssueKind::Bug,
395 IssueKindArg::Enhancement => IssueKind::Enhancement,
396 IssueKindArg::Proposal => IssueKind::Proposal,
397 IssueKindArg::Task => IssueKind::Task,
398 }
399 }
400}
401
402#[derive(ValueEnum, Clone)]
403pub enum IssuePriorityArg {
404 Trivial,
405 Minor,
406 Major,
407 Critical,
408 Blocker,
409}
410
411impl From<IssuePriorityArg> for IssuePriority {
412 fn from(priority: IssuePriorityArg) -> Self {
413 match priority {
414 IssuePriorityArg::Trivial => IssuePriority::Trivial,
415 IssuePriorityArg::Minor => IssuePriority::Minor,
416 IssuePriorityArg::Major => IssuePriority::Major,
417 IssuePriorityArg::Critical => IssuePriority::Critical,
418 IssuePriorityArg::Blocker => IssuePriority::Blocker,
419 }
420 }
421}
422
423#[derive(Tabled)]
424struct IssueRow {
425 #[tabled(rename = "ID")]
426 id: u64,
427 #[tabled(rename = "TITLE")]
428 title: String,
429 #[tabled(rename = "STATE")]
430 state: String,
431 #[tabled(rename = "KIND")]
432 kind: String,
433 #[tabled(rename = "PRIORITY")]
434 priority: String,
435}
436
437#[derive(Tabled)]
438struct CommentRow {
439 #[tabled(rename = "ID")]
440 id: u64,
441 #[tabled(rename = "AUTHOR")]
442 author: String,
443 #[tabled(rename = "CREATED")]
444 created: String,
445 #[tabled(rename = "COMMENT")]
446 comment: String,
447}
448
449#[derive(Tabled)]
450struct ChangeRow {
451 #[tabled(rename = "ID")]
452 id: String,
453 #[tabled(rename = "USER")]
454 user: String,
455 #[tabled(rename = "DATE")]
456 date: String,
457 #[tabled(rename = "CHANGED")]
458 changed: String,
459}
460
461#[derive(Tabled)]
462struct MetaRow {
463 #[tabled(rename = "ID")]
464 id: String,
465 #[tabled(rename = "NAME")]
466 name: String,
467}
468
469#[derive(Tabled)]
470struct AttachmentRow {
471 #[tabled(rename = "NAME")]
472 name: String,
473 #[tabled(rename = "LINK")]
474 link: String,
475}
476
477impl IssueCommands {
478 pub async fn run(self) -> Result<()> {
479 match self {
480 IssueCommands::List {
481 repo,
482 state,
483 kind,
484 priority,
485 assignee,
486 reporter,
487 query,
488 sort,
489 page,
490 limit,
491 } => {
492 let (workspace, repo_slug) = parse_repo(&repo)?;
493
494 let capped = capped_limit(limit);
495 if capped != limit && !super::output_json() {
496 println!(
497 "{} Limit capped at {} (the Bitbucket API maximum)",
498 "ℹ".blue(),
499 MAX_LIMIT
500 );
501 }
502
503 let client = BitbucketClient::from_stored().await?;
504
505 let filters = IssueListFilters {
506 state: state.map(Into::into),
507 kind: kind.map(Into::into),
508 priority: priority.map(Into::into),
509 assignee: assignee.as_deref(),
510 reporter: reporter.as_deref(),
511 query: query.as_deref(),
512 sort: sort.as_deref(),
513 page,
514 pagelen: Some(capped),
515 };
516
517 let issues = client
518 .list_issues_filtered(&workspace, &repo_slug, &filters)
519 .await?;
520
521 if super::output_json() {
522 return super::print_json(&issues.values);
523 }
524
525 if issues.values.is_empty() {
526 println!("No issues found");
527 return Ok(());
528 }
529
530 let rows: Vec<IssueRow> = issues
531 .values
532 .iter()
533 .map(|issue| IssueRow {
534 id: issue.id,
535 title: issue.title.chars().take(50).collect(),
536 state: format_state(&issue.state),
537 kind: format!("{}", issue.kind),
538 priority: format_priority(&issue.priority),
539 })
540 .collect();
541
542 let table = Table::new(rows).to_string();
543 println!("{}", table);
544
545 if issues.next.is_some() {
546 println!(
547 "{} More issues available; use --page/--limit to see more.",
548 "ℹ".blue()
549 );
550 }
551
552 Ok(())
553 }
554
555 IssueCommands::View {
556 repo,
557 id,
558 comments,
559 web,
560 } => {
561 let (workspace, repo_slug) = parse_repo(&repo)?;
562 let client = BitbucketClient::from_stored().await?;
563 let issue = client.get_issue(&workspace, &repo_slug, id).await?;
564
565 if web && !super::output_json() {
568 if let Some(links) = &issue.links {
569 if let Some(html) = &links.html {
570 open::that(&html.href)?;
571 println!("Opened {} in browser", html.href.cyan());
572 return Ok(());
573 }
574 }
575 anyhow::bail!("Could not find issue URL");
576 }
577
578 if super::output_json() {
579 if comments {
580 let thread = client
581 .list_issue_comments(&workspace, &repo_slug, id, Some(MAX_LIMIT))
582 .await?;
583 return super::print_json(&serde_json::json!({
584 "issue": issue,
585 "comments": thread.values,
586 }));
587 }
588 return super::print_json(&issue);
589 }
590
591 println!(
592 "{} {} #{}",
593 format_state(&issue.state),
594 issue.title.bold(),
595 issue.id
596 );
597 println!("{}", "─".repeat(60));
598
599 println!("{} {}", "Kind:".dimmed(), issue.kind);
600 println!(
601 "{} {}",
602 "Priority:".dimmed(),
603 format_priority(&issue.priority)
604 );
605
606 if let Some(reporter) = &issue.reporter {
607 println!("{} {}", "Reporter:".dimmed(), reporter.display_name);
608 }
609
610 if let Some(assignee) = &issue.assignee {
611 println!("{} {}", "Assignee:".dimmed(), assignee.display_name);
612 }
613
614 println!(
615 "{} {}",
616 "Created:".dimmed(),
617 issue.created_on.format("%Y-%m-%d %H:%M")
618 );
619
620 if let Some(updated) = issue.updated_on {
621 println!(
622 "{} {}",
623 "Updated:".dimmed(),
624 updated.format("%Y-%m-%d %H:%M")
625 );
626 }
627
628 if let Some(votes) = issue.votes {
629 if votes > 0 {
630 println!("{} {}", "Votes:".dimmed(), votes);
631 }
632 }
633
634 if let Some(content) = &issue.content {
635 if let Some(raw) = &content.raw {
636 if !raw.is_empty() {
637 println!();
638 println!("{}", raw);
639 }
640 }
641 }
642
643 if let Some(links) = &issue.links {
644 if let Some(html) = &links.html {
645 println!();
646 println!("{} {}", "URL:".dimmed(), html.href.cyan());
647 }
648 }
649
650 if comments {
651 let thread = client
652 .list_issue_comments(&workspace, &repo_slug, id, Some(MAX_LIMIT))
653 .await?;
654
655 println!();
656 if thread.values.is_empty() {
657 println!("No comments");
658 } else {
659 println!("{}", format!("Comments ({})", thread.values.len()).bold());
660 for comment in &thread.values {
661 println!("{}", "─".repeat(60));
662 print_comment(comment);
663 }
664 if thread.next.is_some() {
665 println!(
666 "{} More comments available; use 'issue comments' to page through them.",
667 "ℹ".blue()
668 );
669 }
670 }
671 }
672
673 Ok(())
674 }
675
676 IssueCommands::Create {
677 repo,
678 title,
679 body,
680 kind,
681 priority,
682 assignee,
683 component,
684 milestone,
685 version,
686 } => {
687 let (workspace, repo_slug) = parse_repo(&repo)?;
688 let client = BitbucketClient::from_stored().await?;
689
690 let request = CreateIssueRequest {
691 title,
692 content: body.map(|b| IssueContentRequest { raw: b }),
693 kind: Some(kind.into()),
694 priority: Some(priority.into()),
695 assignee: assignee.map(|account_id| UserAccountId { account_id }),
696 component: component.map(|name| ComponentName { name }),
697 milestone: milestone.map(|name| MilestoneName { name }),
698 version: version.map(|name| VersionName { name }),
699 };
700
701 let issue = client
702 .create_issue(&workspace, &repo_slug, &request)
703 .await?;
704
705 if super::output_json() {
706 return super::print_json(&issue);
707 }
708
709 println!("{} Created issue #{}", "✓".green(), issue.id);
710
711 if let Some(links) = &issue.links {
712 if let Some(html) = &links.html {
713 println!("{} {}", "URL:".dimmed(), html.href.cyan());
714 }
715 }
716
717 Ok(())
718 }
719
720 IssueCommands::Edit {
721 repo,
722 id,
723 title,
724 body,
725 kind,
726 priority,
727 assignee,
728 state,
729 } => {
730 let (workspace, repo_slug) = parse_repo(&repo)?;
731
732 let update = IssueUpdate {
733 title: title.as_deref(),
734 content: body.as_deref(),
735 kind: kind.map(Into::into),
736 priority: priority.map(Into::into),
737 assignee: assignee.as_deref(),
738 state: state.map(Into::into),
739 };
740
741 if update.is_empty() {
742 anyhow::bail!(
743 "Nothing to edit: pass at least one of --title, --body, --kind, --priority, --assignee or --state"
744 );
745 }
746
747 let client = BitbucketClient::from_stored().await?;
748 let issue = client
749 .update_issue_full(&workspace, &repo_slug, id, &update)
750 .await?;
751
752 if super::output_json() {
753 return super::print_json(&issue);
754 }
755
756 println!("{} Updated issue #{}", "✓".green(), issue.id);
757
758 Ok(())
759 }
760
761 IssueCommands::Delete { repo, id, yes } => {
762 let (workspace, repo_slug) = parse_repo(&repo)?;
763
764 if !yes
765 && !confirm_or_abort(format!(
766 "Delete issue {} from {}?",
767 format!("#{}", id).red(),
768 repo
769 ))?
770 {
771 return Ok(());
772 }
773
774 let client = BitbucketClient::from_stored().await?;
775 client.delete_issue(&workspace, &repo_slug, id).await?;
776
777 if super::output_json() {
778 return super::print_json(&serde_json::json!({"ok": true}));
779 }
780
781 println!("{} Deleted issue #{}", "✓".green(), id);
782
783 Ok(())
784 }
785
786 IssueCommands::Comment { repo, id, body } => {
787 let (workspace, repo_slug) = parse_repo(&repo)?;
788 let client = BitbucketClient::from_stored().await?;
789
790 let comment = client
791 .add_issue_comment(&workspace, &repo_slug, id, &body)
792 .await?;
793
794 if super::output_json() {
795 return super::print_json(&comment);
796 }
797
798 println!("{} Added comment to issue #{}", "✓".green(), id);
799
800 Ok(())
801 }
802
803 IssueCommands::Comments { repo, id, limit } => {
804 let (workspace, repo_slug) = parse_repo(&repo)?;
805
806 let capped = capped_limit(limit);
807 if capped != limit && !super::output_json() {
808 println!(
809 "{} Limit capped at {} (the Bitbucket API maximum)",
810 "ℹ".blue(),
811 MAX_LIMIT
812 );
813 }
814
815 let client = BitbucketClient::from_stored().await?;
816 let comments = client
817 .list_issue_comments(&workspace, &repo_slug, id, Some(capped))
818 .await?;
819
820 if super::output_json() {
821 return super::print_json(&comments.values);
822 }
823
824 if comments.values.is_empty() {
825 println!("No comments found on issue #{}", id);
826 return Ok(());
827 }
828
829 let rows: Vec<CommentRow> = comments
830 .values
831 .iter()
832 .map(|comment| CommentRow {
833 id: comment.id,
834 author: comment.user.display_name.clone(),
835 created: comment.created_on.format("%Y-%m-%d %H:%M").to_string(),
836 comment: summarize_text(comment.content.raw.as_deref()),
837 })
838 .collect();
839
840 let table = Table::new(rows).to_string();
841 println!("{}", table);
842
843 if comments.next.is_some() {
844 println!(
845 "{} More comments available; use --limit to see more.",
846 "ℹ".blue()
847 );
848 }
849
850 Ok(())
851 }
852
853 IssueCommands::EditComment {
854 repo,
855 id,
856 comment_id,
857 body,
858 } => {
859 let (workspace, repo_slug) = parse_repo(&repo)?;
860 let client = BitbucketClient::from_stored().await?;
861
862 let comment = client
863 .update_issue_comment(&workspace, &repo_slug, id, comment_id, &body)
864 .await?;
865
866 if super::output_json() {
867 return super::print_json(&comment);
868 }
869
870 println!(
871 "{} Updated comment {} on issue #{}",
872 "✓".green(),
873 comment_id,
874 id
875 );
876
877 Ok(())
878 }
879
880 IssueCommands::DeleteComment {
881 repo,
882 id,
883 comment_id,
884 yes,
885 } => {
886 let (workspace, repo_slug) = parse_repo(&repo)?;
887
888 if !yes
889 && !confirm_or_abort(format!(
890 "Delete comment {} from issue #{} in {}?",
891 comment_id.to_string().red(),
892 id,
893 repo
894 ))?
895 {
896 return Ok(());
897 }
898
899 let client = BitbucketClient::from_stored().await?;
900 client
901 .delete_issue_comment(&workspace, &repo_slug, id, comment_id)
902 .await?;
903
904 if super::output_json() {
905 return super::print_json(&serde_json::json!({"ok": true}));
906 }
907
908 println!(
909 "{} Deleted comment {} from issue #{}",
910 "✓".green(),
911 comment_id,
912 id
913 );
914
915 Ok(())
916 }
917
918 IssueCommands::Changes { repo, id, limit } => {
919 let (workspace, repo_slug) = parse_repo(&repo)?;
920
921 let capped = capped_limit(limit);
922 if capped != limit && !super::output_json() {
923 println!(
924 "{} Limit capped at {} (the Bitbucket API maximum)",
925 "ℹ".blue(),
926 MAX_LIMIT
927 );
928 }
929
930 let client = BitbucketClient::from_stored().await?;
931 let changes = client
932 .list_issue_changes(&workspace, &repo_slug, id, Some(capped))
933 .await?;
934
935 if super::output_json() {
936 return super::print_json(&changes.values);
937 }
938
939 if changes.values.is_empty() {
940 println!("No changes found for issue #{}", id);
941 return Ok(());
942 }
943
944 let rows: Vec<ChangeRow> = changes.values.iter().map(change_row).collect();
945
946 let table = Table::new(rows).to_string();
947 println!("{}", table);
948
949 if changes.next.is_some() {
950 println!(
951 "{} More changes available; use --limit to see more.",
952 "ℹ".blue()
953 );
954 }
955
956 Ok(())
957 }
958
959 IssueCommands::Vote { repo, id } => {
960 let (workspace, repo_slug) = parse_repo(&repo)?;
961 let client = BitbucketClient::from_stored().await?;
962
963 client.vote_issue(&workspace, &repo_slug, id).await?;
964
965 if super::output_json() {
966 return super::print_json(&serde_json::json!({"ok": true}));
967 }
968
969 println!("{} Voted for issue #{}", "✓".green(), id);
970
971 Ok(())
972 }
973
974 IssueCommands::Unvote { repo, id } => {
975 let (workspace, repo_slug) = parse_repo(&repo)?;
976 let client = BitbucketClient::from_stored().await?;
977
978 client.unvote_issue(&workspace, &repo_slug, id).await?;
979
980 if super::output_json() {
981 return super::print_json(&serde_json::json!({"ok": true}));
982 }
983
984 println!("{} Removed vote from issue #{}", "✓".green(), id);
985
986 Ok(())
987 }
988
989 IssueCommands::Watch { repo, id } => {
990 let (workspace, repo_slug) = parse_repo(&repo)?;
991 let client = BitbucketClient::from_stored().await?;
992
993 client.watch_issue(&workspace, &repo_slug, id).await?;
994
995 if super::output_json() {
996 return super::print_json(&serde_json::json!({"ok": true}));
997 }
998
999 println!("{} Watching issue #{}", "✓".green(), id);
1000
1001 Ok(())
1002 }
1003
1004 IssueCommands::Unwatch { repo, id } => {
1005 let (workspace, repo_slug) = parse_repo(&repo)?;
1006 let client = BitbucketClient::from_stored().await?;
1007
1008 client.unwatch_issue(&workspace, &repo_slug, id).await?;
1009
1010 if super::output_json() {
1011 return super::print_json(&serde_json::json!({"ok": true}));
1012 }
1013
1014 println!("{} Stopped watching issue #{}", "✓".green(), id);
1015
1016 Ok(())
1017 }
1018
1019 IssueCommands::Components { repo } => {
1020 let (workspace, repo_slug) = parse_repo(&repo)?;
1021 let client = BitbucketClient::from_stored().await?;
1022 let items = client.list_issue_components(&workspace, &repo_slug).await?;
1023
1024 if super::output_json() {
1025 return super::print_json(&items);
1026 }
1027
1028 print_meta_items(&items, "components");
1029
1030 Ok(())
1031 }
1032
1033 IssueCommands::Milestones { repo } => {
1034 let (workspace, repo_slug) = parse_repo(&repo)?;
1035 let client = BitbucketClient::from_stored().await?;
1036 let items = client.list_issue_milestones(&workspace, &repo_slug).await?;
1037
1038 if super::output_json() {
1039 return super::print_json(&items);
1040 }
1041
1042 print_meta_items(&items, "milestones");
1043
1044 Ok(())
1045 }
1046
1047 IssueCommands::Versions { repo } => {
1048 let (workspace, repo_slug) = parse_repo(&repo)?;
1049 let client = BitbucketClient::from_stored().await?;
1050 let items = client.list_issue_versions(&workspace, &repo_slug).await?;
1051
1052 if super::output_json() {
1053 return super::print_json(&items);
1054 }
1055
1056 print_meta_items(&items, "versions");
1057
1058 Ok(())
1059 }
1060
1061 IssueCommands::Attachment { command } => command.run().await,
1062
1063 IssueCommands::Close { repo, id } => {
1064 let (workspace, repo_slug) = parse_repo(&repo)?;
1065 let client = BitbucketClient::from_stored().await?;
1066
1067 let issue = client
1068 .update_issue(
1069 &workspace,
1070 &repo_slug,
1071 id,
1072 None,
1073 None,
1074 Some(IssueState::Closed),
1075 )
1076 .await?;
1077
1078 if super::output_json() {
1079 return super::print_json(&issue);
1080 }
1081
1082 println!("{} Closed issue #{}", "✓".green(), id);
1083
1084 Ok(())
1085 }
1086
1087 IssueCommands::Reopen { repo, id } => {
1088 let (workspace, repo_slug) = parse_repo(&repo)?;
1089 let client = BitbucketClient::from_stored().await?;
1090
1091 let issue = client
1092 .update_issue(
1093 &workspace,
1094 &repo_slug,
1095 id,
1096 None,
1097 None,
1098 Some(IssueState::Open),
1099 )
1100 .await?;
1101
1102 if super::output_json() {
1103 return super::print_json(&issue);
1104 }
1105
1106 println!("{} Reopened issue #{}", "✓".green(), id);
1107
1108 Ok(())
1109 }
1110 }
1111 }
1112}
1113
1114impl AttachmentCommands {
1115 pub async fn run(self) -> Result<()> {
1116 match self {
1117 AttachmentCommands::List { repo, id } => {
1118 let (workspace, repo_slug) = parse_repo(&repo)?;
1119 let client = BitbucketClient::from_stored().await?;
1120 let attachments = client
1121 .list_issue_attachments(&workspace, &repo_slug, id)
1122 .await?;
1123
1124 if super::output_json() {
1125 return super::print_json(&attachments);
1126 }
1127
1128 if attachments.is_empty() {
1129 println!("No attachments found on issue #{}", id);
1130 return Ok(());
1131 }
1132
1133 let rows: Vec<AttachmentRow> = attachments
1134 .iter()
1135 .map(|attachment| AttachmentRow {
1136 name: attachment.name.clone().unwrap_or_else(|| "-".to_string()),
1137 link: attachment_link(attachment),
1138 })
1139 .collect();
1140
1141 let table = Table::new(rows).to_string();
1142 println!("{}", table);
1143
1144 Ok(())
1145 }
1146
1147 AttachmentCommands::Add { repo, id, files } => {
1148 let (workspace, repo_slug) = parse_repo(&repo)?;
1149
1150 let uploads: Vec<(String, PathBuf)> = files
1153 .iter()
1154 .map(|p| Ok((attachment_name_for(p)?, p.clone())))
1155 .collect::<Result<_>>()?;
1156
1157 let mut seen = HashSet::new();
1161 for (name, _) in &uploads {
1162 if !seen.insert(name.as_str()) {
1163 anyhow::bail!(
1164 "Duplicate attachment name '{}': multiple input files share this filename; Bitbucket stores attachments by filename, so one would overwrite the other",
1165 name
1166 );
1167 }
1168 }
1169
1170 let client = BitbucketClient::from_stored().await?;
1171 client
1172 .upload_issue_attachments(&workspace, &repo_slug, id, &uploads)
1173 .await?;
1174
1175 if super::output_json() {
1176 return super::print_json(&serde_json::json!({"ok": true}));
1177 }
1178
1179 for (name, _) in &uploads {
1180 println!("{} Attached {} to issue #{}", "✓".green(), name.cyan(), id);
1181 }
1182
1183 Ok(())
1184 }
1185
1186 AttachmentCommands::Delete {
1187 repo,
1188 id,
1189 path,
1190 yes,
1191 } => {
1192 let (workspace, repo_slug) = parse_repo(&repo)?;
1193
1194 if !yes
1195 && !confirm_or_abort(format!(
1196 "Delete attachment {} from issue #{} in {}?",
1197 path.red(),
1198 id,
1199 repo
1200 ))?
1201 {
1202 return Ok(());
1203 }
1204
1205 let client = BitbucketClient::from_stored().await?;
1206 client
1207 .delete_issue_attachment(&workspace, &repo_slug, id, &path)
1208 .await?;
1209
1210 if super::output_json() {
1211 return super::print_json(&serde_json::json!({"ok": true}));
1212 }
1213
1214 println!(
1215 "{} Deleted attachment {} from issue #{}",
1216 "✓".green(),
1217 path,
1218 id
1219 );
1220
1221 Ok(())
1222 }
1223 }
1224 }
1225}
1226
1227fn format_state(state: &IssueState) -> String {
1228 match state {
1229 IssueState::New => "NEW".cyan().to_string(),
1230 IssueState::Open => "OPEN".green().to_string(),
1231 IssueState::Resolved => "RESOLVED".blue().to_string(),
1232 IssueState::OnHold => "ON HOLD".yellow().to_string(),
1233 IssueState::Invalid => "INVALID".dimmed().to_string(),
1234 IssueState::Duplicate => "DUPLICATE".dimmed().to_string(),
1235 IssueState::Wontfix => "WONTFIX".dimmed().to_string(),
1236 IssueState::Closed => "CLOSED".purple().to_string(),
1237 }
1238}
1239
1240fn format_priority(priority: &IssuePriority) -> String {
1241 match priority {
1242 IssuePriority::Trivial => "trivial".dimmed().to_string(),
1243 IssuePriority::Minor => "minor".normal().to_string(),
1244 IssuePriority::Major => "major".yellow().to_string(),
1245 IssuePriority::Critical => "critical".red().to_string(),
1246 IssuePriority::Blocker => "blocker".red().bold().to_string(),
1247 }
1248}
1249
1250fn print_comment(comment: &IssueComment) {
1252 println!(
1253 "{} {} {}",
1254 format!("#{}", comment.id).dimmed(),
1255 comment.user.display_name.bold(),
1256 comment
1257 .created_on
1258 .format("%Y-%m-%d %H:%M")
1259 .to_string()
1260 .dimmed()
1261 );
1262 if let Some(raw) = &comment.content.raw {
1263 if !raw.is_empty() {
1264 println!("{}", raw);
1265 }
1266 }
1267}
1268
1269fn summarize_text(raw: Option<&str>) -> String {
1272 let flattened = raw
1273 .unwrap_or("")
1274 .split_whitespace()
1275 .collect::<Vec<_>>()
1276 .join(" ");
1277
1278 if flattened.is_empty() {
1279 return "-".to_string();
1280 }
1281
1282 flattened.chars().take(60).collect()
1283}
1284
1285fn change_row(change: &IssueChange) -> ChangeRow {
1288 ChangeRow {
1289 id: change
1290 .id
1291 .map(|v| v.to_string())
1292 .unwrap_or_else(|| "-".to_string()),
1293 user: change
1294 .user
1295 .as_ref()
1296 .map(|u| u.display_name.clone())
1297 .unwrap_or_else(|| "-".to_string()),
1298 date: change
1299 .created_on
1300 .map(|d| d.format("%Y-%m-%d %H:%M").to_string())
1301 .unwrap_or_else(|| "-".to_string()),
1302 changed: changed_keys(change),
1303 }
1304}
1305
1306fn changed_keys(change: &IssueChange) -> String {
1308 let keys = change
1309 .changes
1310 .as_ref()
1311 .and_then(|v| v.as_object())
1312 .map(|obj| obj.keys().cloned().collect::<Vec<_>>().join(", "))
1313 .unwrap_or_default();
1314
1315 if keys.is_empty() {
1316 "-".to_string()
1317 } else {
1318 keys
1319 }
1320}
1321
1322fn print_meta_items(items: &[IssueMetaItem], noun: &str) {
1324 if items.is_empty() {
1325 println!("No {} found", noun);
1326 return;
1327 }
1328
1329 let rows: Vec<MetaRow> = items
1330 .iter()
1331 .map(|item| MetaRow {
1332 id: item
1333 .id
1334 .map(|v| v.to_string())
1335 .unwrap_or_else(|| "-".to_string()),
1336 name: item.name.clone().unwrap_or_else(|| "-".to_string()),
1337 })
1338 .collect();
1339
1340 println!("{}", Table::new(rows));
1341}
1342
1343fn attachment_link(attachment: &IssueAttachment) -> String {
1346 match attachment
1347 .links
1348 .as_ref()
1349 .and_then(|links| links.pointer("/self/href"))
1350 {
1351 Some(serde_json::Value::String(s)) => s.clone(),
1352 Some(serde_json::Value::Array(hrefs)) => hrefs
1353 .iter()
1354 .filter_map(|v| v.as_str())
1355 .next()
1356 .map(str::to_string)
1357 .unwrap_or_else(|| "-".to_string()),
1358 _ => "-".to_string(),
1359 }
1360}
1361
1362fn attachment_name_for(path: &Path) -> Result<String> {
1365 path.file_name()
1366 .and_then(|n| n.to_str())
1367 .map(|s| s.to_string())
1368 .with_context(|| format!("Could not determine a file name for '{}'", path.display()))
1369}
1370
1371#[cfg(test)]
1372mod tests {
1373 use super::*;
1374
1375 #[test]
1376 fn summarize_text_flattens_newlines_and_truncates() {
1377 assert_eq!(summarize_text(Some("a\nb\tc")), "a b c");
1378 assert_eq!(summarize_text(None), "-");
1379 assert_eq!(summarize_text(Some(" ")), "-");
1380 let long = "x".repeat(80);
1381 assert_eq!(summarize_text(Some(&long)).chars().count(), 60);
1382 }
1383
1384 #[test]
1385 fn attachment_link_handles_string_and_array_hrefs() {
1386 let string_href = IssueAttachment {
1387 name: Some("a.png".to_string()),
1388 links: Some(serde_json::json!({"self": {"href": "https://x/a.png"}})),
1389 };
1390 assert_eq!(attachment_link(&string_href), "https://x/a.png");
1391
1392 let array_href = IssueAttachment {
1393 name: Some("b.png".to_string()),
1394 links: Some(
1395 serde_json::json!({"self": {"href": ["https://x/b.png", "https://y/b.png"]}}),
1396 ),
1397 };
1398 assert_eq!(attachment_link(&array_href), "https://x/b.png");
1399
1400 let missing = IssueAttachment {
1401 name: None,
1402 links: None,
1403 };
1404 assert_eq!(attachment_link(&missing), "-");
1405 }
1406
1407 #[test]
1408 fn changed_keys_joins_field_names_of_a_change_entry() {
1409 let change = IssueChange {
1410 id: Some(1),
1411 user: None,
1412 message: None,
1413 created_on: None,
1414 changes: Some(serde_json::json!({
1415 "state": {"old": "new", "new": "open"},
1416 "assignee": {"old": "", "new": "someone"},
1417 })),
1418 };
1419 assert_eq!(changed_keys(&change), "assignee, state");
1420
1421 let empty = IssueChange {
1422 id: None,
1423 user: None,
1424 message: None,
1425 created_on: None,
1426 changes: None,
1427 };
1428 assert_eq!(changed_keys(&empty), "-");
1429 }
1430
1431 #[test]
1432 fn attachment_name_for_extracts_basename_and_errors_without_one() {
1433 assert_eq!(
1434 attachment_name_for(Path::new("/some/dir/shot.png")).unwrap(),
1435 "shot.png"
1436 );
1437 assert_eq!(
1438 attachment_name_for(Path::new("shot.png")).unwrap(),
1439 "shot.png"
1440 );
1441 assert!(attachment_name_for(Path::new("..")).is_err());
1443 }
1444
1445 #[test]
1446 fn change_row_renders_populated_and_empty_changes() {
1447 let user = crate::models::User {
1448 uuid: "u-1".to_string(),
1449 username: None,
1450 display_name: "Alice".to_string(),
1451 account_id: None,
1452 user_type: "user".to_string(),
1453 links: None,
1454 };
1455 let created: chrono::DateTime<chrono::Utc> = "2024-01-15T10:30:00Z".parse().unwrap();
1456 let populated = IssueChange {
1457 id: Some(7),
1458 user: Some(user),
1459 message: None,
1460 created_on: Some(created),
1461 changes: Some(serde_json::json!({"state": {"old": "new", "new": "open"}})),
1462 };
1463 let row = change_row(&populated);
1464 assert_eq!(row.id, "7");
1465 assert_eq!(row.user, "Alice");
1466 assert_eq!(row.date, "2024-01-15 10:30");
1467 assert_eq!(row.changed, "state");
1468
1469 let empty = IssueChange {
1470 id: None,
1471 user: None,
1472 message: None,
1473 created_on: None,
1474 changes: None,
1475 };
1476 let row = change_row(&empty);
1477 assert_eq!(row.id, "-");
1478 assert_eq!(row.user, "-");
1479 assert_eq!(row.date, "-");
1480 assert_eq!(row.changed, "-");
1481 }
1482}