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