Skip to main content

gitflow_core/
issue.rs

1//! Issue 领域类型与平台抽象。
2//!
3//! 定义了 Issue 的数据表示、创建/列表参数,以及跨平台实现所需的
4//! [`IssueProvider`] 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::{CommentData, Label, State, UserSummary, deserialize_u64_or_string},
15};
16
17/// Issue 数据。
18///
19/// 由平台实现填充并返回给上层命令。字段命名与 GitHub CLI 输出的 JSON 字段对齐(camelCase)。
20/// `number` 使用自定义反序列化兼容 `GitCode` CLI 返回的字符串格式。
21#[derive(Debug, Clone, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct IssueData {
24    /// Issue 编号(平台内唯一)。
25    #[serde(deserialize_with = "deserialize_u64_or_string")]
26    pub number: u64,
27    /// Issue 标题。
28    pub title: String,
29    /// Issue 正文(Markdown)。
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub body: Option<String>,
32    /// Issue 当前状态。
33    pub state: State,
34    /// 附加的标签列表。
35    #[serde(default)]
36    pub labels: Vec<Label>,
37    /// Issue 作者。
38    pub author: UserSummary,
39    /// 被指派的成员列表。
40    #[serde(default)]
41    pub assignees: Vec<UserSummary>,
42    /// The milestone this issue is attached to, if any.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub milestone: Option<crate::types::MilestoneRef>,
45    /// 创建时间(UTC)。API 未返回该字段时为 `None`——绝不用当前时间伪造。
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub created_at: Option<DateTime<Utc>>,
48    /// 最近更新时间(UTC)。API 未返回该字段时为 `None`——绝不用当前时间伪造。
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub updated_at: Option<DateTime<Utc>>,
51    /// Issue 的 Web URL。
52    pub url: String,
53}
54
55/// 创建 Issue 所需参数。
56#[derive(Debug, Clone)]
57pub struct CreateIssueArgs {
58    /// Issue 标题。
59    pub title: String,
60    /// Issue 正文(可选)。
61    pub body: Option<String>,
62    /// 附加的标签名列表。
63    pub labels: Vec<String>,
64    /// 指派的登录名列表。
65    pub assignees: Vec<String>,
66    /// Milestone identifier to attach on creation (`NUMBER` or exact `TITLE`), if any.
67    pub milestone: Option<String>,
68}
69
70/// 编辑 Issue 所需参数(部分更新)。
71///
72/// 未设置的字段(`None`)在调用 [`IssueProvider::edit`] 时保持当前值不变。
73#[derive(Debug, Clone, Default)]
74pub struct EditIssueArgs {
75    /// 新标题(不修改时为 `None`)。
76    pub title: Option<String>,
77    /// 新正文(不修改时为 `None`)。
78    pub body: Option<String>,
79    /// Milestone change: `None` = don't touch; `Some(None)` = unassign;
80    /// `Some(Some(identifier))` = set to this milestone (`NUMBER` or `TITLE`).
81    pub milestone: Option<Option<String>>,
82}
83
84/// 列出 Issue 的过滤参数。
85///
86/// 所有字段均可选,未设置时使用平台默认值。
87#[derive(Debug, Clone, Default)]
88pub struct ListIssueArgs {
89    /// 按状态过滤。
90    pub state: Option<State>,
91    /// 按标签名过滤。
92    pub labels: Vec<String>,
93    /// 关键字搜索条件。
94    pub search: Option<String>,
95    /// 返回数量上限。
96    pub limit: Option<u32>,
97    /// Filter by milestone identifier (`NUMBER` or exact `TITLE`), if any.
98    pub milestone: Option<String>,
99}
100
101/// Issue 操作的平台抽象。
102///
103/// 所有平台实现(GitHub/GitLab/GitCode)都必须实现此 trait,
104/// 以提供统一的 Issue 创建、列表、查看、关闭、评论及标签管理能力。
105///
106/// # Errors
107///
108/// 所有方法在平台调用失败、反序列化失败或鉴权失败时返回 [`CoreError`](crate::CoreError)。
109///
110/// [`CoreError`]: crate::CoreError
111#[async_trait]
112pub trait IssueProvider: std::fmt::Debug + Send + Sync {
113    /// 创建一条新 Issue,返回平台生成的完整数据。
114    ///
115    /// # Errors
116    ///
117    /// 当平台 API 调用失败或参数非法时返回错误。
118    async fn create(&self, args: CreateIssueArgs) -> Result<IssueData>;
119
120    /// 编辑 Issue 的标题和/或正文(部分更新)。
121    ///
122    /// 未在 `args` 中设置的字段保持 Issue 当前值不变。
123    ///
124    /// # Errors
125    ///
126    /// 当 Issue 不存在或平台 API 调用失败时返回错误。
127    async fn edit(&self, number: u64, args: EditIssueArgs) -> Result<IssueData>;
128
129    /// 根据过滤条件列出 Issue 列表。
130    ///
131    /// 返回的 [`Paged`] 携带截断标志:平台侧的列表命令默认只返回首页,
132    /// 本方法保证要么取满上限,要么诚实报告还有更多。
133    ///
134    /// # Errors
135    ///
136    /// 当平台 API 调用失败或过滤条件非法时返回错误。
137    async fn list(&self, args: ListIssueArgs) -> Result<Paged<IssueData>>;
138
139    /// 查看指定编号的 Issue 详情。
140    ///
141    /// # Errors
142    ///
143    /// 当 Issue 不存在或平台 API 调用失败时返回错误。
144    async fn view(&self, number: u64) -> Result<IssueData>;
145
146    /// 关闭指定编号的 Issue,返回更新后的数据。
147    ///
148    /// # Errors
149    ///
150    /// 当 Issue 不存在或平台 API 调用失败时返回错误。
151    async fn close(&self, number: u64) -> Result<IssueData>;
152
153    /// 重新打开指定编号的 Issue,返回更新后的数据。
154    ///
155    /// # Errors
156    ///
157    /// 当 Issue 不存在或平台 API 调用失败时返回错误。
158    async fn reopen(&self, number: u64) -> Result<IssueData>;
159
160    /// 在指定 Issue 上添加评论,返回新建评论的数据。
161    ///
162    /// # Errors
163    ///
164    /// 当 Issue 不存在、`body` 为空或平台 API 调用失败时返回错误。
165    async fn comment(&self, number: u64, body: &str) -> Result<CommentData>;
166
167    /// 列出指定 Issue 的评论。
168    ///
169    /// `limit` 为 `None` 时取至 [`crate::paging::DEFAULT_LIST_LIMIT`]。
170    ///
171    /// # Errors
172    ///
173    /// 当 Issue 不存在或平台 API 调用失败时返回错误。
174    async fn list_comments(&self, number: u64, limit: Option<u32>) -> Result<Paged<CommentData>>;
175
176    /// 为指定 Issue 添加标签。
177    ///
178    /// # Errors
179    ///
180    /// 当 Issue 不存在、标签列表为空或平台 API 调用失败时返回错误。
181    async fn add_labels(&self, number: u64, labels: &[String]) -> Result<()>;
182
183    /// 从指定 Issue 移除一个标签。
184    ///
185    /// # Errors
186    ///
187    /// 当 Issue 不存在、标签不存在或平台 API 调用失败时返回错误。
188    async fn remove_label(&self, number: u64, label: &str) -> Result<()>;
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    /// 构造用于 serde 测试的样本 JSON,字段命名与 `gh issue view --json` 输出一致。
196    fn sample_issue_json() -> &'static str {
197        r#"{
198            "number": 42,
199            "title": "Fix login bug",
200            "body": "Reproduced on v1.2.3",
201            "state": "open",
202            "labels": [
203                {"name": "bug", "color": "d73a4a", "description": "Something isn't working"}
204            ],
205            "author": {"login": "octocat", "id": "1"},
206            "assignees": [{"login": "alice", "id": "7"}],
207            "createdAt": "2026-01-15T09:30:00Z",
208            "updatedAt": "2026-01-16T11:00:00Z",
209            "url": "https://github.com/octocat/hello-world/issues/42"
210        }"#
211    }
212
213    #[test]
214    fn test_should_deserialize_issue_data_from_gh_cli_json() {
215        let json = sample_issue_json();
216        let issue: IssueData = serde_json::from_str(json).expect("valid IssueData JSON");
217
218        assert_eq!(issue.number, 42);
219        assert_eq!(issue.title, "Fix login bug");
220        assert_eq!(issue.body.as_deref(), Some("Reproduced on v1.2.3"));
221        assert_eq!(issue.state, State::Open);
222        assert_eq!(issue.labels.len(), 1);
223        assert_eq!(issue.labels[0].name, "bug");
224        assert_eq!(issue.labels[0].color.as_deref(), Some("d73a4a"));
225        assert_eq!(issue.author.login, "octocat");
226        assert_eq!(issue.author.id, "1");
227        assert_eq!(issue.assignees.len(), 1);
228        assert_eq!(issue.assignees[0].login, "alice");
229        assert_eq!(
230            issue.url,
231            "https://github.com/octocat/hello-world/issues/42"
232        );
233    }
234
235    #[test]
236    fn test_should_roundtrip_issue_data_via_serde() {
237        let json = sample_issue_json();
238        let issue: IssueData = serde_json::from_str(json).expect("deserialize");
239        let re_serialized = serde_json::to_string(&issue).expect("serialize");
240        let round_tripped: IssueData =
241            serde_json::from_str(&re_serialized).expect("re-deserialize");
242
243        assert_eq!(round_tripped.number, issue.number);
244        assert_eq!(round_tripped.title, issue.title);
245        assert_eq!(round_tripped.body, issue.body);
246        assert_eq!(round_tripped.state, issue.state);
247        assert_eq!(round_tripped.url, issue.url);
248        assert_eq!(round_tripped.created_at, issue.created_at);
249        assert_eq!(round_tripped.updated_at, issue.updated_at);
250    }
251
252    #[test]
253    fn test_should_deserialize_issue_with_null_optional_body() {
254        let json = r#"{
255            "number": 1,
256            "title": "t",
257            "body": null,
258            "state": "closed",
259            "labels": [],
260            "author": {"login": "u", "id": "2"},
261            "assignees": [],
262            "createdAt": "2026-02-01T00:00:00Z",
263            "updatedAt": "2026-02-02T00:00:00Z",
264            "url": "https://example.com/1"
265        }"#;
266        let issue: IssueData = serde_json::from_str(json).expect("deserialize");
267        assert!(issue.body.is_none());
268        assert_eq!(issue.state, State::Closed);
269        assert!(issue.labels.is_empty());
270        assert!(issue.assignees.is_empty());
271    }
272
273    #[test]
274    fn test_should_omit_none_body_on_serialize() {
275        let json = sample_issue_json();
276        let mut issue: IssueData = serde_json::from_str(json).expect("deserialize");
277        issue.body = None;
278        let serialized = serde_json::to_string(&issue).expect("serialize");
279        // `body: null` 不应出现在输出中
280        assert!(!serialized.contains("\"body\":null"));
281        assert!(!serialized.contains("\"body\": null"));
282    }
283
284    #[test]
285    fn test_should_default_empty_labels_and_assignees_when_missing() {
286        let json = r#"{
287            "number": 7,
288            "title": "t",
289            "state": "open",
290            "author": {"login": "u", "id": "3"},
291            "createdAt": "2026-03-01T00:00:00Z",
292            "updatedAt": "2026-03-02T00:00:00Z",
293            "url": "https://example.com/7"
294        }"#;
295        let issue: IssueData = serde_json::from_str(json).expect("deserialize");
296        assert!(issue.labels.is_empty());
297        assert!(issue.assignees.is_empty());
298    }
299
300    #[test]
301    fn test_list_issue_args_default_is_empty() {
302        let args = ListIssueArgs::default();
303        assert!(args.state.is_none());
304        assert!(args.labels.is_empty());
305        assert!(args.search.is_none());
306        assert!(args.limit.is_none());
307    }
308
309    #[test]
310    fn test_edit_issue_args_default_is_empty() {
311        let args = EditIssueArgs::default();
312        assert!(args.title.is_none());
313        assert!(args.body.is_none());
314    }
315}