Skip to main content

gitflow_core/
pr.rs

1//! Pull Request 领域类型与平台抽象。
2//!
3//! 定义了 PR 的数据表示、创建/列表参数,以及跨平台实现所需的
4//! [`PrProvider`] trait。GitHub、GitLab、GitCode 等平台实现都
5//! 需实现该 trait,使上层命令层可统一消费。
6
7use 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/// Pull Request 数据。
20///
21/// 由平台实现填充并返回给上层命令。字段命名与 `gh pr`
22/// CLI 输出的 JSON 字段对齐(camelCase)。
23#[derive(Debug, Clone, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct PrData {
26    /// PR 编号(平台内唯一)。
27    #[serde(deserialize_with = "deserialize_u64_or_string")]
28    pub number: u64,
29    /// PR 标题。
30    pub title: String,
31    /// PR 正文(Markdown)。
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub body: Option<String>,
34    /// PR 当前状态。
35    pub state: State,
36    /// 是否为草稿 PR。
37    #[serde(alias = "isDraft")]
38    pub draft: bool,
39    /// PR 作者。
40    pub author: UserSummary,
41    /// 目标分支。
42    #[serde(alias = "baseRefName")]
43    pub base_branch: String,
44    /// 来源分支。
45    #[serde(alias = "headRefName")]
46    pub head_branch: String,
47    /// 创建时间(UTC)。API 未返回该字段时为 `None`——绝不用当前时间伪造。
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub created_at: Option<DateTime<Utc>>,
50    /// 最近更新时间(UTC)。API 未返回该字段时为 `None`——绝不用当前时间伪造。
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub updated_at: Option<DateTime<Utc>>,
53    /// 合并时间(UTC);未合并时为 `None`。
54    ///
55    /// 存在的必要:[`State`] 把 `MERGED` alias 进 `Closed`,仅凭 `state`
56    /// **无法区分"已合并"与"关闭但未合并"**,而 Branch Finish 必须区分二者
57    /// 才能安全删分支。`gh` 提供 `mergedAt`;GitLab/GitCode 若不返回则为 `None`,
58    /// 调用方须把 `None` 当作"未知"而非"未合并"。
59    pub merged_at: Option<DateTime<Utc>>,
60    /// The milestone this PR is attached to, if any.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub milestone: Option<crate::types::MilestoneRef>,
63    /// PR 的 Web URL。
64    pub url: String,
65}
66
67/// 创建 PR 所需参数。
68#[derive(Debug, Clone)]
69pub struct CreatePrArgs {
70    /// PR 标题。
71    pub title: String,
72    /// PR 正文(可选)。
73    pub body: Option<String>,
74    /// 来源分支。
75    pub head: String,
76    /// 目标分支。
77    pub base: String,
78    /// 是否以草稿方式创建。
79    pub draft: bool,
80    /// 可选的目标仓库(`owner/name` 格式),未设置时使用默认仓库。
81    pub repo: Option<String>,
82    /// 需要在合并时自动关闭的 Issue 编号列表。
83    pub closes_issues: Vec<u64>,
84    /// Milestone identifier to attach on creation (`NUMBER` or exact `TITLE`), if any.
85    pub milestone: Option<String>,
86}
87
88/// 列出 PR 的过滤参数。
89///
90/// 所有字段均可选,未设置时使用平台默认值。
91#[derive(Debug, Clone, Default)]
92pub struct ListPrArgs {
93    /// 按状态过滤。
94    pub state: Option<State>,
95    /// 返回数量上限。
96    pub limit: Option<u32>,
97}
98
99/// PR 操作的平台抽象。
100///
101/// 所有平台实现(GitHub/GitLab/GitCode)都必须实现此 trait,
102/// 以提供统一的 PR 创建、列表、查看、关闭、合并、检出等能力。
103///
104/// # Errors
105///
106/// 所有方法在平台调用失败、反序列化失败或鉴权失败时返回 [`CoreError`](crate::CoreError)。
107///
108/// [`CoreError`]: crate::CoreError
109#[async_trait]
110pub trait PrProvider: std::fmt::Debug + Send + Sync {
111    /// 创建一条新 PR,返回平台生成的完整数据。
112    ///
113    /// # Errors
114    ///
115    /// 当平台 API 调用失败或参数非法时返回错误。
116    async fn create(&self, args: CreatePrArgs) -> Result<PrData>;
117
118    /// 根据过滤条件列出 PR 列表。
119    ///
120    /// 返回的 [`Paged`] 携带截断标志,语义见 [`crate::paging`]。
121    ///
122    /// # Errors
123    ///
124    /// 当平台 API 调用失败或过滤条件非法时返回错误。
125    async fn list(&self, args: ListPrArgs) -> Result<Paged<PrData>>;
126
127    /// 查看指定编号的 PR 详情。
128    ///
129    /// # Errors
130    ///
131    /// 当 PR 不存在或平台 API 调用失败时返回错误。
132    async fn view(&self, number: u64) -> Result<PrData>;
133
134    /// 关闭指定编号的 PR,返回更新后的数据。
135    ///
136    /// # Errors
137    ///
138    /// 当 PR 不存在或平台 API 调用失败时返回错误。
139    async fn close(&self, number: u64) -> Result<PrData>;
140
141    /// 重新打开指定编号的 PR,返回更新后的数据。
142    ///
143    /// # Errors
144    ///
145    /// 当 PR 不存在或平台 API 调用失败时返回错误。
146    async fn reopen(&self, number: u64) -> Result<PrData>;
147
148    /// 在指定 PR 上添加评论,返回新建评论的数据。
149    ///
150    /// # Errors
151    ///
152    /// 当 PR 不存在、`body` 为空或平台 API 调用失败时返回错误。
153    async fn comment(&self, number: u64, body: &str) -> Result<CommentData>;
154
155    /// 合并指定编号的 PR,返回合并结果。
156    ///
157    /// `strategy` 指定合并策略(merge/squash/rebase)。
158    /// 未指定时使用平台默认策略。
159    ///
160    /// `auto` 为 `true` 时**排队合并**:满足条件即由平台自动完成合并,
161    /// 调用方不必等待 CI。GitHub 与 GitLab 原生支持;GitCode 不支持,
162    /// 传 `true` 会返回 [`CoreError::Platform`](与 `PipelineProvider` 的处理一致)。
163    ///
164    /// # Errors
165    ///
166    /// 当 PR 不存在、无法合并、平台不支持 `auto` 或平台 API 调用失败时返回错误。
167    async fn merge(
168        &self,
169        number: u64,
170        strategy: Option<MergeStrategy>,
171        auto: bool,
172    ) -> Result<MergeResult>;
173
174    /// 在本地检出指定 PR 的分支。
175    ///
176    /// # Errors
177    ///
178    /// 当 PR 不存在或 git 操作失败时返回错误。
179    async fn checkout(&self, number: u64) -> Result<()>;
180
181    /// 将草稿 PR 标记为可审查状态(ready for review)。
182    ///
183    /// # Errors
184    ///
185    /// 当 PR 不存在、不是草稿或平台 API 调用失败时返回错误。
186    async fn mark_ready(&self, number: u64) -> Result<PrData>;
187
188    /// 将 PR 标记为草稿状态(work in progress)。
189    ///
190    /// # Errors
191    ///
192    /// 当 PR 不存在或平台 API 调用失败时返回错误。
193    async fn mark_wip(&self, number: u64) -> Result<PrData>;
194
195    /// 同步 PR 分支(将 base 分支的最新变更合入 head 分支)。
196    ///
197    /// # Errors
198    ///
199    /// 当 PR 不存在或同步失败时返回错误。
200    async fn sync_branch(&self, number: u64) -> Result<()>;
201
202    /// 获取指定 PR 的统一差异格式(unified diff)文本。
203    ///
204    /// 返回平台原生的 unified diff 输出,可直接用于 `git apply`。
205    ///
206    /// # Errors
207    ///
208    /// 当 PR 不存在或平台 API 调用失败时返回 [`CoreError`]。
209    ///
210    /// [`CoreError`]: crate::CoreError
211    async fn diff(&self, number: u64) -> Result<String>;
212
213    /// 获取指定 PR 的 patch 格式文本(含邮件头信息)。
214    ///
215    /// 返回包含 commit 元数据的 patch 格式输出,可用于 `git am`。
216    ///
217    /// # Errors
218    ///
219    /// 当 PR 不存在或平台 API 调用失败时返回 [`CoreError`]。
220    ///
221    /// [`CoreError`]: crate::CoreError
222    async fn patch(&self, number: u64) -> Result<String>;
223
224    /// 查询仓库配置的默认分支(如 `main`、`dev`)。
225    ///
226    /// 用于 `pr create` 在未显式指定 `--base` 时探测目标分支,避免硬编码
227    /// `"main"` 导致默认分支非 `main` 的仓库创建出目标错误的 PR/MR。
228    ///
229    /// # Errors
230    ///
231    /// 当平台 API 调用失败或平台不支持该查询(如 GitCode)时返回错误。
232    async fn default_branch(&self) -> Result<String>;
233}
234
235/// Format closing keywords and append to body.
236///
237/// `keyword` is the platform closing verb (e.g. `"Closes"`, `"Fixes"`).
238/// Returns `None` if both `body` is `None`/empty and `issues` is empty.
239/// Returns the original body unchanged if `issues` is empty.
240///
241/// # Examples
242///
243/// ```
244/// use gitflow_core::pr::format_closing_body;
245///
246/// let body = Some("Description".to_string());
247/// let result = format_closing_body(&body, &[24, 23], "Closes");
248/// assert_eq!(result, Some("Description\n\nCloses #24\nCloses #23".to_string()));
249/// ```
250#[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    /// 构造用于 serde 测试的样本 JSON,字段命名与 `gh pr view --json` 输出一致。
271    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        // `body: null` 不应出现在输出中
351        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        // camelCase 字段必须被保留
361        assert!(serialized.contains("\"baseBranch\""));
362        assert!(serialized.contains("\"headBranch\""));
363        assert!(serialized.contains("\"createdAt\""));
364        assert!(serialized.contains("\"updatedAt\""));
365        // snake_case 字段不应出现
366        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    /// Compile-time check that `PrProvider` has `diff()` and `patch()` methods.
378    ///
379    /// This test passes if the code compiles; the runtime assertion is trivial.
380    #[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        // Verify Check implements PrProvider with diff() and patch()
448        let check = Check;
449        let _ = format!("{check:?}");
450    }
451
452    // --- format_closing_body tests ---
453
454    #[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}