1use serde_json::json;
34
35use crate::client::{GitFoxClient, Method, Query};
36use crate::error::Result;
37use crate::models::{
38 Commit, CreatePullRequest, FileDiff, MergePullRequest, MergeResult, PullRequest,
39 PullRequestActivity, PullRequestChecks, PullRequestLabels, PullRequestReviewer,
40 PullRequestState, RepoRef, ReviewDecision, UpdatePullRequest,
41};
42
43#[derive(Debug, Clone)]
48pub struct PullRequestFilter {
49 pub state: Vec<PullRequestState>,
50 pub author_id: Option<i64>,
51 pub reviewer_id: Option<i64>,
52 pub source_branch: Option<String>,
53 pub target_branch: Option<String>,
54 pub query: Option<String>,
55 pub label_id: Vec<i64>,
56 pub value_id: Vec<i64>,
57 pub review_decision: Vec<String>,
59 pub include_checks: bool,
61 pub page: u32,
62 pub limit: u32,
63}
64
65impl Default for PullRequestFilter {
66 fn default() -> Self {
67 Self {
68 state: vec![PullRequestState::Open],
69 author_id: None,
70 reviewer_id: None,
71 source_branch: None,
72 target_branch: None,
73 query: None,
74 label_id: Vec::new(),
75 value_id: Vec::new(),
76 review_decision: Vec::new(),
77 include_checks: false,
78 page: 1,
79 limit: 30,
80 }
81 }
82}
83
84impl PullRequestFilter {
85 fn to_query(&self) -> Query {
86 let mut q = Query::new();
87 q.extend("state", self.state.iter().map(|s| s.as_str()))
88 .push_opt("author_id", self.author_id)
89 .push_opt("reviewer_id", self.reviewer_id)
90 .push_opt("source_branch", self.source_branch.as_deref())
91 .push_opt("target_branch", self.target_branch.as_deref())
92 .push_opt("query", self.query.as_deref())
93 .extend("label_id", &self.label_id)
94 .extend("value_id", &self.value_id)
95 .extend("review_decision", &self.review_decision);
96 if self.include_checks {
97 q.push("include_checks", "true");
98 }
99 q.push("page", self.page).push("limit", self.limit);
100 q
101 }
102}
103
104pub struct PullRequestsApi<'a> {
105 client: &'a GitFoxClient,
106}
107
108impl<'a> PullRequestsApi<'a> {
109 pub(crate) fn new(client: &'a GitFoxClient) -> Self {
110 Self { client }
111 }
112
113 fn path(repo: &RepoRef, number: u64) -> String {
114 format!("/api/v1/repos/{}/pullreq/{number}", repo.encoded())
115 }
116
117 pub async fn list(
119 &self,
120 repo: &RepoRef,
121 filter: &PullRequestFilter,
122 ) -> Result<Vec<PullRequest>> {
123 let path = format!("/api/v1/repos/{}/pullreq", repo.encoded());
124 self.client.get_json(&filter.to_query().apply(&path)).await
125 }
126
127 pub async fn get(&self, repo: &RepoRef, number: u64) -> Result<PullRequest> {
129 self.client.get_json(&Self::path(repo, number)).await
130 }
131
132 pub async fn find_for_branch(
137 &self,
138 repo: &RepoRef,
139 branch: &str,
140 ) -> Result<Option<PullRequest>> {
141 let filter = PullRequestFilter {
142 source_branch: Some(branch.to_string()),
143 limit: 2,
144 ..Default::default()
145 };
146 Ok(self.list(repo, &filter).await?.into_iter().next())
147 }
148
149 pub async fn find_any_for_branch(
152 &self,
153 repo: &RepoRef,
154 branch: &str,
155 ) -> Result<Option<PullRequest>> {
156 if let Some(open) = self.find_for_branch(repo, branch).await? {
157 return Ok(Some(open));
158 }
159 let filter = PullRequestFilter {
160 state: vec![PullRequestState::Merged, PullRequestState::Closed],
161 source_branch: Some(branch.to_string()),
162 limit: 20,
163 ..Default::default()
164 };
165 let mut found = self.list(repo, &filter).await?;
166 found.sort_by_key(|pr| std::cmp::Reverse(pr.number));
167 Ok(found.into_iter().next())
168 }
169
170 pub async fn create(&self, repo: &RepoRef, input: &CreatePullRequest) -> Result<PullRequest> {
172 let body = serde_json::to_value(input).map_err(|e| crate::Error::Decode(e.to_string()))?;
173 self.client
174 .request(
175 Method::POST,
176 &format!("/api/v1/repos/{}/pullreq", repo.encoded()),
177 Some(&body),
178 &[],
179 )
180 .await?
181 .deserialize()
182 }
183
184 pub async fn update(
186 &self,
187 repo: &RepoRef,
188 number: u64,
189 input: &UpdatePullRequest,
190 ) -> Result<PullRequest> {
191 let body = serde_json::to_value(input).map_err(|e| crate::Error::Decode(e.to_string()))?;
192 self.client
193 .request(Method::PATCH, &Self::path(repo, number), Some(&body), &[])
194 .await?
195 .deserialize()
196 }
197
198 pub async fn merge(
200 &self,
201 repo: &RepoRef,
202 number: u64,
203 input: &MergePullRequest,
204 ) -> Result<MergeResult> {
205 let body = serde_json::to_value(input).map_err(|e| crate::Error::Decode(e.to_string()))?;
206 self.client
207 .request(
208 Method::POST,
209 &format!("{}/merge", Self::path(repo, number)),
210 Some(&body),
211 &[],
212 )
213 .await?
214 .deserialize()
215 }
216
217 pub async fn delete_source_branch(&self, repo: &RepoRef, number: u64) -> Result<()> {
222 self.client
223 .request(
224 Method::DELETE,
225 &format!("{}/branch", Self::path(repo, number)),
226 None,
227 &[],
228 )
229 .await
230 .map(|_| ())
231 }
232
233 pub async fn diff_files(&self, repo: &RepoRef, number: u64) -> Result<Vec<FileDiff>> {
238 self.client
239 .get_json(&format!("{}/diff", Self::path(repo, number)))
240 .await
241 }
242
243 pub async fn diff_text(&self, repo: &RepoRef, number: u64) -> Result<String> {
245 let response = self
246 .client
247 .request(
248 Method::GET,
249 &format!("{}/diff", Self::path(repo, number)),
250 None,
251 &[("Accept".to_string(), "text/plain".to_string())],
252 )
253 .await?;
254 Ok(response.text)
255 }
256
257 pub async fn checks(&self, repo: &RepoRef, number: u64) -> Result<PullRequestChecks> {
259 self.client
260 .get_json(&format!("{}/checks", Self::path(repo, number)))
261 .await
262 }
263
264 pub async fn commits(
266 &self,
267 repo: &RepoRef,
268 number: u64,
269 page: u32,
270 limit: u32,
271 ) -> Result<Vec<Commit>> {
272 let mut q = Query::new();
273 q.push("page", page).push("limit", limit);
274 self.client
275 .get_json(&q.apply(&format!("{}/commits", Self::path(repo, number))))
276 .await
277 }
278
279 pub async fn set_state(
281 &self,
282 repo: &RepoRef,
283 number: u64,
284 state: PullRequestState,
285 ) -> Result<PullRequest> {
286 self.post_state(repo, number, json!({ "state": state.as_str() }))
287 .await
288 }
289
290 pub async fn set_draft(&self, repo: &RepoRef, number: u64, draft: bool) -> Result<PullRequest> {
295 self.post_state(repo, number, json!({ "state": "open", "is_draft": draft }))
296 .await
297 }
298
299 async fn post_state(
300 &self,
301 repo: &RepoRef,
302 number: u64,
303 body: serde_json::Value,
304 ) -> Result<PullRequest> {
305 self.client
306 .request(
307 Method::POST,
308 &format!("{}/state", Self::path(repo, number)),
309 Some(&body),
310 &[],
311 )
312 .await?
313 .deserialize()
314 }
315
316 pub async fn activities(
319 &self,
320 repo: &RepoRef,
321 number: u64,
322 kinds: &[&str],
323 ) -> Result<Vec<PullRequestActivity>> {
324 let mut q = Query::new();
325 q.extend("kind", kinds.iter().copied());
326 self.client
327 .get_json(&q.apply(&format!("{}/activities", Self::path(repo, number))))
328 .await
329 }
330
331 pub async fn comment(
333 &self,
334 repo: &RepoRef,
335 number: u64,
336 text: &str,
337 ) -> Result<PullRequestActivity> {
338 self.client
339 .request(
340 Method::POST,
341 &format!("{}/comments", Self::path(repo, number)),
342 Some(&json!({ "text": text })),
343 &[],
344 )
345 .await?
346 .deserialize()
347 }
348
349 pub async fn update_comment(
351 &self,
352 repo: &RepoRef,
353 number: u64,
354 comment_id: i64,
355 text: &str,
356 ) -> Result<PullRequestActivity> {
357 self.client
358 .request(
359 Method::PATCH,
360 &format!("{}/comments/{comment_id}", Self::path(repo, number)),
361 Some(&json!({ "text": text })),
362 &[],
363 )
364 .await?
365 .deserialize()
366 }
367
368 pub async fn delete_comment(&self, repo: &RepoRef, number: u64, comment_id: i64) -> Result<()> {
370 self.client
371 .request(
372 Method::DELETE,
373 &format!("{}/comments/{comment_id}", Self::path(repo, number)),
374 None,
375 &[],
376 )
377 .await
378 .map(|_| ())
379 }
380
381 pub async fn review(
386 &self,
387 repo: &RepoRef,
388 number: u64,
389 commit_sha: &str,
390 decision: ReviewDecision,
391 ) -> Result<()> {
392 self.client
393 .request(
394 Method::POST,
395 &format!("{}/reviews", Self::path(repo, number)),
396 Some(&json!({ "commit_sha": commit_sha, "decision": decision.as_str() })),
397 &[],
398 )
399 .await
400 .map(|_| ())
401 }
402
403 pub async fn reviewers(&self, repo: &RepoRef, number: u64) -> Result<Vec<PullRequestReviewer>> {
405 self.client
406 .get_json(&format!("{}/reviewers", Self::path(repo, number)))
407 .await
408 }
409
410 pub async fn add_reviewer(
412 &self,
413 repo: &RepoRef,
414 number: u64,
415 reviewer_id: i64,
416 ) -> Result<PullRequestReviewer> {
417 self.client
418 .request(
419 Method::PUT,
420 &format!("{}/reviewers", Self::path(repo, number)),
421 Some(&json!({ "reviewer_id": reviewer_id })),
422 &[],
423 )
424 .await?
425 .deserialize()
426 }
427
428 pub async fn remove_reviewer(
430 &self,
431 repo: &RepoRef,
432 number: u64,
433 reviewer_id: i64,
434 ) -> Result<()> {
435 self.client
436 .request(
437 Method::DELETE,
438 &format!("{}/reviewers/{reviewer_id}", Self::path(repo, number)),
439 None,
440 &[],
441 )
442 .await
443 .map(|_| ())
444 }
445
446 pub async fn labels(&self, repo: &RepoRef, number: u64) -> Result<PullRequestLabels> {
449 self.client
450 .get_json(&format!("{}/labels?limit=100", Self::path(repo, number)))
451 .await
452 }
453
454 pub async fn assign_label(
459 &self,
460 repo: &RepoRef,
461 number: u64,
462 label_id: i64,
463 value_id: Option<i64>,
464 value: Option<&str>,
465 ) -> Result<()> {
466 let mut body = json!({ "label_id": label_id });
467 if let Some(value_id) = value_id {
468 body["value_id"] = json!(value_id);
469 }
470 if let Some(value) = value {
471 body["value"] = json!(value);
472 }
473 self.client
474 .request(
475 Method::PUT,
476 &format!("{}/labels", Self::path(repo, number)),
477 Some(&body),
478 &[],
479 )
480 .await
481 .map(|_| ())
482 }
483
484 pub async fn unassign_label(&self, repo: &RepoRef, number: u64, label_id: i64) -> Result<()> {
486 self.client
487 .request(
488 Method::DELETE,
489 &format!("{}/labels/{label_id}", Self::path(repo, number)),
490 None,
491 &[],
492 )
493 .await
494 .map(|_| ())
495 }
496}
497
498#[cfg(test)]
499mod tests {
500 use super::*;
501
502 #[test]
503 fn the_default_filter_asks_for_open_pull_requests_only() {
504 let q = PullRequestFilter::default().to_query();
505 assert_eq!(q.apply("/p"), "/p?state=open&page=1&limit=30");
506 }
507
508 #[test]
509 fn several_states_become_repeated_parameters() {
510 let filter = PullRequestFilter {
511 state: vec![PullRequestState::Open, PullRequestState::Merged],
512 ..Default::default()
513 };
514 assert!(
515 filter
516 .to_query()
517 .encode()
518 .contains("state=open&state=merged")
519 );
520 }
521
522 #[test]
523 fn unset_filters_are_left_out_entirely() {
524 let encoded = PullRequestFilter::default().to_query().encode();
525 for absent in [
526 "author_id",
527 "reviewer_id",
528 "source_branch",
529 "target_branch",
530 "query",
531 "label_id",
532 "value_id",
533 "review_decision",
534 "include_checks",
535 ] {
536 assert!(
537 !encoded.contains(absent),
538 "{absent} should be absent: {encoded}"
539 );
540 }
541 }
542
543 #[test]
544 fn label_and_review_filters_repeat_like_the_state_filter() {
545 let filter = PullRequestFilter {
546 label_id: vec![3, 4],
547 value_id: vec![9],
548 reviewer_id: Some(7),
549 review_decision: vec!["approved".into()],
550 include_checks: true,
551 ..Default::default()
552 };
553 let encoded = filter.to_query().encode();
554 for expected in [
555 "label_id=3&label_id=4",
556 "value_id=9",
557 "reviewer_id=7",
558 "review_decision=approved",
559 "include_checks=true",
560 ] {
561 assert!(encoded.contains(expected), "{expected}: {encoded}");
562 }
563 }
564}