use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::{
Result,
paging::Paged,
types::{
CommentData, MergeResult, MergeStrategy, State, UserSummary, deserialize_u64_or_string,
},
};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PrData {
#[serde(deserialize_with = "deserialize_u64_or_string")]
pub number: u64,
pub title: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub body: Option<String>,
pub state: State,
#[serde(alias = "isDraft")]
pub draft: bool,
pub author: UserSummary,
#[serde(alias = "baseRefName")]
pub base_branch: String,
#[serde(alias = "headRefName")]
pub head_branch: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub created_at: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub updated_at: Option<DateTime<Utc>>,
pub merged_at: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub milestone: Option<crate::types::MilestoneRef>,
pub url: String,
}
#[derive(Debug, Clone)]
pub struct CreatePrArgs {
pub title: String,
pub body: Option<String>,
pub head: String,
pub base: String,
pub draft: bool,
pub repo: Option<String>,
pub closes_issues: Vec<u64>,
pub milestone: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct ListPrArgs {
pub state: Option<State>,
pub limit: Option<u32>,
}
#[async_trait]
pub trait PrProvider: std::fmt::Debug + Send + Sync {
async fn create(&self, args: CreatePrArgs) -> Result<PrData>;
async fn list(&self, args: ListPrArgs) -> Result<Paged<PrData>>;
async fn view(&self, number: u64) -> Result<PrData>;
async fn close(&self, number: u64) -> Result<PrData>;
async fn reopen(&self, number: u64) -> Result<PrData>;
async fn comment(&self, number: u64, body: &str) -> Result<CommentData>;
async fn merge(
&self,
number: u64,
strategy: Option<MergeStrategy>,
auto: bool,
) -> Result<MergeResult>;
async fn checkout(&self, number: u64) -> Result<()>;
async fn mark_ready(&self, number: u64) -> Result<PrData>;
async fn mark_wip(&self, number: u64) -> Result<PrData>;
async fn sync_branch(&self, number: u64) -> Result<()>;
async fn diff(&self, number: u64) -> Result<String>;
async fn patch(&self, number: u64) -> Result<String>;
async fn default_branch(&self) -> Result<String>;
}
#[must_use]
pub fn format_closing_body(body: &Option<String>, issues: &[u64], keyword: &str) -> Option<String> {
if issues.is_empty() {
return body.clone();
}
let closing = issues
.iter()
.map(|n| format!("{keyword} #{n}"))
.collect::<Vec<_>>()
.join("\n");
Some(match body {
Some(b) if !b.is_empty() => format!("{b}\n\n{closing}"),
_ => closing,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_pr_json() -> &'static str {
r#"{
"number": 101,
"title": "Add feature X",
"body": "Implements X per spec.",
"state": "open",
"draft": false,
"author": {"login": "alice", "id": "7"},
"baseBranch": "main",
"headBranch": "feature/x",
"createdAt": "2026-02-10T08:00:00Z",
"updatedAt": "2026-02-11T12:30:00Z",
"url": "https://github.com/octocat/hello-world/pull/101"
}"#
}
#[test]
fn test_should_deserialize_pr_data_from_gh_cli_json() {
let json = sample_pr_json();
let pr: PrData = serde_json::from_str(json).expect("valid PrData JSON");
assert_eq!(pr.number, 101);
assert_eq!(pr.title, "Add feature X");
assert_eq!(pr.body.as_deref(), Some("Implements X per spec."));
assert_eq!(pr.state, State::Open);
assert!(!pr.draft);
assert_eq!(pr.author.login, "alice");
assert_eq!(pr.author.id, "7");
assert_eq!(pr.base_branch, "main");
assert_eq!(pr.head_branch, "feature/x");
assert_eq!(pr.url, "https://github.com/octocat/hello-world/pull/101");
}
#[test]
fn test_should_roundtrip_pr_data_via_serde() {
let json = sample_pr_json();
let pr: PrData = serde_json::from_str(json).expect("deserialize");
let re_serialized = serde_json::to_string(&pr).expect("serialize");
let round_tripped: PrData = serde_json::from_str(&re_serialized).expect("re-deserialize");
assert_eq!(round_tripped.number, pr.number);
assert_eq!(round_tripped.title, pr.title);
assert_eq!(round_tripped.body, pr.body);
assert_eq!(round_tripped.state, pr.state);
assert_eq!(round_tripped.draft, pr.draft);
assert_eq!(round_tripped.base_branch, pr.base_branch);
assert_eq!(round_tripped.head_branch, pr.head_branch);
assert_eq!(round_tripped.url, pr.url);
assert_eq!(round_tripped.created_at, pr.created_at);
assert_eq!(round_tripped.updated_at, pr.updated_at);
}
#[test]
fn test_should_deserialize_draft_pr_with_null_body() {
let json = r#"{
"number": 5,
"title": "WIP experiment",
"body": null,
"state": "open",
"draft": true,
"author": {"login": "bob", "id": "9"},
"baseBranch": "main",
"headBranch": "wip",
"createdAt": "2026-04-01T00:00:00Z",
"updatedAt": "2026-04-02T00:00:00Z",
"url": "https://example.com/pull/5"
}"#;
let pr: PrData = serde_json::from_str(json).expect("deserialize");
assert!(pr.draft);
assert!(pr.body.is_none());
assert_eq!(pr.state, State::Open);
}
#[test]
fn test_should_omit_none_body_on_serialize() {
let json = sample_pr_json();
let mut pr: PrData = serde_json::from_str(json).expect("deserialize");
pr.body = None;
let serialized = serde_json::to_string(&pr).expect("serialize");
assert!(!serialized.contains("\"body\":null"));
assert!(!serialized.contains("\"body\": null"));
}
#[test]
fn test_should_serialize_camel_case_fields() {
let json = sample_pr_json();
let pr: PrData = serde_json::from_str(json).expect("deserialize");
let serialized = serde_json::to_string(&pr).expect("serialize");
assert!(serialized.contains("\"baseBranch\""));
assert!(serialized.contains("\"headBranch\""));
assert!(serialized.contains("\"createdAt\""));
assert!(serialized.contains("\"updatedAt\""));
assert!(!serialized.contains("\"base_branch\""));
assert!(!serialized.contains("\"head_branch\""));
}
#[test]
fn test_list_pr_args_default_is_empty() {
let args = ListPrArgs::default();
assert!(args.state.is_none());
assert!(args.limit.is_none());
}
#[test]
fn test_should_have_diff_and_patch_methods_on_trait() {
use async_trait::async_trait;
use crate::{Result, pr::PrProvider};
#[derive(Debug)]
struct Check;
#[async_trait]
impl PrProvider for Check {
async fn create(&self, _args: crate::pr::CreatePrArgs) -> Result<crate::pr::PrData> {
unimplemented!()
}
async fn list(
&self,
_args: crate::pr::ListPrArgs,
) -> Result<crate::paging::Paged<crate::pr::PrData>> {
unimplemented!()
}
async fn view(&self, _number: u64) -> Result<crate::pr::PrData> {
unimplemented!()
}
async fn close(&self, _number: u64) -> Result<crate::pr::PrData> {
unimplemented!()
}
async fn reopen(&self, _number: u64) -> Result<crate::pr::PrData> {
unimplemented!()
}
async fn comment(
&self,
_number: u64,
_body: &str,
) -> Result<crate::types::CommentData> {
unimplemented!()
}
async fn merge(
&self,
_number: u64,
_strategy: Option<crate::types::MergeStrategy>,
_auto: bool,
) -> Result<crate::types::MergeResult> {
unimplemented!()
}
async fn checkout(&self, _number: u64) -> Result<()> {
unimplemented!()
}
async fn mark_ready(&self, _number: u64) -> Result<crate::pr::PrData> {
unimplemented!()
}
async fn mark_wip(&self, _number: u64) -> Result<crate::pr::PrData> {
unimplemented!()
}
async fn sync_branch(&self, _number: u64) -> Result<()> {
unimplemented!()
}
async fn diff(&self, _number: u64) -> Result<String> {
unimplemented!()
}
async fn patch(&self, _number: u64) -> Result<String> {
unimplemented!()
}
async fn default_branch(&self) -> Result<String> {
unimplemented!()
}
}
let check = Check;
let _ = format!("{check:?}");
}
#[test]
fn test_should_return_body_unchanged_when_no_issues() {
let body = Some("Existing body".to_string());
let result = crate::pr::format_closing_body(&body, &[], "Closes");
assert_eq!(result, Some("Existing body".to_string()));
}
#[test]
fn test_should_return_none_when_no_body_and_no_issues() {
let result = crate::pr::format_closing_body(&None, &[], "Closes");
assert!(result.is_none());
}
#[test]
fn test_should_create_closing_body_when_no_existing_body() {
let result = crate::pr::format_closing_body(&None, &[24], "Closes");
assert_eq!(result, Some("Closes #24".to_string()));
}
#[test]
fn test_should_append_closing_to_existing_body() {
let body = Some("Feature description".to_string());
let result = crate::pr::format_closing_body(&body, &[24], "Closes");
assert_eq!(
result,
Some("Feature description\n\nCloses #24".to_string())
);
}
#[test]
fn test_should_handle_multiple_issues() {
let body = Some("Description".to_string());
let result = crate::pr::format_closing_body(&body, &[24, 23], "Closes");
assert_eq!(
result,
Some("Description\n\nCloses #24\nCloses #23".to_string())
);
}
#[test]
fn test_should_use_custom_keyword() {
let result = crate::pr::format_closing_body(&None, &[42], "Fixes");
assert_eq!(result, Some("Fixes #42".to_string()));
}
#[test]
fn test_should_treat_empty_body_as_no_body() {
let body = Some(String::new());
let result = crate::pr::format_closing_body(&body, &[10], "Closes");
assert_eq!(result, Some("Closes #10".to_string()));
}
#[test]
fn test_should_have_closes_issues_field() {
let args = crate::pr::CreatePrArgs {
title: "Test".to_string(),
body: None,
head: "feature".to_string(),
base: "main".to_string(),
draft: false,
repo: None,
closes_issues: vec![24, 23],
milestone: None,
};
assert_eq!(args.closes_issues, vec![24, 23]);
}
}