Skip to main content

gitflow_github/
issue.rs

1//! GitHub Issue 提供者实现。
2//!
3//! 通过 `gh` CLI 实现 [`IssueProvider`] trait,支持 Issue 的创建、列表、查看、
4//! 关闭、重新打开、评论及标签管理。
5//! 所有方法通过 `tokio::process::Command` 调用 `gh`,捕获 stdout 并解析 JSON。
6
7use async_trait::async_trait;
8use gitflow_core::{
9    CoreError, Result,
10    issue::{CreateIssueArgs, IssueData, IssueProvider, ListIssueArgs},
11    types::{CommentData, Label, State, UserSummary},
12};
13use tracing::debug;
14
15use crate::{
16    error::parse_gh_error,
17    runner::{CommandRunner, RealCommandRunner},
18};
19
20/// `gh issue` 请求的 JSON 字段列表。
21const ISSUE_FIELDS: &str =
22    "number,title,body,state,labels,author,assignees,createdAt,updatedAt,url";
23
24/// GitHub Issue 提供者,通过 `gh` CLI 操作。
25///
26/// 该结构体通过调用 `gh` CLI 实现 [`IssueProvider`] trait 的所有方法,
27/// 使上层命令能够以统一的方式操作 GitHub Issue。
28///
29/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
30/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
31///
32/// # Examples
33///
34/// ```no_run
35/// use gitflow_github::GitHubIssueProvider;
36///
37/// let provider = GitHubIssueProvider::new("octocat/hello-world");
38/// ```
39#[derive(Debug, Clone)]
40pub struct GitHubIssueProvider<R: CommandRunner = RealCommandRunner> {
41    /// GitHub `owner/repo`,如 `"byx-darwin/gitflow-cli"`。
42    repo: String,
43    /// 用于执行 `gh` CLI 命令的 runner。
44    runner: R,
45}
46
47impl GitHubIssueProvider<RealCommandRunner> {
48    /// 创建新的 GitHub Issue 提供者,使用真实的进程执行器。
49    ///
50    /// `repo` 格式为 `owner/repo`。
51    #[must_use]
52    pub fn new(repo: impl Into<String>) -> Self {
53        Self {
54            repo: repo.into(),
55            runner: RealCommandRunner,
56        }
57    }
58}
59
60impl<R: CommandRunner> GitHubIssueProvider<R> {
61    /// 使用自定义 [`CommandRunner`] 创建提供者。
62    ///
63    /// 主要用于测试,可注入模拟 runner 以控制 `gh` CLI 的输出。
64    /// `repo` 格式为 `owner/repo`。
65    #[must_use]
66    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
67        Self {
68            repo: repo.into(),
69            runner,
70        }
71    }
72
73    /// 创建缺失的标签(如已存在则忽略"已存在"错误)。
74    ///
75    /// 调用 `gh label create <name> --color ededed --repo <repo> --force`。
76    /// `--force` 确保在竞态条件(标签被并发创建)下仍保持幂等。
77    ///
78    /// # Errors
79    ///
80    /// 当 `gh label create` 调用失败时返回错误。
81    async fn ensure_label_exists(&self, name: &str) -> Result<()> {
82        debug!(repo = %self.repo, name, "auto-creating missing label via `gh label create`");
83
84        let output = self
85            .runner
86            .run(
87                "gh",
88                &[
89                    "label", "create", name, "--color", "ededed", "--repo", &self.repo, "--force",
90                ],
91            )
92            .await
93            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label create: {e}")))?;
94
95        if !output.status.success() {
96            let mut gh_err = parse_gh_error(&output.stderr);
97            gh_err.user_message = format!("自动创建标签 '{name}' 失败:{}", gh_err.user_message);
98            return Err(gh_err.into());
99        }
100
101        Ok(())
102    }
103}
104
105#[async_trait]
106impl<R: CommandRunner + 'static> IssueProvider for GitHubIssueProvider<R> {
107    async fn create(&self, args: CreateIssueArgs) -> Result<IssueData> {
108        let labels_joined = args.labels.join(",");
109        let assignees_joined = args.assignees.join(",");
110
111        let mut cmd_args: Vec<&str> = vec![
112            "issue",
113            "create",
114            "--repo",
115            &self.repo,
116            "--title",
117            &args.title,
118        ];
119
120        if let Some(body) = &args.body {
121            cmd_args.push("--body");
122            cmd_args.push(body);
123        }
124
125        if !args.labels.is_empty() {
126            cmd_args.push("--label");
127            cmd_args.push(&labels_joined);
128        }
129
130        if !args.assignees.is_empty() {
131            cmd_args.push("--assignee");
132            cmd_args.push(&assignees_joined);
133        }
134
135        debug!(repo = %self.repo, title = %args.title, "spawning `gh issue create`");
136
137        let output = self
138            .runner
139            .run("gh", &cmd_args)
140            .await
141            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
142
143        if !output.status.success() {
144            // `gh issue create` fails when a requested label doesn't exist.
145            // Auto-create missing labels and retry once.
146            let missing = extract_missing_labels_from_error(&output.stderr);
147            if !missing.is_empty() {
148                debug!(
149                    repo = %self.repo,
150                    missing_count = missing.len(),
151                    "auto-creating missing label(s) before retrying issue create"
152                );
153                for label in &missing {
154                    self.ensure_label_exists(label).await?;
155                }
156
157                let retry_output = self.runner.run("gh", &cmd_args).await.map_err(|e| {
158                    CoreError::Platform(format!("Failed to spawn gh on retry: {e}"))
159                })?;
160
161                if !retry_output.status.success() {
162                    return Err(parse_gh_error(&retry_output.stderr).into());
163                }
164
165                let stdout = String::from_utf8_lossy(&retry_output.stdout);
166                let issue_number = parse_issue_number_from_url(&stdout).ok_or_else(|| {
167                    CoreError::Platform(format!("Failed to parse issue URL from output: {stdout}"))
168                })?;
169                return self.view(issue_number).await;
170            }
171
172            return Err(parse_gh_error(&output.stderr).into());
173        }
174
175        // Parse the issue URL from stdout (format: https://github.com/owner/repo/issues/123)
176        let stdout = String::from_utf8_lossy(&output.stdout);
177        let issue_number = parse_issue_number_from_url(&stdout).ok_or_else(|| {
178            CoreError::Platform(format!("Failed to parse issue URL from output: {stdout}"))
179        })?;
180
181        // Fetch full issue details via view
182        self.view(issue_number).await
183    }
184
185    async fn list(&self, args: ListIssueArgs) -> Result<Vec<IssueData>> {
186        let mut cmd_args: Vec<&str> = vec![
187            "issue",
188            "list",
189            "--repo",
190            &self.repo,
191            "--json",
192            ISSUE_FIELDS,
193        ];
194
195        if let Some(state) = &args.state {
196            cmd_args.push("--state");
197            cmd_args.push(match state {
198                State::Open => "open",
199                State::Closed => "closed",
200            });
201        }
202
203        if let Some(ref search) = args.search {
204            cmd_args.push("--search");
205            cmd_args.push(search);
206        }
207
208        let limit_str = args.limit.map(|limit| limit.to_string());
209        if let Some(ref limit) = limit_str {
210            cmd_args.push("--limit");
211            cmd_args.push(limit);
212        }
213
214        debug!(repo = %self.repo, "spawning `gh issue list`");
215
216        let output = self
217            .runner
218            .run("gh", &cmd_args)
219            .await
220            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
221
222        if !output.status.success() {
223            return Err(parse_gh_error(&output.stderr).into());
224        }
225
226        let issues: Vec<IssueData> =
227            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
228
229        Ok(issues)
230    }
231
232    async fn view(&self, number: u64) -> Result<IssueData> {
233        debug!(repo = %self.repo, number, "spawning `gh issue view`");
234
235        let number_str = number.to_string();
236        let output = self
237            .runner
238            .run(
239                "gh",
240                &[
241                    "issue",
242                    "view",
243                    &number_str,
244                    "--repo",
245                    &self.repo,
246                    "--json",
247                    ISSUE_FIELDS,
248                ],
249            )
250            .await
251            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
252
253        if !output.status.success() {
254            return Err(parse_gh_error(&output.stderr).into());
255        }
256
257        let issue: IssueData =
258            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
259
260        Ok(issue)
261    }
262
263    /// 关闭指定编号的 Issue。
264    ///
265    /// 通过单次 `gh api repos/{owner}/{repo}/issues/{number} -X PATCH -f state=closed`
266    /// 调用更新状态,并直接解析 REST 响应获得更新后的完整 Issue 数据。
267    /// 该调用幂等:对已关闭的 Issue 再次关闭将成功返回其当前数据。
268    ///
269    /// # 设计说明(issue #117)
270    ///
271    /// 早期实现先调用 `gh issue close`,再用 `gh issue view --json` 重新获取详情。
272    /// 该双调用设计有两个缺陷:
273    ///
274    /// 1. `--json` 输出来自 `gh` 的 GraphQL 导出层,字段形状随 `gh` 版本漂移 (如 gh 2.94+ 的 bot
275    ///    author 省略 `id`),导致反序列化失败;
276    /// 2. 关闭操作已经成功时,二次获取的解析失败仍被误报为"关闭失败"。
277    ///
278    /// 改为单次 REST 调用后,变更与数据在同一响应中返回,两个缺陷同时消除。
279    /// REST 响应形状是 GitHub API 的稳定契约,bot 用户同样携带数字 `id`。
280    ///
281    /// # Errors
282    ///
283    /// 当 Issue 不存在、`gh` CLI 调用失败或响应解析失败时返回错误。
284    async fn close(&self, number: u64) -> Result<IssueData> {
285        debug!(repo = %self.repo, number, "spawning `gh api issues PATCH state=closed`");
286
287        let api_path = format!("repos/{repo}/issues/{number}", repo = self.repo);
288        let output = self
289            .runner
290            .run(
291                "gh",
292                &["api", &api_path, "-X", "PATCH", "-f", "state=closed"],
293            )
294            .await
295            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api issue close: {e}")))?;
296
297        if !output.status.success() {
298            return Err(parse_gh_error(&output.stderr).into());
299        }
300
301        let api_response: GitHubIssueApiResponse =
302            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
303
304        Ok(api_response.into())
305    }
306
307    /// 重新打开指定编号的 Issue。
308    ///
309    /// 通过单次 `gh api repos/{owner}/{repo}/issues/{number} -X PATCH -f state=open`
310    /// 调用更新状态,并直接解析 REST 响应获得更新后的完整 Issue 数据。
311    /// 该调用幂等:对未关闭的 Issue 再次打开将成功返回其当前数据。
312    ///
313    /// # 设计说明(issue #117)
314    ///
315    /// 与 [`close`](Self::close) 相同,改为单次 REST 调用以消除双调用的
316    /// 反序列化漂移与误报失败问题。
317    ///
318    /// # Errors
319    ///
320    /// 当 Issue 不存在、`gh` CLI 调用失败或响应解析失败时返回错误。
321    async fn reopen(&self, number: u64) -> Result<IssueData> {
322        debug!(repo = %self.repo, number, "spawning `gh api issues PATCH state=open`");
323
324        let api_path = format!("repos/{repo}/issues/{number}", repo = self.repo);
325        let output = self
326            .runner
327            .run("gh", &["api", &api_path, "-X", "PATCH", "-f", "state=open"])
328            .await
329            .map_err(|e| {
330                CoreError::Platform(format!("Failed to spawn gh api issue reopen: {e}"))
331            })?;
332
333        if !output.status.success() {
334            return Err(parse_gh_error(&output.stderr).into());
335        }
336
337        let api_response: GitHubIssueApiResponse =
338            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
339
340        Ok(api_response.into())
341    }
342
343    /// 在指定 Issue 上添加评论。
344    ///
345    /// 调用 `gh api repos/{repo}/issues/{number}/comments -X POST` 创建评论,
346    /// 直接从 POST 响应中解析新创建的评论数据。
347    ///
348    /// # Errors
349    ///
350    /// 当 Issue 不存在、`body` 为空或 `gh` CLI 调用失败时返回错误。
351    async fn comment(&self, number: u64, body: &str) -> Result<CommentData> {
352        debug!(repo = %self.repo, number, "spawning `gh api` POST to create issue comment");
353
354        let api_path = format!(
355            "repos/{repo}/issues/{number}/comments",
356            repo = self.repo,
357            number = number
358        );
359
360        let body_field = format!("body={body}");
361        let output = self
362            .runner
363            .run("gh", &["api", &api_path, "-X", "POST", "-f", &body_field])
364            .await
365            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api: {e}")))?;
366
367        if !output.status.success() {
368            return Err(parse_gh_error(&output.stderr).into());
369        }
370
371        let comment: GitHubCommentApiResponse =
372            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
373
374        Ok(comment.into())
375    }
376
377    /// 为指定 Issue 添加一个或多个标签。
378    ///
379    /// 调用 `gh issue edit <number> --repo <repo> --add-label <label>` 逐个添加标签。
380    /// 如果 `labels` 为空,不进行任何调用并返回成功。
381    ///
382    /// # 自动创建缺失标签
383    ///
384    /// 当 `gh issue edit --add-label` 因标签不存在而失败时,本方法会自动调用
385    /// `gh label create` 创建缺失的标签(使用默认颜色 `ededed`),然后重试原操作。
386    /// 这避免了手动同步仓库标签列表的繁琐流程。
387    ///
388    /// # Errors
389    ///
390    /// 当 Issue 不存在、标签创建失败或 `gh` CLI 调用失败时返回错误。
391    async fn add_labels(&self, number: u64, labels: &[String]) -> Result<()> {
392        debug!(
393            repo = %self.repo,
394            number,
395            label_count = labels.len(),
396            "spawning `gh issue edit --add-label`"
397        );
398
399        let number_str = number.to_string();
400        let mut cmd_args: Vec<&str> = vec!["issue", "edit", &number_str, "--repo", &self.repo];
401
402        for label in labels {
403            cmd_args.push("--add-label");
404            cmd_args.push(label);
405        }
406
407        let output = self
408            .runner
409            .run("gh", &cmd_args)
410            .await
411            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
412
413        if output.status.success() {
414            return Ok(());
415        }
416
417        // gh issue edit --add-label fails when a label doesn't exist in the repo.
418        // Auto-create the missing label(s) and retry once.
419        let missing = extract_missing_labels_from_error(&output.stderr);
420        if missing.is_empty() {
421            return Err(parse_gh_error(&output.stderr).into());
422        }
423
424        debug!(
425            repo = %self.repo,
426            missing_count = missing.len(),
427            "auto-creating missing label(s) before retry"
428        );
429
430        for label in &missing {
431            self.ensure_label_exists(label).await?;
432        }
433
434        // Retry the original add-label command.
435        let retry_output = self
436            .runner
437            .run("gh", &cmd_args)
438            .await
439            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh on retry: {e}")))?;
440
441        if !retry_output.status.success() {
442            return Err(parse_gh_error(&retry_output.stderr).into());
443        }
444
445        Ok(())
446    }
447
448    /// 从指定 Issue 移除一个标签。
449    ///
450    /// 调用 `gh issue edit <number> --repo <repo> --remove-label <label>` 移除标签。
451    ///
452    /// # Errors
453    ///
454    /// 当 Issue 不存在、标签未附加到该 Issue 或 `gh` CLI 调用失败时返回错误。
455    async fn remove_label(&self, number: u64, label: &str) -> Result<()> {
456        debug!(repo = %self.repo, number, label, "spawning `gh issue edit --remove-label`");
457
458        let number_str = number.to_string();
459        let output = self
460            .runner
461            .run(
462                "gh",
463                &[
464                    "issue",
465                    "edit",
466                    &number_str,
467                    "--repo",
468                    &self.repo,
469                    "--remove-label",
470                    label,
471                ],
472            )
473            .await
474            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
475
476        if !output.status.success() {
477            return Err(parse_gh_error(&output.stderr).into());
478        }
479
480        Ok(())
481    }
482}
483
484/// GitHub API 评论响应结构。
485///
486/// 用于解析 `gh api repos/{owner}/{repo}/issues/{number}/comments` 的返回数据。
487#[derive(Debug, Clone, serde::Deserialize)]
488pub struct GitHubCommentApiResponse {
489    pub id: u64,
490    pub body: String,
491    pub user: GitHubUser,
492    pub created_at: String,
493}
494
495/// GitHub API 标签响应结构(REST 形状)。
496///
497/// 用于解析 `gh api` 返回的 Issue 对象中的标签。REST 标签的 `description`
498/// 在无描述时为 `null`,`color` 为不带 `#` 前缀的十六进制字符串。
499#[derive(Debug, Clone, serde::Deserialize)]
500pub struct GitHubLabelApiResponse {
501    pub name: String,
502    #[serde(default)]
503    pub color: Option<String>,
504    #[serde(default)]
505    pub description: Option<String>,
506}
507
508/// GitHub API Issue 响应结构(REST 形状)。
509///
510/// 用于解析 `gh api repos/{owner}/{repo}/issues/{number} -X PATCH` 的返回数据。
511///
512/// 与 `gh issue view --json` 的 GraphQL 导出格式不同,REST 形状是 GitHub API
513/// 的稳定契约,不随 `gh` CLI 版本漂移:bot 用户同样携带数字 `id`,
514/// 也不存在 GraphQL 导出层新增/省略字段的问题(issue #117)。
515#[derive(Debug, Clone, serde::Deserialize)]
516pub struct GitHubIssueApiResponse {
517    pub number: u64,
518    pub title: String,
519    #[serde(default)]
520    pub body: Option<String>,
521    pub state: State,
522    #[serde(default)]
523    pub labels: Vec<GitHubLabelApiResponse>,
524    pub user: GitHubUser,
525    #[serde(default)]
526    pub assignees: Vec<GitHubUser>,
527    pub created_at: String,
528    pub updated_at: String,
529    pub html_url: String,
530}
531
532/// GitHub API 用户结构。
533#[derive(Debug, Clone, serde::Deserialize)]
534pub struct GitHubUser {
535    pub login: String,
536    pub id: u64,
537}
538
539impl From<GitHubCommentApiResponse> for CommentData {
540    fn from(api: GitHubCommentApiResponse) -> Self {
541        Self {
542            id: api.id,
543            body: api.body,
544            author: gitflow_core::types::UserSummary {
545                login: api.user.login,
546                id: api.user.id.to_string(),
547            },
548            created_at: parse_api_datetime(&api.created_at),
549        }
550    }
551}
552
553impl From<GitHubLabelApiResponse> for Label {
554    fn from(api: GitHubLabelApiResponse) -> Self {
555        Self {
556            name: api.name,
557            color: api.color,
558            description: api.description,
559        }
560    }
561}
562
563impl From<GitHubUser> for UserSummary {
564    fn from(user: GitHubUser) -> Self {
565        Self {
566            login: user.login,
567            id: user.id.to_string(),
568        }
569    }
570}
571
572impl From<GitHubIssueApiResponse> for IssueData {
573    fn from(api: GitHubIssueApiResponse) -> Self {
574        Self {
575            number: api.number,
576            title: api.title,
577            body: api.body,
578            state: api.state,
579            labels: api.labels.into_iter().map(Label::from).collect(),
580            author: api.user.into(),
581            assignees: api.assignees.into_iter().map(UserSummary::from).collect(),
582            created_at: parse_api_datetime(&api.created_at),
583            updated_at: parse_api_datetime(&api.updated_at),
584            url: api.html_url,
585        }
586    }
587}
588
589/// 解析 GitHub REST API 的 RFC 3339 时间戳。
590///
591/// 格式非法时记录警告并回退到 Unix 纪元,避免时间戳异常阻断主流程。
592fn parse_api_datetime(value: &str) -> chrono::DateTime<chrono::Utc> {
593    value.parse().unwrap_or_else(|_| {
594        tracing::warn!(value, "Failed to parse GitHub API timestamp, using epoch");
595        chrono::DateTime::UNIX_EPOCH
596    })
597}
598
599/// Parse issue number from GitHub URL.
600///
601/// Extracts the numeric issue number from URLs like:
602/// - `https://github.com/owner/repo/issues/123`
603/// - `https://github.enterprise.com/org/project/issues/456`
604fn parse_issue_number_from_url(url: &str) -> Option<u64> {
605    url.lines().find_map(|line| {
606        let line = line.trim();
607        if line.contains("/issues/") {
608            line.rsplit("/issues/")
609                .next()
610                .and_then(|s| s.split('/').next())
611                .and_then(|s| s.parse().ok())
612        } else {
613            None
614        }
615    })
616}
617
618/// 从 `gh issue edit --add-label` 的 stderr 中提取缺失的标签名。
619///
620/// `gh` 对缺失标签的错误格式为:
621/// ```text
622/// failed to update https://github.com/owner/repo/issues/18: 'type:enhancement' not found
623/// ```
624/// 或多个标签缺失时:
625/// ```text
626/// failed to update ...: 'bug' not found, 'priority:high' not found
627/// ```
628///
629/// 本函数扫描所有 `'<label>' not found` 模式并返回标签名列表。
630/// 若 stderr 不含该模式(例如鉴权错误),返回空列表,调用方据此判断
631/// 是否为"标签缺失"错误并决定是否重试。
632fn extract_missing_labels_from_error(stderr: &[u8]) -> Vec<String> {
633    let text = String::from_utf8_lossy(stderr);
634    let mut labels = Vec::new();
635    let mut search_from: usize = 0;
636
637    while let Some(rel_open) = text[search_from..].find('\'') {
638        let open_pos = search_from + rel_open + 1; // position after opening quote
639        let Some(rel_close) = text[open_pos..].find('\'') else {
640            break; // no matching close quote
641        };
642        let close_pos = open_pos + rel_close;
643        let after_close = &text[close_pos + 1..];
644
645        if after_close.starts_with(" not found") {
646            let label = text[open_pos..close_pos].to_string();
647            if !label.is_empty() {
648                labels.push(label);
649            }
650        }
651        search_from = close_pos + 1;
652    }
653
654    labels
655}
656
657#[cfg(test)]
658mod tests {
659    use gitflow_core::types::UserSummary;
660
661    use super::*;
662    use crate::runner::{MockCommandRunner, SequencedMockCommandRunner};
663
664    #[test]
665    fn test_should_construct_github_issue_provider() {
666        let provider = GitHubIssueProvider::new("octocat/hello-world");
667        assert_eq!(provider.repo, "octocat/hello-world");
668    }
669
670    #[test]
671    fn test_should_construct_github_issue_provider_from_string() {
672        let repo = String::from("octocat/hello-world");
673        let provider = GitHubIssueProvider::new(repo);
674        assert_eq!(provider.repo, "octocat/hello-world");
675    }
676
677    #[test]
678    fn test_should_deserialize_issue_data_from_gh_output() {
679        // 模拟 `gh issue view --json ...` 的实际输出
680        let gh_json = br#"{
681            "number": 42,
682            "title": "Fix login bug",
683            "body": "Reproduced on v1.2.3",
684            "state": "open",
685            "labels": [
686                {"name": "bug", "color": "d73a4a", "description": "Something isn't working"}
687            ],
688            "author": {"login": "octocat", "id": "1"},
689            "assignees": [{"login": "alice", "id": "7"}],
690            "createdAt": "2026-01-15T09:30:00Z",
691            "updatedAt": "2026-01-16T11:00:00Z",
692            "url": "https://github.com/octocat/hello-world/issues/42"
693        }"#;
694
695        let issue: IssueData = serde_json::from_slice(gh_json).expect("valid IssueData JSON");
696        assert_eq!(issue.number, 42);
697        assert_eq!(issue.title, "Fix login bug");
698        assert_eq!(issue.state, State::Open);
699        assert_eq!(issue.labels.len(), 1);
700        assert_eq!(issue.author.login, "octocat");
701        assert_eq!(issue.assignees.len(), 1);
702        assert_eq!(
703            issue.url,
704            "https://github.com/octocat/hello-world/issues/42"
705        );
706    }
707
708    #[test]
709    fn test_should_deserialize_empty_issue_list_from_gh_output() {
710        let gh_json = b"[]";
711        let issues: Vec<IssueData> = serde_json::from_slice(gh_json).expect("valid IssueData list");
712        assert!(issues.is_empty());
713    }
714
715    #[test]
716    fn test_should_debug_format_provider() {
717        let provider = GitHubIssueProvider::new("octocat/hello-world");
718        let debug = format!("{provider:?}");
719        assert!(debug.contains("GitHubIssueProvider"));
720        assert!(debug.contains("octocat/hello-world"));
721    }
722
723    // --- close/reopen: deserialized IssueData tests ---
724
725    #[test]
726    fn test_should_deserialize_closed_issue_from_gh_close_output() {
727        // 模拟 `gh issue close --json ...` 的返回数据
728        let gh_json = br#"{
729            "number": 10,
730            "title": "Fixed typo",
731            "body": null,
732            "state": "closed",
733            "labels": [],
734            "author": {"login": "dev", "id": "5"},
735            "assignees": [],
736            "createdAt": "2026-06-01T08:00:00Z",
737            "updatedAt": "2026-06-02T12:00:00Z",
738            "url": "https://github.com/octocat/hello-world/issues/10"
739        }"#;
740
741        let issue: IssueData = serde_json::from_slice(gh_json).expect("valid closed IssueData");
742        assert_eq!(issue.number, 10);
743        assert_eq!(issue.state, State::Closed);
744        assert_eq!(issue.title, "Fixed typo");
745    }
746
747    #[test]
748    fn test_should_deserialize_reopened_issue_from_gh_reopen_output() {
749        let gh_json = br#"{
750            "number": 10,
751            "title": "Fixed typo",
752            "body": null,
753            "state": "open",
754            "labels": [],
755            "author": {"login": "dev", "id": "5"},
756            "assignees": [],
757            "createdAt": "2026-06-01T08:00:00Z",
758            "updatedAt": "2026-06-03T09:00:00Z",
759            "url": "https://github.com/octocat/hello-world/issues/10"
760        }"#;
761
762        let issue: IssueData = serde_json::from_slice(gh_json).expect("valid reopened IssueData");
763        assert_eq!(issue.number, 10);
764        assert_eq!(issue.state, State::Open);
765    }
766
767    // --- comment: CommentData deserialization tests ---
768
769    #[test]
770    fn test_should_deserialize_comment_data_from_gh_comment_output() {
771        // 模拟 `gh issue comment --json id,body,author,createdAt` 的输出
772        let gh_json = br#"{
773            "id": 1001,
774            "body": "Thanks for reporting, looking into it.",
775            "author": {"login": "maintainer", "id": "42"},
776            "createdAt": "2026-06-15T14:00:00Z"
777        }"#;
778
779        let comment: CommentData = serde_json::from_slice(gh_json).expect("valid CommentData");
780        assert_eq!(comment.id, 1001);
781        assert_eq!(comment.body, "Thanks for reporting, looking into it.");
782        assert_eq!(comment.author.login, "maintainer");
783        assert_eq!(comment.author.id, "42");
784    }
785
786    #[test]
787    fn test_should_roundtrip_comment_data_via_serde() {
788        let comment = CommentData {
789            id: 77,
790            body: "reviewed".into(),
791            author: UserSummary {
792                login: "alice".into(),
793                id: "3".to_string(),
794            },
795            created_at: "2026-05-01T00:00:00Z".parse().expect("valid date"),
796        };
797        let json = serde_json::to_string(&comment).expect("serialize");
798        let round_tripped: CommentData = serde_json::from_str(&json).expect("deserialize");
799        assert_eq!(round_tripped.id, comment.id);
800        assert_eq!(round_tripped.body, comment.body);
801        assert_eq!(round_tripped.author.login, comment.author.login);
802    }
803
804    // --- GitHubCommentApiResponse conversion tests ---
805
806    #[test]
807    fn test_should_convert_github_api_response_to_comment_data() {
808        let api_response = GitHubCommentApiResponse {
809            id: 12345,
810            body: "Test comment body".to_string(),
811            user: GitHubUser {
812                login: "testuser".to_string(),
813                id: 42,
814            },
815            created_at: "2026-07-08T10:30:00Z".to_string(),
816        };
817
818        let comment_data: CommentData = api_response.into();
819
820        assert_eq!(comment_data.id, 12345);
821        assert_eq!(comment_data.body, "Test comment body");
822        assert_eq!(comment_data.author.login, "testuser");
823        assert_eq!(comment_data.author.id, "42");
824    }
825
826    #[test]
827    fn test_should_handle_invalid_date_in_api_response() {
828        let api_response = GitHubCommentApiResponse {
829            id: 1,
830            body: "test".to_string(),
831            user: GitHubUser {
832                login: "user".to_string(),
833                id: 1,
834            },
835            created_at: "invalid-date".to_string(),
836        };
837
838        let comment_data: CommentData = api_response.into();
839        // Should fall back to UNIX_EPOCH
840        assert_eq!(comment_data.created_at, chrono::DateTime::UNIX_EPOCH);
841    }
842
843    // --- GitHubIssueApiResponse conversion tests ---
844
845    fn sample_rest_issue_response() -> GitHubIssueApiResponse {
846        serde_json::from_str(REST_CLOSED_ISSUE_JSON).expect("fixture must deserialize")
847    }
848
849    #[test]
850    fn test_should_convert_rest_issue_response_to_issue_data() {
851        let issue: IssueData = sample_rest_issue_response().into();
852
853        assert_eq!(issue.number, 107);
854        assert_eq!(issue.title, "upstream CLI 新版本: glab 1.111.0");
855        assert_eq!(issue.body, None);
856        assert_eq!(issue.state, State::Closed);
857        assert_eq!(issue.author.login, "github-actions[bot]");
858        assert_eq!(issue.author.id, "41898282");
859        assert_eq!(issue.labels.len(), 1);
860        assert_eq!(issue.labels[0].name, "upstream-drift");
861        assert_eq!(
862            issue.labels[0].color.as_deref(),
863            Some("ededed"),
864            "REST label colors must keep the API-provided hex value"
865        );
866        assert_eq!(issue.labels[0].description, None);
867        assert!(issue.assignees.is_empty());
868        assert_eq!(issue.url, "https://github.com/o/r/issues/107");
869    }
870
871    #[test]
872    fn test_should_fall_back_to_epoch_for_invalid_rest_issue_dates() {
873        let mut api_response = sample_rest_issue_response();
874        api_response.created_at = "invalid-date".to_string();
875        api_response.updated_at = "also-invalid".to_string();
876
877        let issue: IssueData = api_response.into();
878
879        assert_eq!(issue.created_at, chrono::DateTime::UNIX_EPOCH);
880        assert_eq!(issue.updated_at, chrono::DateTime::UNIX_EPOCH);
881    }
882
883    // --- add_labels / remove_label: unit tests for provider ---
884
885    #[test]
886    fn test_should_create_provider_with_different_repos() {
887        let r1 = GitHubIssueProvider::new("org/repo-a");
888        let r2 = GitHubIssueProvider::new("org/repo-b");
889        assert_eq!(r1.repo, "org/repo-a");
890        assert_eq!(r2.repo, "org/repo-b");
891    }
892
893    #[test]
894    fn test_should_clone_github_issue_provider() {
895        let original = GitHubIssueProvider::new("owner/repo");
896        let cloned = original.clone();
897        assert_eq!(original.repo, cloned.repo);
898    }
899
900    #[test]
901    fn test_should_parse_issue_number_from_github_url() {
902        assert_eq!(
903            parse_issue_number_from_url("https://github.com/owner/repo/issues/123"),
904            Some(123)
905        );
906    }
907
908    #[test]
909    fn test_should_parse_issue_number_from_enterprise_url() {
910        assert_eq!(
911            parse_issue_number_from_url("https://github.enterprise.com/org/project/issues/456"),
912            Some(456)
913        );
914    }
915
916    #[test]
917    fn test_should_parse_issue_number_from_multiline_output() {
918        let output = "Creating issue...\nhttps://github.com/owner/repo/issues/789\nDone.";
919        assert_eq!(parse_issue_number_from_url(output), Some(789));
920    }
921
922    #[test]
923    fn test_should_return_none_for_invalid_url() {
924        assert_eq!(parse_issue_number_from_url("not a url"), None);
925    }
926
927    #[test]
928    fn test_should_return_none_for_url_without_number() {
929        assert_eq!(
930            parse_issue_number_from_url("https://github.com/owner/repo/issues/"),
931            None
932        );
933    }
934
935    // --- Failure-path tests using an injected MockCommandRunner ---
936
937    #[tokio::test]
938    async fn test_should_return_platform_error_when_gh_fails_for_view() {
939        let runner = MockCommandRunner::failure(r#"{"message": "Issue not found"}"#, 256);
940        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
941
942        let result = provider.view(999).await;
943
944        assert!(result.is_err());
945        assert!(matches!(
946            result.unwrap_err(),
947            gitflow_core::CoreError::Cli(_)
948        ));
949    }
950
951    #[tokio::test]
952    async fn test_should_return_serialization_error_on_invalid_json_for_view() {
953        let runner = MockCommandRunner::success("not valid json");
954        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
955
956        let result = provider.view(1).await;
957
958        assert!(result.is_err());
959        assert!(matches!(
960            result.unwrap_err(),
961            gitflow_core::CoreError::Serialization(_)
962        ));
963    }
964
965    #[tokio::test]
966    async fn test_should_return_platform_error_when_gh_fails_for_list() {
967        let runner = MockCommandRunner::failure(r#"{"message": "Forbidden"}"#, 256);
968        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
969
970        let result = provider.list(ListIssueArgs::default()).await;
971
972        assert!(result.is_err());
973        assert!(matches!(
974            result.unwrap_err(),
975            gitflow_core::CoreError::Cli(_)
976        ));
977    }
978
979    #[tokio::test]
980    async fn test_should_return_serialization_error_on_invalid_json_for_list() {
981        let runner = MockCommandRunner::success("invalid");
982        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
983
984        let result = provider.list(ListIssueArgs::default()).await;
985
986        assert!(result.is_err());
987        assert!(matches!(
988            result.unwrap_err(),
989            gitflow_core::CoreError::Serialization(_)
990        ));
991    }
992
993    fn sample_create_args() -> CreateIssueArgs {
994        CreateIssueArgs {
995            title: "Bug report".to_string(),
996            body: Some("Steps to reproduce".to_string()),
997            labels: vec!["bug".to_string()],
998            assignees: vec!["octocat".to_string()],
999        }
1000    }
1001
1002    #[tokio::test]
1003    async fn test_should_return_platform_error_when_gh_fails_for_create() {
1004        let runner = MockCommandRunner::failure(r#"{"message": "Validation failed"}"#, 256);
1005        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1006
1007        let result = provider.create(sample_create_args()).await;
1008
1009        assert!(result.is_err());
1010        assert!(matches!(
1011            result.unwrap_err(),
1012            gitflow_core::CoreError::Cli(_)
1013        ));
1014    }
1015
1016    #[tokio::test]
1017    async fn test_should_return_serialization_error_on_invalid_json_for_create() {
1018        // `create` succeeds and parses the issue number from this URL, then delegates
1019        // to `view`, which receives the same non-JSON stdout and fails to deserialize.
1020        let runner = MockCommandRunner::success("https://github.com/owner/repo/issues/7");
1021        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1022
1023        let result = provider.create(sample_create_args()).await;
1024
1025        assert!(result.is_err());
1026        assert!(matches!(
1027            result.unwrap_err(),
1028            gitflow_core::CoreError::Serialization(_)
1029        ));
1030    }
1031
1032    #[tokio::test]
1033    async fn test_should_return_platform_error_when_gh_fails_for_close() {
1034        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1035        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1036
1037        let result = provider.close(42).await;
1038
1039        assert!(result.is_err());
1040        assert!(matches!(
1041            result.unwrap_err(),
1042            gitflow_core::CoreError::Cli(_)
1043        ));
1044    }
1045
1046    #[tokio::test]
1047    async fn test_should_return_serialization_error_on_invalid_json_for_close() {
1048        // The single `gh api PATCH` call succeeds but its stdout is not JSON.
1049        let runner = MockCommandRunner::success("invalid");
1050        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1051
1052        let result = provider.close(42).await;
1053
1054        assert!(result.is_err());
1055        assert!(matches!(
1056            result.unwrap_err(),
1057            gitflow_core::CoreError::Serialization(_)
1058        ));
1059    }
1060
1061    /// 模拟 `gh api repos/{owner}/{repo}/issues/{number} -X PATCH -f state=closed`
1062    /// 返回的 GitHub REST issue 对象(bot user、null body、含 null description 的 label)。
1063    const REST_CLOSED_ISSUE_JSON: &str = r#"{
1064        "id": 5123456789,
1065        "node_id": "I_kwDOXYZ",
1066        "number": 107,
1067        "title": "upstream CLI 新版本: glab 1.111.0",
1068        "body": null,
1069        "state": "closed",
1070        "labels": [
1071            {
1072                "id": 7301464236,
1073                "node_id": "LA_kwDOXYZ",
1074                "url": "https://api.github.com/repos/o/r/labels/upstream-drift",
1075                "name": "upstream-drift",
1076                "color": "ededed",
1077                "description": null,
1078                "default": false
1079            }
1080        ],
1081        "user": {"login": "github-actions[bot]", "id": 41898282, "type": "Bot"},
1082        "assignees": [],
1083        "created_at": "2026-07-31T02:00:00Z",
1084        "updated_at": "2026-08-03T09:31:29Z",
1085        "closed_at": "2026-08-03T09:31:29Z",
1086        "html_url": "https://github.com/o/r/issues/107"
1087    }"#;
1088
1089    const REST_OPEN_ISSUE_JSON: &str = r#"{
1090        "id": 5123456790,
1091        "node_id": "I_kwDOXYZ2",
1092        "number": 108,
1093        "title": "upstream CLI 新版本: gitcode 0.8.0",
1094        "body": "patrol report",
1095        "state": "open",
1096        "labels": [],
1097        "user": {"login": "github-actions[bot]", "id": 41898282, "type": "Bot"},
1098        "assignees": [{"login": "octocat", "id": 583231}],
1099        "created_at": "2026-07-31T02:00:00Z",
1100        "updated_at": "2026-08-03T06:20:18Z",
1101        "closed_at": null,
1102        "html_url": "https://github.com/o/r/issues/108"
1103    }"#;
1104
1105    // --- close/reopen: single-call PATCH redesign (issue #117) ---
1106    //
1107    // The old flow ran `gh issue close` and then re-fetched via `gh issue view`;
1108    // a parse failure on the re-fetch misreported an already-successful close as
1109    // a failure. The new flow performs ONE `gh api PATCH` call whose response is
1110    // the authoritative REST issue object — mutation and data in one round trip.
1111
1112    #[tokio::test]
1113    async fn test_should_close_issue_via_single_api_patch_call() {
1114        // Exactly one response: if `close` makes a second call (the old
1115        // `gh issue view` re-fetch), the sequenced runner errors out.
1116        let runner = SequencedMockCommandRunner::from_results(&[(true, REST_CLOSED_ISSUE_JSON)]);
1117        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1118
1119        let issue = provider
1120            .close(107)
1121            .await
1122            .expect("close must succeed with a single PATCH call");
1123
1124        assert_eq!(issue.number, 107);
1125        assert_eq!(issue.state, State::Closed);
1126        assert_eq!(issue.title, "upstream CLI 新版本: glab 1.111.0");
1127        assert_eq!(issue.body, None);
1128        assert_eq!(issue.author.login, "github-actions[bot]");
1129        assert_eq!(issue.author.id, "41898282");
1130        assert_eq!(issue.labels.len(), 1);
1131        assert_eq!(issue.labels[0].name, "upstream-drift");
1132        assert_eq!(issue.labels[0].description, None);
1133        assert_eq!(issue.url, "https://github.com/o/r/issues/107");
1134        assert_eq!(issue.updated_at.to_rfc3339(), "2026-08-03T09:31:29+00:00");
1135    }
1136
1137    #[tokio::test]
1138    async fn test_should_reopen_issue_via_single_api_patch_call() {
1139        let runner = SequencedMockCommandRunner::from_results(&[(true, REST_OPEN_ISSUE_JSON)]);
1140        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1141
1142        let issue = provider
1143            .reopen(108)
1144            .await
1145            .expect("reopen must succeed with a single PATCH call");
1146
1147        assert_eq!(issue.number, 108);
1148        assert_eq!(issue.state, State::Open);
1149        assert_eq!(issue.body.as_deref(), Some("patrol report"));
1150        assert_eq!(issue.assignees.len(), 1);
1151        assert_eq!(issue.assignees[0].login, "octocat");
1152        assert_eq!(issue.assignees[0].id, "583231");
1153        assert_eq!(issue.url, "https://github.com/o/r/issues/108");
1154    }
1155
1156    #[tokio::test]
1157    async fn test_should_return_platform_error_when_gh_fails_for_reopen() {
1158        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1159        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1160
1161        let result = provider.reopen(42).await;
1162
1163        assert!(result.is_err());
1164        assert!(matches!(
1165            result.unwrap_err(),
1166            gitflow_core::CoreError::Cli(_)
1167        ));
1168    }
1169
1170    #[tokio::test]
1171    async fn test_should_return_serialization_error_on_invalid_json_for_reopen() {
1172        // The single `gh api PATCH` call succeeds but its stdout is not JSON.
1173        let runner = MockCommandRunner::success("invalid");
1174        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1175
1176        let result = provider.reopen(42).await;
1177
1178        assert!(result.is_err());
1179        assert!(matches!(
1180            result.unwrap_err(),
1181            gitflow_core::CoreError::Serialization(_)
1182        ));
1183    }
1184
1185    #[tokio::test]
1186    async fn test_should_return_platform_error_when_gh_fails_for_comment() {
1187        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1188        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1189
1190        let result = provider.comment(42, "a comment").await;
1191
1192        assert!(result.is_err());
1193        assert!(matches!(
1194            result.unwrap_err(),
1195            gitflow_core::CoreError::Cli(_)
1196        ));
1197    }
1198
1199    #[tokio::test]
1200    async fn test_should_return_serialization_error_on_invalid_json_for_comment() {
1201        // The `gh issue comment` call succeeds, then the `gh api` call returns the same
1202        // non-JSON stdout that fails to deserialize into the comment response array.
1203        let runner = MockCommandRunner::success("invalid");
1204        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1205
1206        let result = provider.comment(42, "a comment").await;
1207
1208        assert!(result.is_err());
1209        assert!(matches!(
1210            result.unwrap_err(),
1211            gitflow_core::CoreError::Serialization(_)
1212        ));
1213    }
1214
1215    #[tokio::test]
1216    async fn test_should_return_newly_created_comment_not_stale() {
1217        use crate::runner::MockCommandRunner;
1218
1219        // Mock `gh api POST` response — the comment just created
1220        let post_response_json = r#"{
1221            "id": 9999999999,
1222            "body": "This is the NEW comment",
1223            "user": {"login": "testuser", "id": 42},
1224            "created_at": "2026-08-04T12:00:00Z"
1225        }"#;
1226
1227        let runner = MockCommandRunner::success(post_response_json);
1228        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1229
1230        let result = provider
1231            .comment(42, "This is the NEW comment")
1232            .await
1233            .unwrap();
1234
1235        // The returned id must be the NEW comment's id, not a stale one
1236        assert_eq!(result.id, 9_999_999_999);
1237        assert_eq!(result.body, "This is the NEW comment");
1238        assert_eq!(result.author.login, "testuser");
1239    }
1240
1241    #[tokio::test]
1242    async fn test_should_return_error_when_gh_api_post_fails() {
1243        use crate::runner::MockCommandRunner;
1244
1245        let runner = MockCommandRunner::failure(
1246            r#"{"message": "Issue not found", "documentation_url": "https://docs.github.com"}"#,
1247            1,
1248        );
1249        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1250
1251        let result = provider.comment(999, "test").await;
1252
1253        assert!(result.is_err());
1254        let err = result.unwrap_err();
1255        // `parse_gh_error` returns `PlatformCliError`, which converts to
1256        // `CoreError::Cli` (matching the existing comment error-path test).
1257        assert!(
1258            matches!(err, CoreError::Cli(_)),
1259            "expected Cli error, got: {err:?}"
1260        );
1261    }
1262
1263    #[tokio::test]
1264    async fn test_should_return_platform_error_when_gh_fails_for_add_labels() {
1265        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1266        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1267
1268        let result = provider.add_labels(42, &["bug".to_string()]).await;
1269
1270        assert!(result.is_err());
1271        assert!(matches!(
1272            result.unwrap_err(),
1273            gitflow_core::CoreError::Cli(_)
1274        ));
1275    }
1276
1277    #[tokio::test]
1278    async fn test_should_return_platform_error_when_gh_fails_for_remove_label() {
1279        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1280        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1281
1282        let result = provider.remove_label(42, "bug").await;
1283
1284        assert!(result.is_err());
1285        assert!(matches!(
1286            result.unwrap_err(),
1287            gitflow_core::CoreError::Cli(_)
1288        ));
1289    }
1290
1291    // --- extract_missing_labels_from_error: pure-function tests ---
1292
1293    #[test]
1294    fn test_should_extract_single_missing_label_from_gh_stderr() {
1295        let stderr = b"failed to update https://github.com/owner/repo/issues/18: 'type:enhancement' not found\nfailed to update 1 issue";
1296        let missing = extract_missing_labels_from_error(stderr);
1297        assert_eq!(missing, vec!["type:enhancement".to_string()]);
1298    }
1299
1300    #[test]
1301    fn test_should_extract_multiple_missing_labels_from_gh_stderr() {
1302        let stderr = b"failed to update https://github.com/owner/repo/issues/5: 'bug' not found, 'priority:high' not found\nfailed to update 1 issue";
1303        let missing = extract_missing_labels_from_error(stderr);
1304        assert_eq!(
1305            missing,
1306            vec!["bug".to_string(), "priority:high".to_string()]
1307        );
1308    }
1309
1310    #[test]
1311    fn test_should_return_empty_when_no_label_not_found_in_stderr() {
1312        let stderr = b"gh: Not logged in. Please run `gh auth login`";
1313        let missing = extract_missing_labels_from_error(stderr);
1314        assert!(missing.is_empty());
1315    }
1316
1317    #[test]
1318    fn test_should_return_empty_for_empty_stderr() {
1319        let missing = extract_missing_labels_from_error(b"");
1320        assert!(missing.is_empty());
1321    }
1322
1323    #[test]
1324    fn test_should_handle_label_with_special_characters() {
1325        let stderr = b"failed to update https://github.com/o/r/issues/1: 'type: enhancement / bug' not found";
1326        let missing = extract_missing_labels_from_error(stderr);
1327        assert_eq!(missing, vec!["type: enhancement / bug".to_string()]);
1328    }
1329
1330    // --- add_labels: auto-create missing labels (RED phase) ---
1331
1332    #[tokio::test]
1333    async fn test_should_auto_create_label_and_retry_on_not_found() {
1334        // Sequence:
1335        // 1. `gh issue edit 18 --add-label type:enhancement` → fails (label not found)
1336        // 2. `gh label create type:enhancement --color ededed --repo owner/repo` → succeeds
1337        // 3. `gh issue edit 18 --add-label type:enhancement` → succeeds (retry)
1338        let runner = SequencedMockCommandRunner::from_results(&[
1339            (
1340                false,
1341                "failed to update https://github.com/owner/repo/issues/18: 'type:enhancement' not \
1342                 found\nfailed to update 1 issue",
1343            ),
1344            (true, "Created label type:enhancement"),
1345            (true, ""),
1346        ]);
1347        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1348
1349        let result = provider
1350            .add_labels(18, &["type:enhancement".to_string()])
1351            .await;
1352
1353        assert!(result.is_ok(), "expected Ok, got {result:?}");
1354    }
1355
1356    #[tokio::test]
1357    async fn test_should_auto_create_multiple_labels_and_retry() {
1358        // Sequence:
1359        // 1. `gh issue edit 5 --add-label bug --add-label priority:high` → fails (both missing)
1360        // 2. `gh label create bug` → succeeds
1361        // 3. `gh label create priority:high` → succeeds
1362        // 4. `gh issue edit 5 --add-label bug --add-label priority:high` → succeeds (retry)
1363        let runner = SequencedMockCommandRunner::from_results(&[
1364            (
1365                false,
1366                "failed to update https://github.com/o/r/issues/5: 'bug' not found, \
1367                 'priority:high' not found\nfailed to update 1 issue",
1368            ),
1369            (true, "Created label bug"),
1370            (true, "Created label priority:high"),
1371            (true, ""),
1372        ]);
1373        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1374
1375        let result = provider
1376            .add_labels(5, &["bug".to_string(), "priority:high".to_string()])
1377            .await;
1378
1379        assert!(result.is_ok(), "expected Ok, got {result:?}");
1380    }
1381
1382    #[tokio::test]
1383    async fn test_should_propagate_error_when_label_creation_fails() {
1384        // Sequence:
1385        // 1. `gh issue edit 1 --add-label ghost` → fails (label not found)
1386        // 2. `gh label create ghost` → also fails (permission denied)
1387        let runner = SequencedMockCommandRunner::from_results(&[
1388            (
1389                false,
1390                "failed to update https://github.com/o/r/issues/1: 'ghost' not found",
1391            ),
1392            (false, "gh: 403 Forbidden"),
1393        ]);
1394        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1395
1396        let result = provider.add_labels(1, &["ghost".to_string()]).await;
1397
1398        assert!(result.is_err());
1399        let err = result.unwrap_err();
1400        assert!(
1401            matches!(err, gitflow_core::CoreError::Cli(_)),
1402            "expected CoreError::Cli, got: {err:?}"
1403        );
1404        if let gitflow_core::CoreError::Cli(boxed) = err {
1405            assert!(
1406                boxed.raw_stderr.contains("403") || boxed.raw_stderr.contains("Forbidden"),
1407                "unexpected raw_stderr: {}",
1408                boxed.raw_stderr
1409            );
1410        }
1411    }
1412
1413    #[tokio::test]
1414    async fn test_should_not_retry_on_non_label_not_found_error() {
1415        // An auth error should propagate directly without any label create calls.
1416        // Only one response in the sequence — if the runner tries a second call,
1417        // SequencedMockCommandRunner will return an error ("no more responses").
1418        let runner = SequencedMockCommandRunner::from_results(&[(
1419            false,
1420            "gh: Not logged in. Please run `gh auth login`",
1421        )]);
1422        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1423
1424        let result = provider.add_labels(1, &["bug".to_string()]).await;
1425
1426        assert!(result.is_err());
1427    }
1428
1429    #[tokio::test]
1430    async fn test_should_propagate_retry_error_when_second_add_also_fails() {
1431        // Sequence:
1432        // 1. `gh issue edit 1 --add-label bug` → fails (label not found)
1433        // 2. `gh label create bug` → succeeds
1434        // 3. `gh issue edit 1 --add-label bug` → fails again (unrelated error)
1435        let runner = SequencedMockCommandRunner::from_results(&[
1436            (
1437                false,
1438                "failed to update https://github.com/o/r/issues/1: 'bug' not found",
1439            ),
1440            (true, "Created label bug"),
1441            (false, "gh: 500 Internal Server Error"),
1442        ]);
1443        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1444
1445        let result = provider.add_labels(1, &["bug".to_string()]).await;
1446
1447        assert!(result.is_err());
1448        let err = result.unwrap_err();
1449        assert!(
1450            matches!(err, gitflow_core::CoreError::Cli(_)),
1451            "expected CoreError::Cli, got: {err:?}"
1452        );
1453        if let gitflow_core::CoreError::Cli(boxed) = err {
1454            assert!(
1455                boxed.raw_stderr.contains("500") || boxed.raw_stderr.contains("Internal"),
1456                "unexpected raw_stderr: {}",
1457                boxed.raw_stderr
1458            );
1459        }
1460    }
1461
1462    // --- create: auto-create missing labels (RED phase) ---
1463
1464    fn create_args_with_labels(labels: Vec<String>) -> CreateIssueArgs {
1465        CreateIssueArgs {
1466            title: "New feature".to_string(),
1467            body: Some("Description".to_string()),
1468            labels,
1469            assignees: vec![],
1470        }
1471    }
1472
1473    #[tokio::test]
1474    async fn test_should_auto_create_label_and_retry_on_create_issue() {
1475        // Sequence:
1476        // 1. `gh issue create` → fails (label not found)
1477        // 2. `gh label create type:enhancement` → succeeds
1478        // 3. `gh issue create` (retry) → succeeds, returns URL
1479        // 4. `gh issue view <number>` → returns issue JSON
1480        let runner = SequencedMockCommandRunner::from_results(&[
1481            (false, "could not add label: 'type:enhancement' not found"),
1482            (true, "Created label type:enhancement"),
1483            (true, "https://github.com/owner/repo/issues/42"),
1484            (
1485                true,
1486                r#"{"number":42,"title":"New feature","body":"Description","state":"open","labels":[{"name":"type:enhancement","color":"ededed"}],"author":{"login":"octocat","id":"1"},"assignees":[],"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","url":"https://github.com/owner/repo/issues/42"}"#,
1487            ),
1488        ]);
1489        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1490
1491        let result = provider
1492            .create(create_args_with_labels(vec![
1493                "type:enhancement".to_string(),
1494            ]))
1495            .await;
1496
1497        assert!(result.is_ok(), "expected Ok, got {result:?}");
1498        let issue = result.expect("already checked");
1499        assert_eq!(issue.number, 42);
1500    }
1501
1502    #[tokio::test]
1503    async fn test_should_propagate_error_when_label_create_fails_on_create_issue() {
1504        // Sequence:
1505        // 1. `gh issue create` → fails (label not found)
1506        // 2. `gh label create ghost` → also fails (permission denied)
1507        let runner = SequencedMockCommandRunner::from_results(&[
1508            (false, "could not add label: 'ghost' not found"),
1509            (false, "gh: 403 Forbidden"),
1510        ]);
1511        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1512
1513        let result = provider
1514            .create(create_args_with_labels(vec!["ghost".to_string()]))
1515            .await;
1516
1517        assert!(result.is_err());
1518    }
1519
1520    #[tokio::test]
1521    async fn test_should_not_retry_create_on_non_label_error() {
1522        // Only one response — any extra call will error with "no more responses".
1523        let runner = SequencedMockCommandRunner::from_results(&[(false, "gh: Not logged in")]);
1524        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1525
1526        let result = provider
1527            .create(create_args_with_labels(vec!["bug".to_string()]))
1528            .await;
1529
1530        assert!(result.is_err());
1531    }
1532}
1533
1534#[cfg(test)]
1535mod contract_tests {
1536    use super::*;
1537    use crate::runner::MockCommandRunner;
1538
1539    /// 契约测试:验证 gh v2.94 对 bot author 省略 `id` 字段时仍可反序列化。
1540    ///
1541    /// gh 2.94 对 bot-authored issue 返回 `{"is_bot": true, "login": "app/github-actions"}`
1542    /// 而非人类的 `{"id": "...", "login": "..."}`。`UserSummary::id` 使用 `#[serde(default)]`
1543    /// 兼容该差异,此处用真实 fixture 守护契约。
1544    #[tokio::test]
1545    async fn test_contract_issue_list_github_v294_bot_author() {
1546        let fixture = include_str!("../tests/fixtures/issue_list_github_v294_bot_author.json");
1547        let runner = MockCommandRunner::success(fixture);
1548        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1549
1550        let issues = provider
1551            .list(ListIssueArgs::default())
1552            .await
1553            .expect("gh v2.94 bot-author fixture must parse");
1554
1555        assert_eq!(issues.len(), 2);
1556        assert_eq!(issues[0].number, 107);
1557        assert_eq!(issues[0].author.login, "app/github-actions");
1558        assert_eq!(issues[1].number, 42);
1559        assert_eq!(issues[1].author.login, "test-user");
1560    }
1561
1562    /// 契约测试:验证 gh issue list JSON 输出与 `IssueData` 反序列化一致。
1563    ///
1564    /// 夹具来源:gh v2.x `--json` 输出格式。
1565    #[tokio::test]
1566    async fn test_contract_issue_list_github_v2() {
1567        let fixture = include_str!("../tests/fixtures/issue_list_github_v2.json");
1568        let runner = MockCommandRunner::success(fixture);
1569        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1570
1571        let issues = provider
1572            .list(ListIssueArgs::default())
1573            .await
1574            .expect("contract fixture must parse");
1575
1576        assert_eq!(issues.len(), 1);
1577        let issue = &issues[0];
1578        assert_eq!(issue.number, 42);
1579        assert!(!issue.title.is_empty());
1580        assert_eq!(issue.state, gitflow_core::types::State::Open);
1581        assert_eq!(issue.author.login, "test-user");
1582    }
1583
1584    /// 契约测试:验证 gh v2.97 混合 author 形状(bot 无 `id` + human 新增 `name`)可反序列化。
1585    ///
1586    /// gh 2.97.0 对 bot author 返回 `{"is_bot": true, "login": "app/github-actions"}`
1587    /// (无 `id`),对 human author 返回
1588    /// `{"id": "...", "is_bot": false, "login": "...", "name": "..."}`(新增 `name` 字段)。
1589    /// `UserSummary::id` 的 `#[serde(default)]` 兜底 bot 缺 `id`,`name` 作为未知字段被忽略。
1590    /// 夹具为 2026-08-03 从 gh 2.97.0 真实捕获(issue #108/#117)并截断 body。
1591    /// 守护 issue #117:修复前该形状触发 `missing field 'id'` 反序列化错误。
1592    #[tokio::test]
1593    async fn test_contract_issue_list_github_v297_mixed_authors() {
1594        let fixture = include_str!("../tests/fixtures/issue_list_github_v297_mixed_authors.json");
1595        let runner = MockCommandRunner::success(fixture);
1596        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1597
1598        let issues = provider
1599            .list(ListIssueArgs::default())
1600            .await
1601            .expect("gh v2.97 mixed-author fixture must parse");
1602
1603        assert_eq!(issues.len(), 2);
1604        // bot-authored issue: id omitted by gh → defaults to empty string
1605        assert_eq!(issues[0].number, 108);
1606        assert_eq!(issues[0].author.login, "app/github-actions");
1607        assert_eq!(issues[0].author.id, "");
1608        // human-authored issue: id present, extra `name` field ignored
1609        assert_eq!(issues[1].number, 117);
1610        assert_eq!(issues[1].author.login, "byx-darwin");
1611        assert!(!issues[1].author.id.is_empty());
1612    }
1613
1614    /// 契约测试:验证 gh v2.97 `issue view` 对 bot-authored issue 的输出可反序列化。
1615    ///
1616    /// 夹具为 2026-08-03 从 gh 2.97.0 真实捕获(issue #108,author 为
1617    /// `app/github-actions`)并截断 body。守护 issue #117 的 `close`/`view`
1618    /// 路径:bot-authored issue 的 author 对象缺少 `id` 字段。
1619    #[tokio::test]
1620    async fn test_contract_issue_view_github_v297_bot_author() {
1621        let fixture = include_str!("../tests/fixtures/issue_view_github_v297_bot_author.json");
1622        let runner = MockCommandRunner::success(fixture);
1623        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1624
1625        let issue = provider
1626            .view(108)
1627            .await
1628            .expect("gh v2.97 bot-author view fixture must parse");
1629
1630        assert_eq!(issue.number, 108);
1631        assert_eq!(issue.author.login, "app/github-actions");
1632        assert_eq!(issue.author.id, "");
1633        assert_eq!(issue.state, gitflow_core::types::State::Open);
1634    }
1635}