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