1use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10
11use crate::{
12 Result,
13 paging::Paged,
14 types::{
15 CommentData, MergeResult, MergeStrategy, State, UserSummary, deserialize_u64_or_string,
16 },
17};
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct PrData {
26 #[serde(deserialize_with = "deserialize_u64_or_string")]
28 pub number: u64,
29 pub title: String,
31 #[serde(skip_serializing_if = "Option::is_none")]
33 pub body: Option<String>,
34 pub state: State,
36 #[serde(alias = "isDraft")]
38 pub draft: bool,
39 pub author: UserSummary,
41 #[serde(alias = "baseRefName")]
43 pub base_branch: String,
44 #[serde(alias = "headRefName")]
46 pub head_branch: String,
47 #[serde(skip_serializing_if = "Option::is_none")]
49 pub created_at: Option<DateTime<Utc>>,
50 #[serde(skip_serializing_if = "Option::is_none")]
52 pub updated_at: Option<DateTime<Utc>>,
53 pub merged_at: Option<DateTime<Utc>>,
60 #[serde(skip_serializing_if = "Option::is_none")]
62 pub milestone: Option<crate::types::MilestoneRef>,
63 pub url: String,
65}
66
67#[derive(Debug, Clone)]
69pub struct CreatePrArgs {
70 pub title: String,
72 pub body: Option<String>,
74 pub head: String,
76 pub base: String,
78 pub draft: bool,
80 pub repo: Option<String>,
82 pub closes_issues: Vec<u64>,
84 pub milestone: Option<String>,
86}
87
88#[derive(Debug, Clone, Default)]
92pub struct ListPrArgs {
93 pub state: Option<State>,
95 pub limit: Option<u32>,
97}
98
99#[async_trait]
110pub trait PrProvider: std::fmt::Debug + Send + Sync {
111 async fn create(&self, args: CreatePrArgs) -> Result<PrData>;
117
118 async fn list(&self, args: ListPrArgs) -> Result<Paged<PrData>>;
126
127 async fn view(&self, number: u64) -> Result<PrData>;
133
134 async fn close(&self, number: u64) -> Result<PrData>;
140
141 async fn reopen(&self, number: u64) -> Result<PrData>;
147
148 async fn comment(&self, number: u64, body: &str) -> Result<CommentData>;
154
155 async fn merge(
168 &self,
169 number: u64,
170 strategy: Option<MergeStrategy>,
171 auto: bool,
172 ) -> Result<MergeResult>;
173
174 async fn checkout(&self, number: u64) -> Result<()>;
180
181 async fn mark_ready(&self, number: u64) -> Result<PrData>;
187
188 async fn mark_wip(&self, number: u64) -> Result<PrData>;
194
195 async fn sync_branch(&self, number: u64) -> Result<()>;
201
202 async fn diff(&self, number: u64) -> Result<String>;
212
213 async fn patch(&self, number: u64) -> Result<String>;
223
224 async fn default_branch(&self) -> Result<String>;
233}
234
235#[must_use]
251pub fn format_closing_body(body: &Option<String>, issues: &[u64], keyword: &str) -> Option<String> {
252 if issues.is_empty() {
253 return body.clone();
254 }
255 let closing = issues
256 .iter()
257 .map(|n| format!("{keyword} #{n}"))
258 .collect::<Vec<_>>()
259 .join("\n");
260 Some(match body {
261 Some(b) if !b.is_empty() => format!("{b}\n\n{closing}"),
262 _ => closing,
263 })
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 fn sample_pr_json() -> &'static str {
272 r#"{
273 "number": 101,
274 "title": "Add feature X",
275 "body": "Implements X per spec.",
276 "state": "open",
277 "draft": false,
278 "author": {"login": "alice", "id": "7"},
279 "baseBranch": "main",
280 "headBranch": "feature/x",
281 "createdAt": "2026-02-10T08:00:00Z",
282 "updatedAt": "2026-02-11T12:30:00Z",
283 "url": "https://github.com/octocat/hello-world/pull/101"
284 }"#
285 }
286
287 #[test]
288 fn test_should_deserialize_pr_data_from_gh_cli_json() {
289 let json = sample_pr_json();
290 let pr: PrData = serde_json::from_str(json).expect("valid PrData JSON");
291
292 assert_eq!(pr.number, 101);
293 assert_eq!(pr.title, "Add feature X");
294 assert_eq!(pr.body.as_deref(), Some("Implements X per spec."));
295 assert_eq!(pr.state, State::Open);
296 assert!(!pr.draft);
297 assert_eq!(pr.author.login, "alice");
298 assert_eq!(pr.author.id, "7");
299 assert_eq!(pr.base_branch, "main");
300 assert_eq!(pr.head_branch, "feature/x");
301 assert_eq!(pr.url, "https://github.com/octocat/hello-world/pull/101");
302 }
303
304 #[test]
305 fn test_should_roundtrip_pr_data_via_serde() {
306 let json = sample_pr_json();
307 let pr: PrData = serde_json::from_str(json).expect("deserialize");
308 let re_serialized = serde_json::to_string(&pr).expect("serialize");
309 let round_tripped: PrData = serde_json::from_str(&re_serialized).expect("re-deserialize");
310
311 assert_eq!(round_tripped.number, pr.number);
312 assert_eq!(round_tripped.title, pr.title);
313 assert_eq!(round_tripped.body, pr.body);
314 assert_eq!(round_tripped.state, pr.state);
315 assert_eq!(round_tripped.draft, pr.draft);
316 assert_eq!(round_tripped.base_branch, pr.base_branch);
317 assert_eq!(round_tripped.head_branch, pr.head_branch);
318 assert_eq!(round_tripped.url, pr.url);
319 assert_eq!(round_tripped.created_at, pr.created_at);
320 assert_eq!(round_tripped.updated_at, pr.updated_at);
321 }
322
323 #[test]
324 fn test_should_deserialize_draft_pr_with_null_body() {
325 let json = r#"{
326 "number": 5,
327 "title": "WIP experiment",
328 "body": null,
329 "state": "open",
330 "draft": true,
331 "author": {"login": "bob", "id": "9"},
332 "baseBranch": "main",
333 "headBranch": "wip",
334 "createdAt": "2026-04-01T00:00:00Z",
335 "updatedAt": "2026-04-02T00:00:00Z",
336 "url": "https://example.com/pull/5"
337 }"#;
338 let pr: PrData = serde_json::from_str(json).expect("deserialize");
339 assert!(pr.draft);
340 assert!(pr.body.is_none());
341 assert_eq!(pr.state, State::Open);
342 }
343
344 #[test]
345 fn test_should_omit_none_body_on_serialize() {
346 let json = sample_pr_json();
347 let mut pr: PrData = serde_json::from_str(json).expect("deserialize");
348 pr.body = None;
349 let serialized = serde_json::to_string(&pr).expect("serialize");
350 assert!(!serialized.contains("\"body\":null"));
352 assert!(!serialized.contains("\"body\": null"));
353 }
354
355 #[test]
356 fn test_should_serialize_camel_case_fields() {
357 let json = sample_pr_json();
358 let pr: PrData = serde_json::from_str(json).expect("deserialize");
359 let serialized = serde_json::to_string(&pr).expect("serialize");
360 assert!(serialized.contains("\"baseBranch\""));
362 assert!(serialized.contains("\"headBranch\""));
363 assert!(serialized.contains("\"createdAt\""));
364 assert!(serialized.contains("\"updatedAt\""));
365 assert!(!serialized.contains("\"base_branch\""));
367 assert!(!serialized.contains("\"head_branch\""));
368 }
369
370 #[test]
371 fn test_list_pr_args_default_is_empty() {
372 let args = ListPrArgs::default();
373 assert!(args.state.is_none());
374 assert!(args.limit.is_none());
375 }
376
377 #[test]
381 fn test_should_have_diff_and_patch_methods_on_trait() {
382 use async_trait::async_trait;
383
384 use crate::{Result, pr::PrProvider};
385
386 #[derive(Debug)]
387 struct Check;
388
389 #[async_trait]
390 impl PrProvider for Check {
391 async fn create(&self, _args: crate::pr::CreatePrArgs) -> Result<crate::pr::PrData> {
392 unimplemented!()
393 }
394 async fn list(
395 &self,
396 _args: crate::pr::ListPrArgs,
397 ) -> Result<crate::paging::Paged<crate::pr::PrData>> {
398 unimplemented!()
399 }
400 async fn view(&self, _number: u64) -> Result<crate::pr::PrData> {
401 unimplemented!()
402 }
403 async fn close(&self, _number: u64) -> Result<crate::pr::PrData> {
404 unimplemented!()
405 }
406 async fn reopen(&self, _number: u64) -> Result<crate::pr::PrData> {
407 unimplemented!()
408 }
409 async fn comment(
410 &self,
411 _number: u64,
412 _body: &str,
413 ) -> Result<crate::types::CommentData> {
414 unimplemented!()
415 }
416 async fn merge(
417 &self,
418 _number: u64,
419 _strategy: Option<crate::types::MergeStrategy>,
420 _auto: bool,
421 ) -> Result<crate::types::MergeResult> {
422 unimplemented!()
423 }
424 async fn checkout(&self, _number: u64) -> Result<()> {
425 unimplemented!()
426 }
427 async fn mark_ready(&self, _number: u64) -> Result<crate::pr::PrData> {
428 unimplemented!()
429 }
430 async fn mark_wip(&self, _number: u64) -> Result<crate::pr::PrData> {
431 unimplemented!()
432 }
433 async fn sync_branch(&self, _number: u64) -> Result<()> {
434 unimplemented!()
435 }
436 async fn diff(&self, _number: u64) -> Result<String> {
437 unimplemented!()
438 }
439 async fn patch(&self, _number: u64) -> Result<String> {
440 unimplemented!()
441 }
442 async fn default_branch(&self) -> Result<String> {
443 unimplemented!()
444 }
445 }
446
447 let check = Check;
449 let _ = format!("{check:?}");
450 }
451
452 #[test]
455 fn test_should_return_body_unchanged_when_no_issues() {
456 let body = Some("Existing body".to_string());
457 let result = crate::pr::format_closing_body(&body, &[], "Closes");
458 assert_eq!(result, Some("Existing body".to_string()));
459 }
460
461 #[test]
462 fn test_should_return_none_when_no_body_and_no_issues() {
463 let result = crate::pr::format_closing_body(&None, &[], "Closes");
464 assert!(result.is_none());
465 }
466
467 #[test]
468 fn test_should_create_closing_body_when_no_existing_body() {
469 let result = crate::pr::format_closing_body(&None, &[24], "Closes");
470 assert_eq!(result, Some("Closes #24".to_string()));
471 }
472
473 #[test]
474 fn test_should_append_closing_to_existing_body() {
475 let body = Some("Feature description".to_string());
476 let result = crate::pr::format_closing_body(&body, &[24], "Closes");
477 assert_eq!(
478 result,
479 Some("Feature description\n\nCloses #24".to_string())
480 );
481 }
482
483 #[test]
484 fn test_should_handle_multiple_issues() {
485 let body = Some("Description".to_string());
486 let result = crate::pr::format_closing_body(&body, &[24, 23], "Closes");
487 assert_eq!(
488 result,
489 Some("Description\n\nCloses #24\nCloses #23".to_string())
490 );
491 }
492
493 #[test]
494 fn test_should_use_custom_keyword() {
495 let result = crate::pr::format_closing_body(&None, &[42], "Fixes");
496 assert_eq!(result, Some("Fixes #42".to_string()));
497 }
498
499 #[test]
500 fn test_should_treat_empty_body_as_no_body() {
501 let body = Some(String::new());
502 let result = crate::pr::format_closing_body(&body, &[10], "Closes");
503 assert_eq!(result, Some("Closes #10".to_string()));
504 }
505
506 #[test]
507 fn test_should_have_closes_issues_field() {
508 let args = crate::pr::CreatePrArgs {
509 title: "Test".to_string(),
510 body: None,
511 head: "feature".to_string(),
512 base: "main".to_string(),
513 draft: false,
514 repo: None,
515 closes_issues: vec![24, 23],
516 milestone: None,
517 };
518 assert_eq!(args.closes_issues, vec![24, 23]);
519 }
520}