1use std::path::PathBuf;
2
3use anyhow::{Context, Result};
4use reqwest::multipart::{Form, Part};
5
6use super::BitbucketClient;
7use crate::api::util::urlencode_segment;
8use crate::models::{
9 CreateIssueCommentRequest, CreateIssueRequest, Issue, IssueAttachment, IssueChange,
10 IssueComment, IssueContentRequest, IssueKind, IssueMetaItem, IssuePriority, IssueState,
11 Paginated, UserAccountId,
12};
13
14#[derive(Default)]
17pub struct IssueUpdate<'a> {
18 pub title: Option<&'a str>,
19 pub content: Option<&'a str>,
21 pub kind: Option<IssueKind>,
22 pub priority: Option<IssuePriority>,
23 pub assignee: Option<&'a str>,
25 pub state: Option<IssueState>,
26}
27
28impl IssueUpdate<'_> {
29 pub fn is_empty(&self) -> bool {
31 self.title.is_none()
32 && self.content.is_none()
33 && self.kind.is_none()
34 && self.priority.is_none()
35 && self.assignee.is_none()
36 && self.state.is_none()
37 }
38}
39
40#[derive(Default)]
42pub(crate) struct IssueListFilters<'a> {
43 pub state: Option<IssueState>,
44 pub kind: Option<IssueKind>,
45 pub priority: Option<IssuePriority>,
46 pub assignee: Option<&'a str>,
48 pub reporter: Option<&'a str>,
50 pub query: Option<&'a str>,
52 pub sort: Option<&'a str>,
54 pub page: Option<u32>,
55 pub pagelen: Option<u32>,
56}
57
58impl BitbucketClient {
59 pub async fn list_issues(
61 &self,
62 workspace: &str,
63 repo_slug: &str,
64 state: Option<IssueState>,
65 page: Option<u32>,
66 pagelen: Option<u32>,
67 ) -> Result<Paginated<Issue>> {
68 self.list_issues_filtered(
69 workspace,
70 repo_slug,
71 &IssueListFilters {
72 state,
73 page,
74 pagelen,
75 ..Default::default()
76 },
77 )
78 .await
79 }
80
81 pub(crate) async fn list_issues_filtered(
84 &self,
85 workspace: &str,
86 repo_slug: &str,
87 filters: &IssueListFilters<'_>,
88 ) -> Result<Paginated<Issue>> {
89 let query = issue_list_query_full(filters);
90 let query_refs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
91
92 let path = format!("/repositories/{}/{}/issues", workspace, repo_slug);
93 self.get_with_query(&path, &query_refs).await
94 }
95
96 pub async fn get_issue(
98 &self,
99 workspace: &str,
100 repo_slug: &str,
101 issue_id: u64,
102 ) -> Result<Issue> {
103 let path = format!(
104 "/repositories/{}/{}/issues/{}",
105 workspace, repo_slug, issue_id
106 );
107 self.get(&path).await
108 }
109
110 pub async fn create_issue(
112 &self,
113 workspace: &str,
114 repo_slug: &str,
115 request: &CreateIssueRequest,
116 ) -> Result<Issue> {
117 let path = format!("/repositories/{}/{}/issues", workspace, repo_slug);
118 self.post(&path, request).await
119 }
120
121 pub async fn update_issue(
126 &self,
127 workspace: &str,
128 repo_slug: &str,
129 issue_id: u64,
130 title: Option<&str>,
131 content: Option<&str>,
132 state: Option<IssueState>,
133 ) -> Result<Issue> {
134 self.update_issue_full(
135 workspace,
136 repo_slug,
137 issue_id,
138 &IssueUpdate {
139 title,
140 content,
141 state,
142 ..Default::default()
143 },
144 )
145 .await
146 }
147
148 pub async fn update_issue_full(
151 &self,
152 workspace: &str,
153 repo_slug: &str,
154 issue_id: u64,
155 update: &IssueUpdate<'_>,
156 ) -> Result<Issue> {
157 #[derive(serde::Serialize)]
158 struct UpdateRequest<'a> {
159 #[serde(skip_serializing_if = "Option::is_none")]
160 title: Option<&'a str>,
161 #[serde(skip_serializing_if = "Option::is_none")]
162 content: Option<IssueContentRequest>,
163 #[serde(skip_serializing_if = "Option::is_none")]
164 kind: Option<&'a IssueKind>,
165 #[serde(skip_serializing_if = "Option::is_none")]
166 priority: Option<&'a IssuePriority>,
167 #[serde(skip_serializing_if = "Option::is_none")]
168 assignee: Option<UserAccountId>,
169 #[serde(skip_serializing_if = "Option::is_none")]
170 state: Option<&'a IssueState>,
171 }
172
173 let request = UpdateRequest {
174 title: update.title,
175 content: update
176 .content
177 .map(|c| IssueContentRequest { raw: c.to_string() }),
178 kind: update.kind.as_ref(),
179 priority: update.priority.as_ref(),
180 assignee: update.assignee.map(|a| UserAccountId {
181 account_id: a.to_string(),
182 }),
183 state: update.state.as_ref(),
184 };
185
186 let path = format!(
187 "/repositories/{}/{}/issues/{}",
188 workspace, repo_slug, issue_id
189 );
190 self.put(&path, &request).await
191 }
192
193 pub async fn delete_issue(
195 &self,
196 workspace: &str,
197 repo_slug: &str,
198 issue_id: u64,
199 ) -> Result<()> {
200 let path = format!(
201 "/repositories/{}/{}/issues/{}",
202 workspace, repo_slug, issue_id
203 );
204 self.delete(&path).await
205 }
206
207 pub async fn list_issue_comments(
209 &self,
210 workspace: &str,
211 repo_slug: &str,
212 issue_id: u64,
213 pagelen: Option<u32>,
214 ) -> Result<Paginated<IssueComment>> {
215 let query: Vec<(&str, String)> = pagelen
216 .map(|len| ("pagelen", len.to_string()))
217 .into_iter()
218 .collect();
219 let query_refs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
220
221 let path = format!(
222 "/repositories/{}/{}/issues/{}/comments",
223 workspace, repo_slug, issue_id
224 );
225 self.get_with_query(&path, &query_refs).await
226 }
227
228 pub async fn add_issue_comment(
230 &self,
231 workspace: &str,
232 repo_slug: &str,
233 issue_id: u64,
234 content: &str,
235 ) -> Result<IssueComment> {
236 let request = CreateIssueCommentRequest {
237 content: IssueContentRequest {
238 raw: content.to_string(),
239 },
240 };
241
242 let path = format!(
243 "/repositories/{}/{}/issues/{}/comments",
244 workspace, repo_slug, issue_id
245 );
246 self.post(&path, &request).await
247 }
248
249 pub async fn update_issue_comment(
251 &self,
252 workspace: &str,
253 repo_slug: &str,
254 issue_id: u64,
255 comment_id: u64,
256 content: &str,
257 ) -> Result<IssueComment> {
258 let request = CreateIssueCommentRequest {
259 content: IssueContentRequest {
260 raw: content.to_string(),
261 },
262 };
263
264 let path = format!(
265 "/repositories/{}/{}/issues/{}/comments/{}",
266 workspace, repo_slug, issue_id, comment_id
267 );
268 self.put(&path, &request).await
269 }
270
271 pub async fn delete_issue_comment(
273 &self,
274 workspace: &str,
275 repo_slug: &str,
276 issue_id: u64,
277 comment_id: u64,
278 ) -> Result<()> {
279 let path = format!(
280 "/repositories/{}/{}/issues/{}/comments/{}",
281 workspace, repo_slug, issue_id, comment_id
282 );
283 self.delete(&path).await
284 }
285
286 pub async fn list_issue_changes(
289 &self,
290 workspace: &str,
291 repo_slug: &str,
292 issue_id: u64,
293 pagelen: Option<u32>,
294 ) -> Result<Paginated<IssueChange>> {
295 let query: Vec<(&str, String)> = pagelen
296 .map(|len| ("pagelen", len.to_string()))
297 .into_iter()
298 .collect();
299 let query_refs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
300
301 let path = format!(
302 "/repositories/{}/{}/issues/{}/changes",
303 workspace, repo_slug, issue_id
304 );
305 self.get_with_query(&path, &query_refs).await
306 }
307
308 pub async fn list_issue_components(
311 &self,
312 workspace: &str,
313 repo_slug: &str,
314 ) -> Result<Vec<IssueMetaItem>> {
315 let path = format!("/repositories/{}/{}/components", workspace, repo_slug);
316 self.get_all_pages::<IssueMetaItem>(&path).await
317 }
318
319 pub async fn list_issue_milestones(
322 &self,
323 workspace: &str,
324 repo_slug: &str,
325 ) -> Result<Vec<IssueMetaItem>> {
326 let path = format!("/repositories/{}/{}/milestones", workspace, repo_slug);
327 self.get_all_pages::<IssueMetaItem>(&path).await
328 }
329
330 pub async fn list_issue_versions(
333 &self,
334 workspace: &str,
335 repo_slug: &str,
336 ) -> Result<Vec<IssueMetaItem>> {
337 let path = format!("/repositories/{}/{}/versions", workspace, repo_slug);
338 self.get_all_pages::<IssueMetaItem>(&path).await
339 }
340
341 pub async fn list_issue_attachments(
344 &self,
345 workspace: &str,
346 repo_slug: &str,
347 issue_id: u64,
348 ) -> Result<Vec<IssueAttachment>> {
349 let path = format!(
350 "/repositories/{}/{}/issues/{}/attachments",
351 workspace, repo_slug, issue_id
352 );
353 self.get_all_pages::<IssueAttachment>(&path).await
354 }
355
356 pub async fn upload_issue_attachments(
361 &self,
362 workspace: &str,
363 repo_slug: &str,
364 issue_id: u64,
365 files: &[(String, PathBuf)],
366 ) -> Result<()> {
367 let mut form = Form::new();
368
369 for (upload_name, path) in files {
370 let bytes = std::fs::read(path)
374 .with_context(|| format!("Failed to read file '{}'", path.display()))?;
375 let part = Part::bytes(bytes).file_name(upload_name.clone());
376 form = form.part("files", part);
377 }
378
379 let path = format!(
380 "/repositories/{}/{}/issues/{}/attachments",
381 workspace, repo_slug, issue_id
382 );
383 self.post_multipart(&path, form).await
384 }
385
386 pub async fn delete_issue_attachment(
389 &self,
390 workspace: &str,
391 repo_slug: &str,
392 issue_id: u64,
393 attachment_path: &str,
394 ) -> Result<()> {
395 let path = format!(
396 "/repositories/{}/{}/issues/{}/attachments/{}",
397 workspace,
398 repo_slug,
399 issue_id,
400 urlencode_segment(attachment_path)
401 );
402 self.delete(&path).await
403 }
404
405 pub async fn vote_issue(&self, workspace: &str, repo_slug: &str, issue_id: u64) -> Result<()> {
407 let path = format!(
408 "/repositories/{}/{}/issues/{}/vote",
409 workspace, repo_slug, issue_id
410 );
411 self.put::<serde_json::Value, _>(&path, &serde_json::json!({}))
412 .await?;
413 Ok(())
414 }
415
416 pub async fn unvote_issue(
418 &self,
419 workspace: &str,
420 repo_slug: &str,
421 issue_id: u64,
422 ) -> Result<()> {
423 let path = format!(
424 "/repositories/{}/{}/issues/{}/vote",
425 workspace, repo_slug, issue_id
426 );
427 self.delete(&path).await
428 }
429
430 pub async fn watch_issue(&self, workspace: &str, repo_slug: &str, issue_id: u64) -> Result<()> {
432 let path = format!(
433 "/repositories/{}/{}/issues/{}/watch",
434 workspace, repo_slug, issue_id
435 );
436 self.put::<serde_json::Value, _>(&path, &serde_json::json!({}))
437 .await?;
438 Ok(())
439 }
440
441 pub async fn unwatch_issue(
443 &self,
444 workspace: &str,
445 repo_slug: &str,
446 issue_id: u64,
447 ) -> Result<()> {
448 let path = format!(
449 "/repositories/{}/{}/issues/{}/watch",
450 workspace, repo_slug, issue_id
451 );
452 self.delete(&path).await
453 }
454}
455
456#[cfg(test)]
463fn issue_list_query(
464 state: Option<IssueState>,
465 page: Option<u32>,
466 pagelen: Option<u32>,
467) -> Vec<(&'static str, String)> {
468 issue_list_query_full(&IssueListFilters {
469 state,
470 page,
471 pagelen,
472 ..Default::default()
473 })
474}
475
476fn issue_list_query_full(filters: &IssueListFilters<'_>) -> Vec<(&'static str, String)> {
481 let mut query = Vec::new();
482
483 let q = match filters.query {
484 Some(raw) => Some(raw.to_string()),
485 None => issue_query_filter(
486 filters.state.as_ref(),
487 filters.kind.as_ref(),
488 filters.priority.as_ref(),
489 filters.assignee,
490 filters.reporter,
491 ),
492 };
493
494 if let Some(q) = q {
495 query.push(("q", q));
496 }
497 if let Some(sort) = filters.sort {
498 query.push(("sort", sort.to_string()));
499 }
500 if let Some(p) = filters.page {
501 query.push(("page", p.to_string()));
502 }
503 if let Some(len) = filters.pagelen {
504 query.push(("pagelen", len.to_string()));
505 }
506
507 query
508}
509
510fn issue_query_filter(
517 state: Option<&IssueState>,
518 kind: Option<&IssueKind>,
519 priority: Option<&IssuePriority>,
520 assignee: Option<&str>,
521 reporter: Option<&str>,
522) -> Option<String> {
523 let mut parts = Vec::new();
524
525 if let Some(s) = state {
526 parts.push(format!("state=\"{}\"", s));
527 }
528 if let Some(k) = kind {
529 parts.push(format!("kind=\"{}\"", k));
530 }
531 if let Some(p) = priority {
532 parts.push(format!("priority=\"{}\"", p));
533 }
534 if let Some(a) = assignee {
535 parts.push(format!("assignee.account_id={}", bbql_quote(a)));
536 }
537 if let Some(r) = reporter {
538 parts.push(format!("reporter.account_id={}", bbql_quote(r)));
539 }
540
541 if parts.is_empty() {
542 None
543 } else {
544 Some(parts.join(" AND "))
545 }
546}
547
548fn bbql_quote(s: &str) -> String {
554 let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
555 format!("\"{}\"", escaped)
556}
557
558#[cfg(test)]
559mod tests {
560 use super::{
561 IssueListFilters, bbql_quote, issue_list_query, issue_list_query_full, issue_query_filter,
562 urlencode_segment,
563 };
564 use crate::models::{IssueKind, IssuePriority, IssueState};
565
566 #[test]
567 fn open_state_builds_quoted_bbql_filter() {
568 assert_eq!(
569 issue_list_query(Some(IssueState::Open), None, None),
570 vec![("q", "state=\"open\"".to_string())]
571 );
572 }
573
574 #[test]
575 fn on_hold_state_keeps_two_word_value_quoted() {
576 assert_eq!(
577 issue_list_query(Some(IssueState::OnHold), None, None),
578 vec![("q", "state=\"on hold\"".to_string())]
579 );
580 }
581
582 #[test]
583 fn no_state_omits_q_pair() {
584 let query = issue_list_query(None, None, None);
585 assert!(query.is_empty());
586 }
587
588 #[test]
589 fn page_and_pagelen_pass_through_as_strings() {
590 assert_eq!(
591 issue_list_query(None, Some(2), Some(50)),
592 vec![("page", "2".to_string()), ("pagelen", "50".to_string())]
593 );
594 }
595
596 #[test]
597 fn state_page_and_pagelen_combine_in_order() {
598 assert_eq!(
599 issue_list_query(Some(IssueState::Open), Some(3), Some(25)),
600 vec![
601 ("q", "state=\"open\"".to_string()),
602 ("page", "3".to_string()),
603 ("pagelen", "25".to_string()),
604 ]
605 );
606 }
607
608 #[test]
609 fn query_filter_is_none_without_filters() {
610 assert_eq!(issue_query_filter(None, None, None, None, None), None);
611 }
612
613 #[test]
614 fn query_filter_quotes_on_hold_state() {
615 assert_eq!(
616 issue_query_filter(Some(&IssueState::OnHold), None, None, None, None).as_deref(),
617 Some("state=\"on hold\"")
618 );
619 }
620
621 #[test]
622 fn query_filter_ands_all_filters_in_order() {
623 assert_eq!(
624 issue_query_filter(
625 Some(&IssueState::Open),
626 Some(&IssueKind::Bug),
627 Some(&IssuePriority::Major),
628 Some("acc-123"),
629 Some("acc-456"),
630 )
631 .as_deref(),
632 Some(
633 "state=\"open\" AND kind=\"bug\" AND priority=\"major\" AND \
634 assignee.account_id=\"acc-123\" AND reporter.account_id=\"acc-456\""
635 )
636 );
637 }
638
639 #[test]
640 fn query_filter_handles_people_filters_alone() {
641 assert_eq!(
642 issue_query_filter(None, None, None, Some("acc-123"), None).as_deref(),
643 Some("assignee.account_id=\"acc-123\"")
644 );
645 assert_eq!(
646 issue_query_filter(None, None, None, None, Some("acc-456")).as_deref(),
647 Some("reporter.account_id=\"acc-456\"")
648 );
649 }
650
651 #[test]
652 fn full_query_raw_query_wins_over_filters() {
653 let filters = IssueListFilters {
654 state: Some(IssueState::Open),
655 kind: Some(IssueKind::Bug),
656 query: Some("kind=\"task\""),
657 ..Default::default()
658 };
659 assert_eq!(
660 issue_list_query_full(&filters),
661 vec![("q", "kind=\"task\"".to_string())]
662 );
663 }
664
665 #[test]
666 fn full_query_includes_sort_page_and_pagelen_in_order() {
667 let filters = IssueListFilters {
668 state: Some(IssueState::Open),
669 sort: Some("-updated_on"),
670 page: Some(2),
671 pagelen: Some(50),
672 ..Default::default()
673 };
674 assert_eq!(
675 issue_list_query_full(&filters),
676 vec![
677 ("q", "state=\"open\"".to_string()),
678 ("sort", "-updated_on".to_string()),
679 ("page", "2".to_string()),
680 ("pagelen", "50".to_string()),
681 ]
682 );
683 }
684
685 #[test]
686 fn bbql_quote_escapes_backslash_and_double_quote() {
687 assert_eq!(bbql_quote(r#"a"b\c"#), r#""a\"b\\c""#);
690 assert_eq!(bbql_quote("acc-123"), r#""acc-123""#);
692 assert_eq!(
694 bbql_quote(r#"x" OR state="open"#),
695 r#""x\" OR state=\"open""#
696 );
697 }
698
699 #[test]
700 fn urlencode_encodes_spaces_and_leaves_safe_chars() {
701 assert_eq!(urlencode_segment("shot 1.png"), "shot%201.png");
702 assert_eq!(urlencode_segment("a-b_c.d~1"), "a-b_c.d~1");
703 }
704}