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 add_labels(&self, number: u64, labels: &[String]) -> Result<()>;
139
140    /// 从指定 Issue 移除一个标签。
141    ///
142    /// # Errors
143    ///
144    /// 当 Issue 不存在、标签不存在或平台 API 调用失败时返回错误。
145    async fn remove_label(&self, number: u64, label: &str) -> Result<()>;
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    /// 构造用于 serde 测试的样本 JSON,字段命名与 `gh issue view --json` 输出一致。
153    fn sample_issue_json() -> &'static str {
154        r#"{
155            "number": 42,
156            "title": "Fix login bug",
157            "body": "Reproduced on v1.2.3",
158            "state": "open",
159            "labels": [
160                {"name": "bug", "color": "d73a4a", "description": "Something isn't working"}
161            ],
162            "author": {"login": "octocat", "id": "1"},
163            "assignees": [{"login": "alice", "id": "7"}],
164            "createdAt": "2026-01-15T09:30:00Z",
165            "updatedAt": "2026-01-16T11:00:00Z",
166            "url": "https://github.com/octocat/hello-world/issues/42"
167        }"#
168    }
169
170    #[test]
171    fn test_should_deserialize_issue_data_from_gh_cli_json() {
172        let json = sample_issue_json();
173        let issue: IssueData = serde_json::from_str(json).expect("valid IssueData JSON");
174
175        assert_eq!(issue.number, 42);
176        assert_eq!(issue.title, "Fix login bug");
177        assert_eq!(issue.body.as_deref(), Some("Reproduced on v1.2.3"));
178        assert_eq!(issue.state, State::Open);
179        assert_eq!(issue.labels.len(), 1);
180        assert_eq!(issue.labels[0].name, "bug");
181        assert_eq!(issue.labels[0].color.as_deref(), Some("d73a4a"));
182        assert_eq!(issue.author.login, "octocat");
183        assert_eq!(issue.author.id, "1");
184        assert_eq!(issue.assignees.len(), 1);
185        assert_eq!(issue.assignees[0].login, "alice");
186        assert_eq!(
187            issue.url,
188            "https://github.com/octocat/hello-world/issues/42"
189        );
190    }
191
192    #[test]
193    fn test_should_roundtrip_issue_data_via_serde() {
194        let json = sample_issue_json();
195        let issue: IssueData = serde_json::from_str(json).expect("deserialize");
196        let re_serialized = serde_json::to_string(&issue).expect("serialize");
197        let round_tripped: IssueData =
198            serde_json::from_str(&re_serialized).expect("re-deserialize");
199
200        assert_eq!(round_tripped.number, issue.number);
201        assert_eq!(round_tripped.title, issue.title);
202        assert_eq!(round_tripped.body, issue.body);
203        assert_eq!(round_tripped.state, issue.state);
204        assert_eq!(round_tripped.url, issue.url);
205        assert_eq!(round_tripped.created_at, issue.created_at);
206        assert_eq!(round_tripped.updated_at, issue.updated_at);
207    }
208
209    #[test]
210    fn test_should_deserialize_issue_with_null_optional_body() {
211        let json = r#"{
212            "number": 1,
213            "title": "t",
214            "body": null,
215            "state": "closed",
216            "labels": [],
217            "author": {"login": "u", "id": "2"},
218            "assignees": [],
219            "createdAt": "2026-02-01T00:00:00Z",
220            "updatedAt": "2026-02-02T00:00:00Z",
221            "url": "https://example.com/1"
222        }"#;
223        let issue: IssueData = serde_json::from_str(json).expect("deserialize");
224        assert!(issue.body.is_none());
225        assert_eq!(issue.state, State::Closed);
226        assert!(issue.labels.is_empty());
227        assert!(issue.assignees.is_empty());
228    }
229
230    #[test]
231    fn test_should_omit_none_body_on_serialize() {
232        let json = sample_issue_json();
233        let mut issue: IssueData = serde_json::from_str(json).expect("deserialize");
234        issue.body = None;
235        let serialized = serde_json::to_string(&issue).expect("serialize");
236        // `body: null` 不应出现在输出中
237        assert!(!serialized.contains("\"body\":null"));
238        assert!(!serialized.contains("\"body\": null"));
239    }
240
241    #[test]
242    fn test_should_default_empty_labels_and_assignees_when_missing() {
243        let json = r#"{
244            "number": 7,
245            "title": "t",
246            "state": "open",
247            "author": {"login": "u", "id": "3"},
248            "createdAt": "2026-03-01T00:00:00Z",
249            "updatedAt": "2026-03-02T00:00:00Z",
250            "url": "https://example.com/7"
251        }"#;
252        let issue: IssueData = serde_json::from_str(json).expect("deserialize");
253        assert!(issue.labels.is_empty());
254        assert!(issue.assignees.is_empty());
255    }
256
257    #[test]
258    fn test_list_issue_args_default_is_empty() {
259        let args = ListIssueArgs::default();
260        assert!(args.state.is_none());
261        assert!(args.labels.is_empty());
262        assert!(args.assignee.is_none());
263        assert!(args.search.is_none());
264        assert!(args.limit.is_none());
265    }
266}