Skip to main content

bitbucket_cli/cli/
issue.rs

1use anyhow::Result;
2use clap::{Subcommand, ValueEnum};
3use colored::Colorize;
4use tabled::{Table, Tabled};
5
6use super::parse_repo;
7use crate::api::BitbucketClient;
8use crate::models::{
9    CreateIssueRequest, IssueContentRequest, IssueKind, IssuePriority, IssueState,
10};
11
12#[derive(Subcommand)]
13pub enum IssueCommands {
14    /// List issues
15    List {
16        /// Repository in format workspace/repo-slug
17        repo: String,
18
19        /// Filter by state
20        #[arg(short, long, value_enum)]
21        state: Option<IssueStateArg>,
22
23        /// Number of results
24        #[arg(short, long, default_value = "25")]
25        limit: u32,
26    },
27
28    /// View issue details
29    View {
30        /// Repository in format workspace/repo-slug
31        repo: String,
32
33        /// Issue ID
34        id: u64,
35
36        /// Open in browser
37        #[arg(short, long)]
38        web: bool,
39    },
40
41    /// Create a new issue
42    Create {
43        /// Repository in format workspace/repo-slug
44        repo: String,
45
46        /// Issue title
47        #[arg(short, long)]
48        title: String,
49
50        /// Issue description
51        #[arg(short = 'b', long)]
52        body: Option<String>,
53
54        /// Issue type
55        #[arg(short, long, value_enum, default_value = "bug")]
56        kind: IssueKindArg,
57
58        /// Issue priority
59        #[arg(short, long, value_enum, default_value = "major")]
60        priority: IssuePriorityArg,
61    },
62
63    /// Add a comment to an issue
64    Comment {
65        /// Repository in format workspace/repo-slug
66        repo: String,
67
68        /// Issue ID
69        id: u64,
70
71        /// Comment text
72        #[arg(short, long)]
73        body: String,
74    },
75
76    /// Close an issue
77    Close {
78        /// Repository in format workspace/repo-slug
79        repo: String,
80
81        /// Issue ID
82        id: u64,
83    },
84
85    /// Reopen an issue
86    Reopen {
87        /// Repository in format workspace/repo-slug
88        repo: String,
89
90        /// Issue ID
91        id: u64,
92    },
93}
94
95#[derive(ValueEnum, Clone)]
96pub enum IssueStateArg {
97    New,
98    Open,
99    Resolved,
100    OnHold,
101    Invalid,
102    Duplicate,
103    Wontfix,
104    Closed,
105}
106
107impl From<IssueStateArg> for IssueState {
108    fn from(state: IssueStateArg) -> Self {
109        match state {
110            IssueStateArg::New => IssueState::New,
111            IssueStateArg::Open => IssueState::Open,
112            IssueStateArg::Resolved => IssueState::Resolved,
113            IssueStateArg::OnHold => IssueState::OnHold,
114            IssueStateArg::Invalid => IssueState::Invalid,
115            IssueStateArg::Duplicate => IssueState::Duplicate,
116            IssueStateArg::Wontfix => IssueState::Wontfix,
117            IssueStateArg::Closed => IssueState::Closed,
118        }
119    }
120}
121
122#[derive(ValueEnum, Clone)]
123pub enum IssueKindArg {
124    Bug,
125    Enhancement,
126    Proposal,
127    Task,
128}
129
130impl From<IssueKindArg> for IssueKind {
131    fn from(kind: IssueKindArg) -> Self {
132        match kind {
133            IssueKindArg::Bug => IssueKind::Bug,
134            IssueKindArg::Enhancement => IssueKind::Enhancement,
135            IssueKindArg::Proposal => IssueKind::Proposal,
136            IssueKindArg::Task => IssueKind::Task,
137        }
138    }
139}
140
141#[derive(ValueEnum, Clone)]
142pub enum IssuePriorityArg {
143    Trivial,
144    Minor,
145    Major,
146    Critical,
147    Blocker,
148}
149
150impl From<IssuePriorityArg> for IssuePriority {
151    fn from(priority: IssuePriorityArg) -> Self {
152        match priority {
153            IssuePriorityArg::Trivial => IssuePriority::Trivial,
154            IssuePriorityArg::Minor => IssuePriority::Minor,
155            IssuePriorityArg::Major => IssuePriority::Major,
156            IssuePriorityArg::Critical => IssuePriority::Critical,
157            IssuePriorityArg::Blocker => IssuePriority::Blocker,
158        }
159    }
160}
161
162#[derive(Tabled)]
163struct IssueRow {
164    #[tabled(rename = "ID")]
165    id: u64,
166    #[tabled(rename = "TITLE")]
167    title: String,
168    #[tabled(rename = "STATE")]
169    state: String,
170    #[tabled(rename = "KIND")]
171    kind: String,
172    #[tabled(rename = "PRIORITY")]
173    priority: String,
174}
175
176impl IssueCommands {
177    pub async fn run(self) -> Result<()> {
178        match self {
179            IssueCommands::List { repo, state, limit } => {
180                let (workspace, repo_slug) = parse_repo(&repo)?;
181                let client = BitbucketClient::from_stored().await?;
182
183                let issues = client
184                    .list_issues(
185                        &workspace,
186                        &repo_slug,
187                        state.map(|s| s.into()),
188                        None,
189                        Some(limit),
190                    )
191                    .await?;
192
193                if issues.values.is_empty() {
194                    println!("No issues found");
195                    return Ok(());
196                }
197
198                let rows: Vec<IssueRow> = issues
199                    .values
200                    .iter()
201                    .map(|issue| IssueRow {
202                        id: issue.id,
203                        title: issue.title.chars().take(50).collect(),
204                        state: format_state(&issue.state),
205                        kind: format!("{}", issue.kind),
206                        priority: format_priority(&issue.priority),
207                    })
208                    .collect();
209
210                let table = Table::new(rows).to_string();
211                println!("{}", table);
212
213                Ok(())
214            }
215
216            IssueCommands::View { repo, id, web } => {
217                let (workspace, repo_slug) = parse_repo(&repo)?;
218                let client = BitbucketClient::from_stored().await?;
219                let issue = client.get_issue(&workspace, &repo_slug, id).await?;
220
221                if web {
222                    if let Some(links) = &issue.links {
223                        if let Some(html) = &links.html {
224                            open::that(&html.href)?;
225                            println!("Opened {} in browser", html.href.cyan());
226                            return Ok(());
227                        }
228                    }
229                    anyhow::bail!("Could not find issue URL");
230                }
231
232                println!(
233                    "{} {} #{}",
234                    format_state(&issue.state),
235                    issue.title.bold(),
236                    issue.id
237                );
238                println!("{}", "─".repeat(60));
239
240                println!("{} {}", "Kind:".dimmed(), issue.kind);
241                println!(
242                    "{} {}",
243                    "Priority:".dimmed(),
244                    format_priority(&issue.priority)
245                );
246
247                if let Some(reporter) = &issue.reporter {
248                    println!("{} {}", "Reporter:".dimmed(), reporter.display_name);
249                }
250
251                if let Some(assignee) = &issue.assignee {
252                    println!("{} {}", "Assignee:".dimmed(), assignee.display_name);
253                }
254
255                println!(
256                    "{} {}",
257                    "Created:".dimmed(),
258                    issue.created_on.format("%Y-%m-%d %H:%M")
259                );
260
261                if let Some(updated) = issue.updated_on {
262                    println!(
263                        "{} {}",
264                        "Updated:".dimmed(),
265                        updated.format("%Y-%m-%d %H:%M")
266                    );
267                }
268
269                if let Some(votes) = issue.votes {
270                    if votes > 0 {
271                        println!("{} {}", "Votes:".dimmed(), votes);
272                    }
273                }
274
275                if let Some(content) = &issue.content {
276                    if let Some(raw) = &content.raw {
277                        if !raw.is_empty() {
278                            println!();
279                            println!("{}", raw);
280                        }
281                    }
282                }
283
284                if let Some(links) = &issue.links {
285                    if let Some(html) = &links.html {
286                        println!();
287                        println!("{} {}", "URL:".dimmed(), html.href.cyan());
288                    }
289                }
290
291                Ok(())
292            }
293
294            IssueCommands::Create {
295                repo,
296                title,
297                body,
298                kind,
299                priority,
300            } => {
301                let (workspace, repo_slug) = parse_repo(&repo)?;
302                let client = BitbucketClient::from_stored().await?;
303
304                let request = CreateIssueRequest {
305                    title,
306                    content: body.map(|b| IssueContentRequest { raw: b }),
307                    kind: Some(kind.into()),
308                    priority: Some(priority.into()),
309                    assignee: None,
310                    component: None,
311                    milestone: None,
312                    version: None,
313                };
314
315                let issue = client
316                    .create_issue(&workspace, &repo_slug, &request)
317                    .await?;
318
319                println!("{} Created issue #{}", "✓".green(), issue.id);
320
321                if let Some(links) = &issue.links {
322                    if let Some(html) = &links.html {
323                        println!("{} {}", "URL:".dimmed(), html.href.cyan());
324                    }
325                }
326
327                Ok(())
328            }
329
330            IssueCommands::Comment { repo, id, body } => {
331                let (workspace, repo_slug) = parse_repo(&repo)?;
332                let client = BitbucketClient::from_stored().await?;
333
334                client
335                    .add_issue_comment(&workspace, &repo_slug, id, &body)
336                    .await?;
337
338                println!("{} Added comment to issue #{}", "✓".green(), id);
339
340                Ok(())
341            }
342
343            IssueCommands::Close { repo, id } => {
344                let (workspace, repo_slug) = parse_repo(&repo)?;
345                let client = BitbucketClient::from_stored().await?;
346
347                client
348                    .update_issue(
349                        &workspace,
350                        &repo_slug,
351                        id,
352                        None,
353                        None,
354                        Some(IssueState::Closed),
355                    )
356                    .await?;
357
358                println!("{} Closed issue #{}", "✓".green(), id);
359
360                Ok(())
361            }
362
363            IssueCommands::Reopen { repo, id } => {
364                let (workspace, repo_slug) = parse_repo(&repo)?;
365                let client = BitbucketClient::from_stored().await?;
366
367                client
368                    .update_issue(
369                        &workspace,
370                        &repo_slug,
371                        id,
372                        None,
373                        None,
374                        Some(IssueState::Open),
375                    )
376                    .await?;
377
378                println!("{} Reopened issue #{}", "✓".green(), id);
379
380                Ok(())
381            }
382        }
383    }
384}
385
386fn format_state(state: &IssueState) -> String {
387    match state {
388        IssueState::New => "NEW".cyan().to_string(),
389        IssueState::Open => "OPEN".green().to_string(),
390        IssueState::Resolved => "RESOLVED".blue().to_string(),
391        IssueState::OnHold => "ON HOLD".yellow().to_string(),
392        IssueState::Invalid => "INVALID".dimmed().to_string(),
393        IssueState::Duplicate => "DUPLICATE".dimmed().to_string(),
394        IssueState::Wontfix => "WONTFIX".dimmed().to_string(),
395        IssueState::Closed => "CLOSED".purple().to_string(),
396    }
397}
398
399fn format_priority(priority: &IssuePriority) -> String {
400    match priority {
401        IssuePriority::Trivial => "trivial".dimmed().to_string(),
402        IssuePriority::Minor => "minor".normal().to_string(),
403        IssuePriority::Major => "major".yellow().to_string(),
404        IssuePriority::Critical => "critical".red().to_string(),
405        IssuePriority::Blocker => "blocker".red().bold().to_string(),
406    }
407}