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, DEFAULT_LIST_LIMIT, FetchStrategy, Paged, Result, fetch_capped,
10    issue::{CreateIssueArgs, EditIssueArgs, IssueData, IssueProvider, ListIssueArgs},
11    types::{CommentData, Label, State, UserSummary},
12};
13use tracing::debug;
14
15use crate::{
16    GITHUB_API_MAX_PER_PAGE,
17    datetime::parse_api_datetime,
18    error::parse_gh_error,
19    runner::{CommandRunner, RealCommandRunner},
20};
21
22/// `gh issue` 请求的 JSON 字段列表。
23const ISSUE_FIELDS: &str =
24    "number,title,body,state,labels,author,assignees,createdAt,updatedAt,milestone,url";
25
26/// GitHub Issue 提供者,通过 `gh` CLI 操作。
27///
28/// 该结构体通过调用 `gh` CLI 实现 [`IssueProvider`] trait 的所有方法,
29/// 使上层命令能够以统一的方式操作 GitHub Issue。
30///
31/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
32/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
33///
34/// # Examples
35///
36/// ```no_run
37/// use gitflow_github::GitHubIssueProvider;
38///
39/// let provider = GitHubIssueProvider::new("octocat/hello-world");
40/// ```
41#[derive(Debug, Clone)]
42pub struct GitHubIssueProvider<R: CommandRunner = RealCommandRunner> {
43    /// GitHub `owner/repo`,如 `"byx-darwin/gitflow-cli"`。
44    repo: String,
45    /// 用于执行 `gh` CLI 命令的 runner。
46    runner: R,
47}
48
49impl GitHubIssueProvider<RealCommandRunner> {
50    /// 创建新的 GitHub Issue 提供者,使用真实的进程执行器。
51    ///
52    /// `repo` 格式为 `owner/repo`。
53    #[must_use]
54    pub fn new(repo: impl Into<String>) -> Self {
55        Self {
56            repo: repo.into(),
57            runner: RealCommandRunner,
58        }
59    }
60
61    /// Create a new provider from a shared [`Session`].
62    ///
63    /// This enables state reuse across multiple operations in workflow chains.
64    #[must_use]
65    pub fn with_session(session: &gitflow_core::Session) -> Self {
66        Self {
67            repo: session.repo.clone(),
68            runner: RealCommandRunner,
69        }
70    }
71}
72
73impl<R: CommandRunner> GitHubIssueProvider<R> {
74    /// 使用自定义 [`CommandRunner`] 创建提供者。
75    ///
76    /// 主要用于测试,可注入模拟 runner 以控制 `gh` CLI 的输出。
77    /// `repo` 格式为 `owner/repo`。
78    #[must_use]
79    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
80        Self {
81            repo: repo.into(),
82            runner,
83        }
84    }
85
86    /// 创建缺失的标签(如已存在则忽略"已存在"错误)。
87    ///
88    /// 调用 `gh label create <name> --color ededed --repo <repo> --force`。
89    /// `--force` 确保在竞态条件(标签被并发创建)下仍保持幂等。
90    ///
91    /// # Errors
92    ///
93    /// 当 `gh label create` 调用失败时返回错误。
94    async fn ensure_label_exists(&self, name: &str) -> Result<()> {
95        debug!(repo = %self.repo, name, "auto-creating missing label via `gh label create`");
96
97        let output = self
98            .runner
99            .run(
100                "gh",
101                &[
102                    "label", "create", name, "--color", "ededed", "--repo", &self.repo, "--force",
103                ],
104            )
105            .await
106            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label create: {e}")))?;
107
108        if !output.status.success() {
109            let mut gh_err = parse_gh_error(&output.stderr);
110            gh_err.user_message = format!("自动创建标签 '{name}' 失败:{}", gh_err.user_message);
111            return Err(gh_err.into());
112        }
113
114        Ok(())
115    }
116}
117
118impl<R: CommandRunner + Clone + 'static> GitHubIssueProvider<R> {
119    /// [`IssueProvider::list`] 的实际实现。
120    ///
121    /// 抽成普通(非 `async_trait` 装箱)的关联函数,避开泛型 `AsyncFn` 闭包
122    /// 在 `async_trait` 装箱 Future 内部触发的 HRTB `Send` 检查缺陷。
123    async fn list_impl(&self, args: ListIssueArgs) -> Result<Paged<IssueData>> {
124        let cap = args.limit.unwrap_or(DEFAULT_LIST_LIMIT);
125        let state = args.state.map(|state| match state {
126            State::Open => "open",
127            State::Closed => "closed",
128            State::All => "all",
129        });
130        let repo = &self.repo;
131        let runner = &self.runner;
132        let search = &args.search;
133        let labels = &args.labels;
134        let milestone = &args.milestone;
135
136        debug!(repo = %self.repo, cap, "spawning `gh issue list`");
137
138        fetch_capped(FetchStrategy::SingleShot, cap, |_page, limit| async move {
139            let limit_str = limit.to_string();
140            let mut cmd_args: Vec<&str> =
141                vec!["issue", "list", "--repo", repo, "--json", ISSUE_FIELDS];
142
143            if let Some(state) = state {
144                cmd_args.push("--state");
145                cmd_args.push(state);
146            }
147
148            if let Some(search) = search {
149                cmd_args.push("--search");
150                cmd_args.push(search);
151            }
152
153            for label in labels {
154                cmd_args.push("--label");
155                cmd_args.push(label);
156            }
157
158            let resolved_milestone_title;
159            if let Some(identifier) = milestone {
160                let milestone_provider =
161                    crate::GitHubMilestoneProvider::with_runner(repo.as_str(), runner.clone());
162                let resolved = gitflow_core::label::resolve_milestone_identifier(
163                    &milestone_provider,
164                    identifier,
165                )
166                .await?;
167                resolved_milestone_title = resolved.title;
168                cmd_args.push("--milestone");
169                cmd_args.push(&resolved_milestone_title);
170            }
171
172            cmd_args.push("--limit");
173            cmd_args.push(&limit_str);
174
175            let output = runner
176                .run("gh", &cmd_args)
177                .await
178                .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
179
180            if !output.status.success() {
181                return Err(parse_gh_error(&output.stderr).into());
182            }
183
184            let issues: Vec<IssueData> =
185                serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
186            Ok(issues)
187        })
188        .await
189    }
190}
191
192#[async_trait]
193impl<R: CommandRunner + Clone + 'static> IssueProvider for GitHubIssueProvider<R> {
194    async fn create(&self, args: CreateIssueArgs) -> Result<IssueData> {
195        let labels_joined = args.labels.join(",");
196        let assignees_joined = args.assignees.join(",");
197
198        let mut cmd_args: Vec<&str> = vec![
199            "issue",
200            "create",
201            "--repo",
202            &self.repo,
203            "--title",
204            &args.title,
205        ];
206
207        if let Some(body) = &args.body {
208            cmd_args.push("--body");
209            cmd_args.push(body);
210        }
211
212        if !args.labels.is_empty() {
213            cmd_args.push("--label");
214            cmd_args.push(&labels_joined);
215        }
216
217        if !args.assignees.is_empty() {
218            cmd_args.push("--assignee");
219            cmd_args.push(&assignees_joined);
220        }
221
222        let resolved_milestone_title;
223        if let Some(identifier) = &args.milestone {
224            let milestone_provider = crate::GitHubMilestoneProvider::with_runner(
225                self.repo.as_str(),
226                self.runner.clone(),
227            );
228            let resolved =
229                gitflow_core::label::resolve_milestone_identifier(&milestone_provider, identifier)
230                    .await?;
231            resolved_milestone_title = resolved.title;
232            cmd_args.push("--milestone");
233            cmd_args.push(&resolved_milestone_title);
234        }
235
236        debug!(repo = %self.repo, title = %args.title, "spawning `gh issue create`");
237
238        let output = self
239            .runner
240            .run("gh", &cmd_args)
241            .await
242            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
243
244        if !output.status.success() {
245            // `gh issue create` fails when a requested label doesn't exist.
246            // Auto-create missing labels and retry once.
247            let missing = extract_missing_labels_from_error(&output.stderr);
248            if !missing.is_empty() {
249                debug!(
250                    repo = %self.repo,
251                    missing_count = missing.len(),
252                    "auto-creating missing label(s) before retrying issue create"
253                );
254                for label in &missing {
255                    self.ensure_label_exists(label).await?;
256                }
257
258                let retry_output = self.runner.run("gh", &cmd_args).await.map_err(|e| {
259                    CoreError::Platform(format!("Failed to spawn gh on retry: {e}"))
260                })?;
261
262                if !retry_output.status.success() {
263                    return Err(parse_gh_error(&retry_output.stderr).into());
264                }
265
266                let stdout = String::from_utf8_lossy(&retry_output.stdout);
267                let issue_number = parse_issue_number_from_url(&stdout).ok_or_else(|| {
268                    CoreError::Platform(format!("Failed to parse issue URL from output: {stdout}"))
269                })?;
270                return self.view(issue_number).await;
271            }
272
273            return Err(parse_gh_error(&output.stderr).into());
274        }
275
276        // Parse the issue URL from stdout (format: https://github.com/owner/repo/issues/123)
277        let stdout = String::from_utf8_lossy(&output.stdout);
278        let issue_number = parse_issue_number_from_url(&stdout).ok_or_else(|| {
279            CoreError::Platform(format!("Failed to parse issue URL from output: {stdout}"))
280        })?;
281
282        // Fetch full issue details via view
283        self.view(issue_number).await
284    }
285
286    /// 编辑 Issue 的标题和/或正文。
287    ///
288    /// 调用 `gh issue edit <number> --repo <repo> [--title T] [--body B]`,
289    /// 成功后通过 [`view`](Self::view) 重新拉取最新数据并返回。
290    ///
291    /// # Errors
292    ///
293    /// 当 Issue 不存在或 `gh` CLI 调用失败时返回错误。
294    async fn edit(&self, number: u64, args: EditIssueArgs) -> Result<IssueData> {
295        debug!(repo = %self.repo, number, "spawning `gh issue edit`");
296
297        let number_str = number.to_string();
298        let mut cmd_args: Vec<&str> = vec!["issue", "edit", &number_str, "--repo", &self.repo];
299
300        if let Some(title) = &args.title {
301            cmd_args.push("--title");
302            cmd_args.push(title);
303        }
304        if let Some(body) = &args.body {
305            cmd_args.push("--body");
306            cmd_args.push(body);
307        }
308
309        let resolved_milestone_title;
310        match &args.milestone {
311            None => {}
312            Some(None) => {
313                cmd_args.push("--remove-milestone");
314            }
315            Some(Some(identifier)) => {
316                let milestone_provider = crate::GitHubMilestoneProvider::with_runner(
317                    self.repo.as_str(),
318                    self.runner.clone(),
319                );
320                let resolved = gitflow_core::label::resolve_milestone_identifier(
321                    &milestone_provider,
322                    identifier,
323                )
324                .await?;
325                resolved_milestone_title = resolved.title;
326                cmd_args.push("--milestone");
327                cmd_args.push(&resolved_milestone_title);
328            }
329        }
330
331        let output = self
332            .runner
333            .run("gh", &cmd_args)
334            .await
335            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
336
337        if !output.status.success() {
338            return Err(parse_gh_error(&output.stderr).into());
339        }
340
341        self.view(number).await
342    }
343
344    async fn list(&self, args: ListIssueArgs) -> Result<Paged<IssueData>> {
345        self.list_impl(args).await
346    }
347
348    async fn view(&self, number: u64) -> Result<IssueData> {
349        debug!(repo = %self.repo, number, "spawning `gh issue view`");
350
351        let number_str = number.to_string();
352        let output = self
353            .runner
354            .run(
355                "gh",
356                &[
357                    "issue",
358                    "view",
359                    &number_str,
360                    "--repo",
361                    &self.repo,
362                    "--json",
363                    ISSUE_FIELDS,
364                ],
365            )
366            .await
367            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
368
369        if !output.status.success() {
370            return Err(parse_gh_error(&output.stderr).into());
371        }
372
373        let issue: IssueData =
374            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
375
376        Ok(issue)
377    }
378
379    /// 关闭指定编号的 Issue。
380    ///
381    /// 通过单次 `gh api repos/{owner}/{repo}/issues/{number} -X PATCH -f state=closed`
382    /// 调用更新状态,并直接解析 REST 响应获得更新后的完整 Issue 数据。
383    /// 该调用幂等:对已关闭的 Issue 再次关闭将成功返回其当前数据。
384    ///
385    /// # 设计说明(issue #117)
386    ///
387    /// 早期实现先调用 `gh issue close`,再用 `gh issue view --json` 重新获取详情。
388    /// 该双调用设计有两个缺陷:
389    ///
390    /// 1. `--json` 输出来自 `gh` 的 GraphQL 导出层,字段形状随 `gh` 版本漂移 (如 gh 2.94+ 的 bot
391    ///    author 省略 `id`),导致反序列化失败;
392    /// 2. 关闭操作已经成功时,二次获取的解析失败仍被误报为"关闭失败"。
393    ///
394    /// 改为单次 REST 调用后,变更与数据在同一响应中返回,两个缺陷同时消除。
395    /// REST 响应形状是 GitHub API 的稳定契约,bot 用户同样携带数字 `id`。
396    ///
397    /// # Errors
398    ///
399    /// 当 Issue 不存在、`gh` CLI 调用失败或响应解析失败时返回错误。
400    async fn close(&self, number: u64) -> Result<IssueData> {
401        debug!(repo = %self.repo, number, "spawning `gh api issues PATCH state=closed`");
402
403        let api_path = format!("repos/{repo}/issues/{number}", repo = self.repo);
404        let output = self
405            .runner
406            .run(
407                "gh",
408                &["api", &api_path, "-X", "PATCH", "-f", "state=closed"],
409            )
410            .await
411            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api issue close: {e}")))?;
412
413        if !output.status.success() {
414            return Err(parse_gh_error(&output.stderr).into());
415        }
416
417        let api_response: GitHubIssueApiResponse =
418            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
419
420        Ok(api_response.into())
421    }
422
423    /// 重新打开指定编号的 Issue。
424    ///
425    /// 通过单次 `gh api repos/{owner}/{repo}/issues/{number} -X PATCH -f state=open`
426    /// 调用更新状态,并直接解析 REST 响应获得更新后的完整 Issue 数据。
427    /// 该调用幂等:对未关闭的 Issue 再次打开将成功返回其当前数据。
428    ///
429    /// # 设计说明(issue #117)
430    ///
431    /// 与 [`close`](Self::close) 相同,改为单次 REST 调用以消除双调用的
432    /// 反序列化漂移与误报失败问题。
433    ///
434    /// # Errors
435    ///
436    /// 当 Issue 不存在、`gh` CLI 调用失败或响应解析失败时返回错误。
437    async fn reopen(&self, number: u64) -> Result<IssueData> {
438        debug!(repo = %self.repo, number, "spawning `gh api issues PATCH state=open`");
439
440        let api_path = format!("repos/{repo}/issues/{number}", repo = self.repo);
441        let output = self
442            .runner
443            .run("gh", &["api", &api_path, "-X", "PATCH", "-f", "state=open"])
444            .await
445            .map_err(|e| {
446                CoreError::Platform(format!("Failed to spawn gh api issue reopen: {e}"))
447            })?;
448
449        if !output.status.success() {
450            return Err(parse_gh_error(&output.stderr).into());
451        }
452
453        let api_response: GitHubIssueApiResponse =
454            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
455
456        Ok(api_response.into())
457    }
458
459    /// 在指定 Issue 上添加评论。
460    ///
461    /// 调用 `gh api repos/{repo}/issues/{number}/comments -X POST` 创建评论,
462    /// 直接从 POST 响应中解析新创建的评论数据。
463    ///
464    /// # Errors
465    ///
466    /// 当 Issue 不存在、`body` 为空或 `gh` CLI 调用失败时返回错误。
467    async fn comment(&self, number: u64, body: &str) -> Result<CommentData> {
468        debug!(repo = %self.repo, number, "spawning `gh api` POST to create issue comment");
469
470        let api_path = format!(
471            "repos/{repo}/issues/{number}/comments",
472            repo = self.repo,
473            number = number
474        );
475
476        let body_field = format!("body={body}");
477        let output = self
478            .runner
479            .run("gh", &["api", &api_path, "-X", "POST", "-f", &body_field])
480            .await
481            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api: {e}")))?;
482
483        if !output.status.success() {
484            return Err(parse_gh_error(&output.stderr).into());
485        }
486
487        let comment: GitHubCommentApiResponse =
488            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
489
490        Ok(comment.into())
491    }
492
493    /// 列出指定 Issue 的评论。
494    ///
495    /// 调用 `gh api repos/{repo}/issues/{number}/comments` 获取评论列表,
496    /// 通过 `per_page`/`page` 查询参数逐页取到 `limit`(已实测 `gh api`
497    /// 直接接受这两个查询参数,无需 `--paginate`)。
498    ///
499    /// # Errors
500    ///
501    /// 当 Issue 不存在或 `gh` CLI 调用失败时返回错误。
502    async fn list_comments(&self, number: u64, limit: Option<u32>) -> Result<Paged<CommentData>> {
503        let cap = limit.unwrap_or(DEFAULT_LIST_LIMIT);
504        let repo = &self.repo;
505        let runner = &self.runner;
506
507        debug!(repo = %self.repo, number, cap, "spawning `gh api` GET issue comments");
508
509        fetch_capped(
510            FetchStrategy::Paged {
511                per_page: cap.saturating_add(1).min(GITHUB_API_MAX_PER_PAGE),
512            },
513            cap,
514            |page, per_page| async move {
515                let api_path = format!(
516                    "repos/{repo}/issues/{number}/comments?per_page={per_page}&page={page}"
517                );
518
519                let output = runner
520                    .run("gh", &["api", &api_path])
521                    .await
522                    .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api: {e}")))?;
523
524                if !output.status.success() {
525                    return Err(parse_gh_error(&output.stderr).into());
526                }
527
528                let comments: Vec<GitHubCommentApiResponse> =
529                    serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
530                Ok(comments.into_iter().map(CommentData::from).collect())
531            },
532        )
533        .await
534    }
535
536    /// 为指定 Issue 添加一个或多个标签。
537    ///
538    /// 调用 `gh issue edit <number> --repo <repo> --add-label <label>` 逐个添加标签。
539    /// 如果 `labels` 为空,不进行任何调用并返回成功。
540    ///
541    /// # 自动创建缺失标签
542    ///
543    /// 当 `gh issue edit --add-label` 因标签不存在而失败时,本方法会自动调用
544    /// `gh label create` 创建缺失的标签(使用默认颜色 `ededed`),然后重试原操作。
545    /// 这避免了手动同步仓库标签列表的繁琐流程。
546    ///
547    /// # Errors
548    ///
549    /// 当 Issue 不存在、标签创建失败或 `gh` CLI 调用失败时返回错误。
550    async fn add_labels(&self, number: u64, labels: &[String]) -> Result<()> {
551        debug!(
552            repo = %self.repo,
553            number,
554            label_count = labels.len(),
555            "spawning `gh issue edit --add-label`"
556        );
557
558        let number_str = number.to_string();
559        let mut cmd_args: Vec<&str> = vec!["issue", "edit", &number_str, "--repo", &self.repo];
560
561        for label in labels {
562            cmd_args.push("--add-label");
563            cmd_args.push(label);
564        }
565
566        let output = self
567            .runner
568            .run("gh", &cmd_args)
569            .await
570            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
571
572        if output.status.success() {
573            return Ok(());
574        }
575
576        // gh issue edit --add-label fails when a label doesn't exist in the repo.
577        // Auto-create the missing label(s) and retry once.
578        let missing = extract_missing_labels_from_error(&output.stderr);
579        if missing.is_empty() {
580            return Err(parse_gh_error(&output.stderr).into());
581        }
582
583        debug!(
584            repo = %self.repo,
585            missing_count = missing.len(),
586            "auto-creating missing label(s) before retry"
587        );
588
589        for label in &missing {
590            self.ensure_label_exists(label).await?;
591        }
592
593        // Retry the original add-label command.
594        let retry_output = self
595            .runner
596            .run("gh", &cmd_args)
597            .await
598            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh on retry: {e}")))?;
599
600        if !retry_output.status.success() {
601            return Err(parse_gh_error(&retry_output.stderr).into());
602        }
603
604        Ok(())
605    }
606
607    /// 从指定 Issue 移除一个标签。
608    ///
609    /// 调用 `gh issue edit <number> --repo <repo> --remove-label <label>` 移除标签。
610    ///
611    /// # Errors
612    ///
613    /// 当 Issue 不存在、标签未附加到该 Issue 或 `gh` CLI 调用失败时返回错误。
614    async fn remove_label(&self, number: u64, label: &str) -> Result<()> {
615        debug!(repo = %self.repo, number, label, "spawning `gh issue edit --remove-label`");
616
617        let number_str = number.to_string();
618        let output = self
619            .runner
620            .run(
621                "gh",
622                &[
623                    "issue",
624                    "edit",
625                    &number_str,
626                    "--repo",
627                    &self.repo,
628                    "--remove-label",
629                    label,
630                ],
631            )
632            .await
633            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
634
635        if !output.status.success() {
636            return Err(parse_gh_error(&output.stderr).into());
637        }
638
639        Ok(())
640    }
641}
642
643/// GitHub API 评论响应结构。
644///
645/// 用于解析 `gh api repos/{owner}/{repo}/issues/{number}/comments` 的返回数据。
646#[derive(Debug, Clone, serde::Deserialize)]
647pub struct GitHubCommentApiResponse {
648    pub id: u64,
649    pub body: String,
650    pub user: GitHubUser,
651    pub created_at: String,
652}
653
654/// GitHub API 标签响应结构(REST 形状)。
655///
656/// 用于解析 `gh api` 返回的 Issue 对象中的标签。REST 标签的 `description`
657/// 在无描述时为 `null`,`color` 为不带 `#` 前缀的十六进制字符串。
658#[derive(Debug, Clone, serde::Deserialize)]
659pub struct GitHubLabelApiResponse {
660    pub name: String,
661    #[serde(default)]
662    pub color: Option<String>,
663    #[serde(default)]
664    pub description: Option<String>,
665}
666
667/// GitHub API Issue 响应结构(REST 形状)。
668///
669/// 用于解析 `gh api repos/{owner}/{repo}/issues/{number} -X PATCH` 的返回数据。
670///
671/// 与 `gh issue view --json` 的 GraphQL 导出格式不同,REST 形状是 GitHub API
672/// 的稳定契约,不随 `gh` CLI 版本漂移:bot 用户同样携带数字 `id`,
673/// 也不存在 GraphQL 导出层新增/省略字段的问题(issue #117)。
674#[derive(Debug, Clone, serde::Deserialize)]
675pub struct GitHubIssueApiResponse {
676    pub number: u64,
677    pub title: String,
678    #[serde(default)]
679    pub body: Option<String>,
680    pub state: State,
681    #[serde(default)]
682    pub labels: Vec<GitHubLabelApiResponse>,
683    pub user: GitHubUser,
684    #[serde(default)]
685    pub assignees: Vec<GitHubUser>,
686    pub created_at: String,
687    pub updated_at: String,
688    pub html_url: String,
689    #[serde(default)]
690    pub milestone: Option<gitflow_core::types::MilestoneRef>,
691}
692
693/// GitHub API 用户结构。
694#[derive(Debug, Clone, serde::Deserialize)]
695pub struct GitHubUser {
696    pub login: String,
697    pub id: u64,
698}
699
700impl From<GitHubCommentApiResponse> for CommentData {
701    fn from(api: GitHubCommentApiResponse) -> Self {
702        Self {
703            id: api.id,
704            body: api.body,
705            author: gitflow_core::types::UserSummary {
706                login: api.user.login,
707                id: api.user.id.to_string(),
708            },
709            // parse_api_datetime always returns a value (falling back to
710            // UNIX_EPOCH on parse failure); wrapped in Some purely to match
711            // CommentData.created_at's new Option type (#380). Whether that
712            // fallback value itself should change is Issue #401's decision.
713            created_at: Some(parse_api_datetime(&api.created_at)),
714        }
715    }
716}
717
718impl From<GitHubLabelApiResponse> for Label {
719    fn from(api: GitHubLabelApiResponse) -> Self {
720        Self {
721            name: api.name,
722            color: api.color,
723            description: api.description,
724        }
725    }
726}
727
728impl From<GitHubUser> for UserSummary {
729    fn from(user: GitHubUser) -> Self {
730        Self {
731            login: user.login,
732            id: user.id.to_string(),
733        }
734    }
735}
736
737impl From<GitHubIssueApiResponse> for IssueData {
738    fn from(api: GitHubIssueApiResponse) -> Self {
739        Self {
740            number: api.number,
741            title: api.title,
742            body: api.body,
743            state: api.state,
744            labels: api.labels.into_iter().map(Label::from).collect(),
745            author: api.user.into(),
746            assignees: api.assignees.into_iter().map(UserSummary::from).collect(),
747            // Same Some(...) wrap as CommentData above, same reasoning.
748            created_at: Some(parse_api_datetime(&api.created_at)),
749            updated_at: Some(parse_api_datetime(&api.updated_at)),
750            url: api.html_url,
751            milestone: api.milestone,
752        }
753    }
754}
755
756/// Parse issue number from GitHub URL.
757///
758/// Extracts the numeric issue number from URLs like:
759/// - `https://github.com/owner/repo/issues/123`
760/// - `https://github.enterprise.com/org/project/issues/456`
761fn parse_issue_number_from_url(url: &str) -> Option<u64> {
762    url.lines().find_map(|line| {
763        let line = line.trim();
764        if line.contains("/issues/") {
765            line.rsplit("/issues/")
766                .next()
767                .and_then(|s| s.split('/').next())
768                .and_then(|s| s.parse().ok())
769        } else {
770            None
771        }
772    })
773}
774
775/// 从 `gh issue edit --add-label` 的 stderr 中提取缺失的标签名。
776///
777/// `gh` 对缺失标签的错误格式为:
778/// ```text
779/// failed to update https://github.com/owner/repo/issues/18: 'type:enhancement' not found
780/// ```
781/// 或多个标签缺失时:
782/// ```text
783/// failed to update ...: 'bug' not found, 'priority:high' not found
784/// ```
785///
786/// 本函数扫描所有 `'<label>' not found` 模式并返回标签名列表。
787/// 若 stderr 不含该模式(例如鉴权错误),返回空列表,调用方据此判断
788/// 是否为"标签缺失"错误并决定是否重试。
789fn extract_missing_labels_from_error(stderr: &[u8]) -> Vec<String> {
790    let text = String::from_utf8_lossy(stderr);
791    let mut labels = Vec::new();
792    let mut search_from: usize = 0;
793
794    while let Some(rel_open) = text[search_from..].find('\'') {
795        let open_pos = search_from + rel_open + 1; // position after opening quote
796        let Some(rel_close) = text[open_pos..].find('\'') else {
797            break; // no matching close quote
798        };
799        let close_pos = open_pos + rel_close;
800        let after_close = &text[close_pos + 1..];
801
802        if after_close.starts_with(" not found") {
803            let label = text[open_pos..close_pos].to_string();
804            if !label.is_empty() {
805                labels.push(label);
806            }
807        }
808        search_from = close_pos + 1;
809    }
810
811    labels
812}
813
814#[cfg(test)]
815mod tests {
816    use gitflow_core::types::UserSummary;
817
818    use super::*;
819    use crate::runner::{MockCommandRunner, SequencedMockCommandRunner};
820
821    #[test]
822    fn test_should_construct_github_issue_provider() {
823        let provider = GitHubIssueProvider::new("octocat/hello-world");
824        assert_eq!(provider.repo, "octocat/hello-world");
825    }
826
827    #[test]
828    fn test_should_construct_github_issue_provider_from_string() {
829        let repo = String::from("octocat/hello-world");
830        let provider = GitHubIssueProvider::new(repo);
831        assert_eq!(provider.repo, "octocat/hello-world");
832    }
833
834    #[test]
835    fn test_should_deserialize_issue_data_from_gh_output() {
836        // 模拟 `gh issue view --json ...` 的实际输出
837        let gh_json = br#"{
838            "number": 42,
839            "title": "Fix login bug",
840            "body": "Reproduced on v1.2.3",
841            "state": "open",
842            "labels": [
843                {"name": "bug", "color": "d73a4a", "description": "Something isn't working"}
844            ],
845            "author": {"login": "octocat", "id": "1"},
846            "assignees": [{"login": "alice", "id": "7"}],
847            "createdAt": "2026-01-15T09:30:00Z",
848            "updatedAt": "2026-01-16T11:00:00Z",
849            "url": "https://github.com/octocat/hello-world/issues/42"
850        }"#;
851
852        let issue: IssueData = serde_json::from_slice(gh_json).expect("valid IssueData JSON");
853        assert_eq!(issue.number, 42);
854        assert_eq!(issue.title, "Fix login bug");
855        assert_eq!(issue.state, State::Open);
856        assert_eq!(issue.labels.len(), 1);
857        assert_eq!(issue.author.login, "octocat");
858        assert_eq!(issue.assignees.len(), 1);
859        assert_eq!(
860            issue.url,
861            "https://github.com/octocat/hello-world/issues/42"
862        );
863    }
864
865    #[test]
866    fn test_should_deserialize_issue_with_milestone() {
867        let gh_json = br#"{
868            "number": 42,
869            "title": "Test",
870            "body": null,
871            "state": "OPEN",
872            "labels": [],
873            "author": {"login": "octocat", "id": "1"},
874            "assignees": [],
875            "createdAt": "2026-01-01T00:00:00Z",
876            "updatedAt": "2026-01-01T00:00:00Z",
877            "milestone": {"number": 3, "title": "v2.0"},
878            "url": "https://github.com/octocat/hello-world/issues/42"
879        }"#;
880        let issue: IssueData = serde_json::from_slice(gh_json).expect("valid IssueData JSON");
881        assert_eq!(
882            issue.milestone,
883            Some(gitflow_core::types::MilestoneRef {
884                number: 3,
885                title: "v2.0".into()
886            })
887        );
888    }
889
890    #[test]
891    fn test_should_deserialize_issue_with_no_milestone() {
892        let gh_json = br#"{
893            "number": 42,
894            "title": "Test",
895            "body": null,
896            "state": "OPEN",
897            "labels": [],
898            "author": {"login": "octocat", "id": "1"},
899            "assignees": [],
900            "createdAt": "2026-01-01T00:00:00Z",
901            "updatedAt": "2026-01-01T00:00:00Z",
902            "url": "https://github.com/octocat/hello-world/issues/42"
903        }"#;
904        let issue: IssueData = serde_json::from_slice(gh_json).expect("valid IssueData JSON");
905        assert!(issue.milestone.is_none());
906    }
907
908    #[test]
909    fn test_should_deserialize_empty_issue_list_from_gh_output() {
910        let gh_json = b"[]";
911        let issues: Vec<IssueData> = serde_json::from_slice(gh_json).expect("valid IssueData list");
912        assert!(issues.is_empty());
913    }
914
915    #[test]
916    fn test_should_debug_format_provider() {
917        let provider = GitHubIssueProvider::new("octocat/hello-world");
918        let debug = format!("{provider:?}");
919        assert!(debug.contains("GitHubIssueProvider"));
920        assert!(debug.contains("octocat/hello-world"));
921    }
922
923    // --- close/reopen: deserialized IssueData tests ---
924
925    #[test]
926    fn test_should_deserialize_closed_issue_from_gh_close_output() {
927        // 模拟 `gh issue close --json ...` 的返回数据
928        let gh_json = br#"{
929            "number": 10,
930            "title": "Fixed typo",
931            "body": null,
932            "state": "closed",
933            "labels": [],
934            "author": {"login": "dev", "id": "5"},
935            "assignees": [],
936            "createdAt": "2026-06-01T08:00:00Z",
937            "updatedAt": "2026-06-02T12:00:00Z",
938            "url": "https://github.com/octocat/hello-world/issues/10"
939        }"#;
940
941        let issue: IssueData = serde_json::from_slice(gh_json).expect("valid closed IssueData");
942        assert_eq!(issue.number, 10);
943        assert_eq!(issue.state, State::Closed);
944        assert_eq!(issue.title, "Fixed typo");
945    }
946
947    #[test]
948    fn test_should_deserialize_reopened_issue_from_gh_reopen_output() {
949        let gh_json = br#"{
950            "number": 10,
951            "title": "Fixed typo",
952            "body": null,
953            "state": "open",
954            "labels": [],
955            "author": {"login": "dev", "id": "5"},
956            "assignees": [],
957            "createdAt": "2026-06-01T08:00:00Z",
958            "updatedAt": "2026-06-03T09:00:00Z",
959            "url": "https://github.com/octocat/hello-world/issues/10"
960        }"#;
961
962        let issue: IssueData = serde_json::from_slice(gh_json).expect("valid reopened IssueData");
963        assert_eq!(issue.number, 10);
964        assert_eq!(issue.state, State::Open);
965    }
966
967    // --- comment: CommentData deserialization tests ---
968
969    #[test]
970    fn test_should_deserialize_comment_data_from_gh_comment_output() {
971        // 模拟 `gh issue comment --json id,body,author,createdAt` 的输出
972        let gh_json = br#"{
973            "id": 1001,
974            "body": "Thanks for reporting, looking into it.",
975            "author": {"login": "maintainer", "id": "42"},
976            "createdAt": "2026-06-15T14:00:00Z"
977        }"#;
978
979        let comment: CommentData = serde_json::from_slice(gh_json).expect("valid CommentData");
980        assert_eq!(comment.id, 1001);
981        assert_eq!(comment.body, "Thanks for reporting, looking into it.");
982        assert_eq!(comment.author.login, "maintainer");
983        assert_eq!(comment.author.id, "42");
984    }
985
986    #[test]
987    fn test_should_roundtrip_comment_data_via_serde() {
988        let comment = CommentData {
989            id: 77,
990            body: "reviewed".into(),
991            author: UserSummary {
992                login: "alice".into(),
993                id: "3".to_string(),
994            },
995            created_at: Some("2026-05-01T00:00:00Z".parse().expect("valid date")),
996        };
997        let json = serde_json::to_string(&comment).expect("serialize");
998        let round_tripped: CommentData = serde_json::from_str(&json).expect("deserialize");
999        assert_eq!(round_tripped.id, comment.id);
1000        assert_eq!(round_tripped.body, comment.body);
1001        assert_eq!(round_tripped.author.login, comment.author.login);
1002    }
1003
1004    // --- GitHubCommentApiResponse conversion tests ---
1005
1006    #[test]
1007    fn test_should_convert_github_api_response_to_comment_data() {
1008        let api_response = GitHubCommentApiResponse {
1009            id: 12345,
1010            body: "Test comment body".to_string(),
1011            user: GitHubUser {
1012                login: "testuser".to_string(),
1013                id: 42,
1014            },
1015            created_at: "2026-07-08T10:30:00Z".to_string(),
1016        };
1017
1018        let comment_data: CommentData = api_response.into();
1019
1020        assert_eq!(comment_data.id, 12345);
1021        assert_eq!(comment_data.body, "Test comment body");
1022        assert_eq!(comment_data.author.login, "testuser");
1023        assert_eq!(comment_data.author.id, "42");
1024    }
1025
1026    #[test]
1027    fn test_should_handle_invalid_date_in_api_response() {
1028        let api_response = GitHubCommentApiResponse {
1029            id: 1,
1030            body: "test".to_string(),
1031            user: GitHubUser {
1032                login: "user".to_string(),
1033                id: 1,
1034            },
1035            created_at: "invalid-date".to_string(),
1036        };
1037
1038        let comment_data: CommentData = api_response.into();
1039        // Should fall back to UNIX_EPOCH
1040        assert_eq!(comment_data.created_at, Some(chrono::DateTime::UNIX_EPOCH));
1041    }
1042
1043    // --- GitHubIssueApiResponse conversion tests ---
1044
1045    fn sample_rest_issue_response() -> GitHubIssueApiResponse {
1046        serde_json::from_str(REST_CLOSED_ISSUE_JSON).expect("fixture must deserialize")
1047    }
1048
1049    #[test]
1050    fn test_should_convert_rest_issue_response_to_issue_data() {
1051        let issue: IssueData = sample_rest_issue_response().into();
1052
1053        assert_eq!(issue.number, 107);
1054        assert_eq!(issue.title, "upstream CLI 新版本: glab 1.111.0");
1055        assert_eq!(issue.body, None);
1056        assert_eq!(issue.state, State::Closed);
1057        assert_eq!(issue.author.login, "github-actions[bot]");
1058        assert_eq!(issue.author.id, "41898282");
1059        assert_eq!(issue.labels.len(), 1);
1060        assert_eq!(issue.labels[0].name, "upstream-drift");
1061        assert_eq!(
1062            issue.labels[0].color.as_deref(),
1063            Some("ededed"),
1064            "REST label colors must keep the API-provided hex value"
1065        );
1066        assert_eq!(issue.labels[0].description, None);
1067        assert!(issue.assignees.is_empty());
1068        assert_eq!(issue.url, "https://github.com/o/r/issues/107");
1069    }
1070
1071    #[test]
1072    fn test_should_deserialize_issue_with_present_timestamps_as_some() {
1073        // Sanity check that the Option type change doesn't break the normal
1074        // (timestamp present) path through GitHubIssueApiResponse, only the
1075        // already-covered UNIX_EPOCH fallback path.
1076        let issue: IssueData = sample_rest_issue_response().into();
1077        assert!(issue.created_at.is_some());
1078        assert!(issue.updated_at.is_some());
1079    }
1080
1081    #[test]
1082    fn test_should_fall_back_to_epoch_for_invalid_rest_issue_dates() {
1083        let mut api_response = sample_rest_issue_response();
1084        api_response.created_at = "invalid-date".to_string();
1085        api_response.updated_at = "also-invalid".to_string();
1086
1087        let issue: IssueData = api_response.into();
1088
1089        assert_eq!(issue.created_at, Some(chrono::DateTime::UNIX_EPOCH));
1090        assert_eq!(issue.updated_at, Some(chrono::DateTime::UNIX_EPOCH));
1091    }
1092
1093    // --- add_labels / remove_label: unit tests for provider ---
1094
1095    #[test]
1096    fn test_should_create_provider_with_different_repos() {
1097        let r1 = GitHubIssueProvider::new("org/repo-a");
1098        let r2 = GitHubIssueProvider::new("org/repo-b");
1099        assert_eq!(r1.repo, "org/repo-a");
1100        assert_eq!(r2.repo, "org/repo-b");
1101    }
1102
1103    #[test]
1104    fn test_should_clone_github_issue_provider() {
1105        let original = GitHubIssueProvider::new("owner/repo");
1106        let cloned = original.clone();
1107        assert_eq!(original.repo, cloned.repo);
1108    }
1109
1110    #[test]
1111    fn test_should_parse_issue_number_from_github_url() {
1112        assert_eq!(
1113            parse_issue_number_from_url("https://github.com/owner/repo/issues/123"),
1114            Some(123)
1115        );
1116    }
1117
1118    #[test]
1119    fn test_should_parse_issue_number_from_enterprise_url() {
1120        assert_eq!(
1121            parse_issue_number_from_url("https://github.enterprise.com/org/project/issues/456"),
1122            Some(456)
1123        );
1124    }
1125
1126    #[test]
1127    fn test_should_parse_issue_number_from_multiline_output() {
1128        let output = "Creating issue...\nhttps://github.com/owner/repo/issues/789\nDone.";
1129        assert_eq!(parse_issue_number_from_url(output), Some(789));
1130    }
1131
1132    #[test]
1133    fn test_should_return_none_for_invalid_url() {
1134        assert_eq!(parse_issue_number_from_url("not a url"), None);
1135    }
1136
1137    #[test]
1138    fn test_should_return_none_for_url_without_number() {
1139        assert_eq!(
1140            parse_issue_number_from_url("https://github.com/owner/repo/issues/"),
1141            None
1142        );
1143    }
1144
1145    // --- Failure-path tests using an injected MockCommandRunner ---
1146
1147    #[tokio::test]
1148    async fn test_should_return_platform_error_when_gh_fails_for_view() {
1149        let runner = MockCommandRunner::failure(r#"{"message": "Issue not found"}"#, 256);
1150        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1151
1152        let result = provider.view(999).await;
1153
1154        assert!(result.is_err());
1155        assert!(matches!(
1156            result.unwrap_err(),
1157            gitflow_core::CoreError::Cli(_)
1158        ));
1159    }
1160
1161    #[tokio::test]
1162    async fn test_should_return_serialization_error_on_invalid_json_for_view() {
1163        let runner = MockCommandRunner::success("not valid json");
1164        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1165
1166        let result = provider.view(1).await;
1167
1168        assert!(result.is_err());
1169        assert!(matches!(
1170            result.unwrap_err(),
1171            gitflow_core::CoreError::Serialization(_)
1172        ));
1173    }
1174
1175    #[tokio::test]
1176    async fn test_should_return_platform_error_when_gh_fails_for_list() {
1177        let runner = MockCommandRunner::failure(r#"{"message": "Forbidden"}"#, 256);
1178        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1179
1180        let result = provider.list(ListIssueArgs::default()).await;
1181
1182        assert!(result.is_err());
1183        assert!(matches!(
1184            result.unwrap_err(),
1185            gitflow_core::CoreError::Cli(_)
1186        ));
1187    }
1188
1189    #[tokio::test]
1190    async fn test_should_return_serialization_error_on_invalid_json_for_list() {
1191        let runner = MockCommandRunner::success("invalid");
1192        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1193
1194        let result = provider.list(ListIssueArgs::default()).await;
1195
1196        assert!(result.is_err());
1197        assert!(matches!(
1198            result.unwrap_err(),
1199            gitflow_core::CoreError::Serialization(_)
1200        ));
1201    }
1202
1203    fn sample_create_args() -> CreateIssueArgs {
1204        CreateIssueArgs {
1205            title: "Bug report".to_string(),
1206            body: Some("Steps to reproduce".to_string()),
1207            labels: vec!["bug".to_string()],
1208            assignees: vec!["octocat".to_string()],
1209            milestone: None,
1210        }
1211    }
1212
1213    #[tokio::test]
1214    async fn test_should_return_platform_error_when_gh_fails_for_create() {
1215        let runner = MockCommandRunner::failure(r#"{"message": "Validation failed"}"#, 256);
1216        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1217
1218        let result = provider.create(sample_create_args()).await;
1219
1220        assert!(result.is_err());
1221        assert!(matches!(
1222            result.unwrap_err(),
1223            gitflow_core::CoreError::Cli(_)
1224        ));
1225    }
1226
1227    #[tokio::test]
1228    async fn test_should_return_serialization_error_on_invalid_json_for_create() {
1229        // `create` succeeds and parses the issue number from this URL, then delegates
1230        // to `view`, which receives the same non-JSON stdout and fails to deserialize.
1231        let runner = MockCommandRunner::success("https://github.com/owner/repo/issues/7");
1232        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1233
1234        let result = provider.create(sample_create_args()).await;
1235
1236        assert!(result.is_err());
1237        assert!(matches!(
1238            result.unwrap_err(),
1239            gitflow_core::CoreError::Serialization(_)
1240        ));
1241    }
1242
1243    #[tokio::test]
1244    async fn test_should_return_platform_error_when_gh_fails_for_close() {
1245        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1246        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1247
1248        let result = provider.close(42).await;
1249
1250        assert!(result.is_err());
1251        assert!(matches!(
1252            result.unwrap_err(),
1253            gitflow_core::CoreError::Cli(_)
1254        ));
1255    }
1256
1257    #[tokio::test]
1258    async fn test_should_return_serialization_error_on_invalid_json_for_close() {
1259        // The single `gh api PATCH` call succeeds but its stdout is not JSON.
1260        let runner = MockCommandRunner::success("invalid");
1261        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1262
1263        let result = provider.close(42).await;
1264
1265        assert!(result.is_err());
1266        assert!(matches!(
1267            result.unwrap_err(),
1268            gitflow_core::CoreError::Serialization(_)
1269        ));
1270    }
1271
1272    /// 模拟 `gh api repos/{owner}/{repo}/issues/{number} -X PATCH -f state=closed`
1273    /// 返回的 GitHub REST issue 对象(bot user、null body、含 null description 的 label)。
1274    const REST_CLOSED_ISSUE_JSON: &str = r#"{
1275        "id": 5123456789,
1276        "node_id": "I_kwDOXYZ",
1277        "number": 107,
1278        "title": "upstream CLI 新版本: glab 1.111.0",
1279        "body": null,
1280        "state": "closed",
1281        "labels": [
1282            {
1283                "id": 7301464236,
1284                "node_id": "LA_kwDOXYZ",
1285                "url": "https://api.github.com/repos/o/r/labels/upstream-drift",
1286                "name": "upstream-drift",
1287                "color": "ededed",
1288                "description": null,
1289                "default": false
1290            }
1291        ],
1292        "user": {"login": "github-actions[bot]", "id": 41898282, "type": "Bot"},
1293        "assignees": [],
1294        "created_at": "2026-07-31T02:00:00Z",
1295        "updated_at": "2026-08-03T09:31:29Z",
1296        "closed_at": "2026-08-03T09:31:29Z",
1297        "milestone": {"number": 3, "title": "v2.0", "state": "open", "id": 17970779},
1298        "html_url": "https://github.com/o/r/issues/107"
1299    }"#;
1300
1301    const REST_OPEN_ISSUE_JSON: &str = r#"{
1302        "id": 5123456790,
1303        "node_id": "I_kwDOXYZ2",
1304        "number": 108,
1305        "title": "upstream CLI 新版本: gitcode 0.8.0",
1306        "body": "patrol report",
1307        "state": "open",
1308        "labels": [],
1309        "user": {"login": "github-actions[bot]", "id": 41898282, "type": "Bot"},
1310        "assignees": [{"login": "octocat", "id": 583231}],
1311        "created_at": "2026-07-31T02:00:00Z",
1312        "updated_at": "2026-08-03T06:20:18Z",
1313        "closed_at": null,
1314        "html_url": "https://github.com/o/r/issues/108"
1315    }"#;
1316
1317    // --- close/reopen: single-call PATCH redesign (issue #117) ---
1318    //
1319    // The old flow ran `gh issue close` and then re-fetched via `gh issue view`;
1320    // a parse failure on the re-fetch misreported an already-successful close as
1321    // a failure. The new flow performs ONE `gh api PATCH` call whose response is
1322    // the authoritative REST issue object — mutation and data in one round trip.
1323
1324    #[tokio::test]
1325    async fn test_should_close_issue_via_single_api_patch_call() {
1326        // Exactly one response: if `close` makes a second call (the old
1327        // `gh issue view` re-fetch), the sequenced runner errors out.
1328        let runner = SequencedMockCommandRunner::from_results(&[(true, REST_CLOSED_ISSUE_JSON)]);
1329        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1330
1331        let issue = provider
1332            .close(107)
1333            .await
1334            .expect("close must succeed with a single PATCH call");
1335
1336        assert_eq!(issue.number, 107);
1337        assert_eq!(issue.state, State::Closed);
1338        assert_eq!(issue.title, "upstream CLI 新版本: glab 1.111.0");
1339        assert_eq!(issue.body, None);
1340        assert_eq!(issue.author.login, "github-actions[bot]");
1341        assert_eq!(issue.author.id, "41898282");
1342        assert_eq!(issue.labels.len(), 1);
1343        assert_eq!(issue.labels[0].name, "upstream-drift");
1344        assert_eq!(issue.labels[0].description, None);
1345        assert_eq!(issue.url, "https://github.com/o/r/issues/107");
1346        assert_eq!(
1347            issue.updated_at.map(|dt| dt.to_rfc3339()),
1348            Some("2026-08-03T09:31:29+00:00".to_string())
1349        );
1350        assert_eq!(
1351            issue.milestone,
1352            Some(gitflow_core::types::MilestoneRef {
1353                number: 3,
1354                title: "v2.0".into(),
1355            })
1356        );
1357    }
1358
1359    #[tokio::test]
1360    async fn test_should_reopen_issue_via_single_api_patch_call() {
1361        let runner = SequencedMockCommandRunner::from_results(&[(true, REST_OPEN_ISSUE_JSON)]);
1362        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1363
1364        let issue = provider
1365            .reopen(108)
1366            .await
1367            .expect("reopen must succeed with a single PATCH call");
1368
1369        assert_eq!(issue.number, 108);
1370        assert_eq!(issue.state, State::Open);
1371        assert_eq!(issue.body.as_deref(), Some("patrol report"));
1372        assert_eq!(issue.assignees.len(), 1);
1373        assert_eq!(issue.assignees[0].login, "octocat");
1374        assert_eq!(issue.assignees[0].id, "583231");
1375        assert_eq!(issue.url, "https://github.com/o/r/issues/108");
1376        assert_eq!(issue.milestone, None);
1377    }
1378
1379    #[tokio::test]
1380    async fn test_should_return_platform_error_when_gh_fails_for_reopen() {
1381        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1382        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1383
1384        let result = provider.reopen(42).await;
1385
1386        assert!(result.is_err());
1387        assert!(matches!(
1388            result.unwrap_err(),
1389            gitflow_core::CoreError::Cli(_)
1390        ));
1391    }
1392
1393    #[tokio::test]
1394    async fn test_should_return_serialization_error_on_invalid_json_for_reopen() {
1395        // The single `gh api PATCH` call succeeds but its stdout is not JSON.
1396        let runner = MockCommandRunner::success("invalid");
1397        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1398
1399        let result = provider.reopen(42).await;
1400
1401        assert!(result.is_err());
1402        assert!(matches!(
1403            result.unwrap_err(),
1404            gitflow_core::CoreError::Serialization(_)
1405        ));
1406    }
1407
1408    #[tokio::test]
1409    async fn test_should_return_platform_error_when_gh_fails_for_comment() {
1410        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1411        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1412
1413        let result = provider.comment(42, "a comment").await;
1414
1415        assert!(result.is_err());
1416        assert!(matches!(
1417            result.unwrap_err(),
1418            gitflow_core::CoreError::Cli(_)
1419        ));
1420    }
1421
1422    #[tokio::test]
1423    async fn test_should_return_serialization_error_on_invalid_json_for_comment() {
1424        // The `gh issue comment` call succeeds, then the `gh api` call returns the same
1425        // non-JSON stdout that fails to deserialize into the comment response array.
1426        let runner = MockCommandRunner::success("invalid");
1427        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1428
1429        let result = provider.comment(42, "a comment").await;
1430
1431        assert!(result.is_err());
1432        assert!(matches!(
1433            result.unwrap_err(),
1434            gitflow_core::CoreError::Serialization(_)
1435        ));
1436    }
1437
1438    #[tokio::test]
1439    async fn test_should_return_newly_created_comment_not_stale() {
1440        use crate::runner::MockCommandRunner;
1441
1442        // Mock `gh api POST` response — the comment just created
1443        let post_response_json = r#"{
1444            "id": 9999999999,
1445            "body": "This is the NEW comment",
1446            "user": {"login": "testuser", "id": 42},
1447            "created_at": "2026-08-04T12:00:00Z"
1448        }"#;
1449
1450        let runner = MockCommandRunner::success(post_response_json);
1451        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1452
1453        let result = provider
1454            .comment(42, "This is the NEW comment")
1455            .await
1456            .unwrap();
1457
1458        // The returned id must be the NEW comment's id, not a stale one
1459        assert_eq!(result.id, 9_999_999_999);
1460        assert_eq!(result.body, "This is the NEW comment");
1461        assert_eq!(result.author.login, "testuser");
1462    }
1463
1464    #[tokio::test]
1465    async fn test_should_return_error_when_gh_api_post_fails() {
1466        use crate::runner::MockCommandRunner;
1467
1468        let runner = MockCommandRunner::failure(
1469            r#"{"message": "Issue not found", "documentation_url": "https://docs.github.com"}"#,
1470            1,
1471        );
1472        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1473
1474        let result = provider.comment(999, "test").await;
1475
1476        assert!(result.is_err());
1477        let err = result.unwrap_err();
1478        // `parse_gh_error` returns `PlatformCliError`, which converts to
1479        // `CoreError::Cli` (matching the existing comment error-path test).
1480        assert!(
1481            matches!(err, CoreError::Cli(_)),
1482            "expected Cli error, got: {err:?}"
1483        );
1484    }
1485
1486    #[tokio::test]
1487    async fn test_should_produce_complete_argv_for_list_comments_with_default_limit() {
1488        let runner = MockCommandRunner::success("[]");
1489        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
1490
1491        let paged = provider
1492            .list_comments(359, None)
1493            .await
1494            .expect("list_comments should succeed");
1495
1496        assert!(paged.items.is_empty());
1497        let calls = runner.recorded_calls();
1498        assert_eq!(calls[0].0, "gh");
1499        assert_eq!(
1500            calls[0].1,
1501            vec![
1502                "api",
1503                "repos/owner/repo/issues/359/comments?per_page=100&page=1"
1504            ]
1505        );
1506    }
1507
1508    #[tokio::test]
1509    async fn test_should_build_well_formed_query_string_for_list_comments() {
1510        let runner = MockCommandRunner::success("[]");
1511        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
1512
1513        provider
1514            .list_comments(359, None)
1515            .await
1516            .expect("list_comments should succeed");
1517
1518        let calls = runner.recorded_calls();
1519        let api_path = &calls[0].1[1];
1520        assert_eq!(
1521            api_path.matches('?').count(),
1522            1,
1523            "must have exactly one '?', got: {api_path}"
1524        );
1525        assert_eq!(
1526            api_path.matches('&').count(),
1527            1,
1528            "must have exactly one '&', got: {api_path}"
1529        );
1530        assert!(api_path.contains("per_page=100"), "got: {api_path}");
1531        assert!(api_path.contains("page=1"), "got: {api_path}");
1532    }
1533
1534    /// 证明分页确实会递增页码:第一页给满 100 条(`per_page` 值),
1535    /// 迫使循环请求第二页;第二页给 1 条(短页)以终止循环。
1536    #[tokio::test]
1537    async fn test_should_increment_page_across_calls_for_list_comments() {
1538        let full_page: Vec<String> = (0..100)
1539            .map(|i| {
1540                format!(
1541                    r#"{{"id":{i},"body":"c{i}","user":{{"login":"u","id":1}},"created_at":"2026-08-18T00:00:00Z"}}"#
1542                )
1543            })
1544            .collect();
1545        let full_page_json = format!("[{}]", full_page.join(","));
1546
1547        let short_page_json = r#"[{"id":9999,"body":"last","user":{"login":"u","id":1},"created_at":"2026-08-18T00:00:00Z"}]"#;
1548
1549        let runner = SequencedMockCommandRunner::from_results(&[
1550            (true, &full_page_json),
1551            (true, short_page_json),
1552        ]);
1553        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
1554
1555        let paged = provider
1556            .list_comments(359, Some(150))
1557            .await
1558            .expect("should list across two pages");
1559
1560        assert_eq!(paged.items.len(), 101);
1561
1562        let calls = runner.recorded_calls();
1563        assert_eq!(calls.len(), 2, "必须恰好翻两页");
1564        assert!(
1565            calls[0].1[1].contains("page=1"),
1566            "第一次调用必须请求 page=1,实际: {:?}",
1567            calls[0].1
1568        );
1569        assert!(
1570            calls[1].1[1].contains("page=2"),
1571            "第二次调用必须请求 page=2,实际: {:?}",
1572            calls[1].1
1573        );
1574    }
1575
1576    #[tokio::test]
1577    async fn test_should_return_platform_error_when_gh_fails_for_add_labels() {
1578        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1579        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1580
1581        let result = provider.add_labels(42, &["bug".to_string()]).await;
1582
1583        assert!(result.is_err());
1584        assert!(matches!(
1585            result.unwrap_err(),
1586            gitflow_core::CoreError::Cli(_)
1587        ));
1588    }
1589
1590    #[tokio::test]
1591    async fn test_should_edit_issue_title_and_view_result() {
1592        // Sequence: 1. `gh issue edit` → succeeds (empty stdout)
1593        //           2. `gh issue view --json ...` → returns updated issue JSON
1594        let runner = SequencedMockCommandRunner::from_results(&[
1595            (true, ""),
1596            (
1597                true,
1598                r#"{"number":42,"title":"New title","body":"orig","state":"open","labels":[],"author":{"login":"octocat","id":"1"},"assignees":[],"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-02T00:00:00Z","url":"https://github.com/owner/repo/issues/42"}"#,
1599            ),
1600        ]);
1601        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1602
1603        let issue = provider
1604            .edit(
1605                42,
1606                gitflow_core::issue::EditIssueArgs {
1607                    title: Some("New title".to_string()),
1608                    body: None,
1609                    milestone: None,
1610                },
1611            )
1612            .await
1613            .expect("edit should succeed");
1614
1615        assert_eq!(issue.number, 42);
1616        assert_eq!(issue.title, "New title");
1617    }
1618
1619    #[tokio::test]
1620    async fn test_should_send_only_provided_fields_for_edit() {
1621        let runner = MockCommandRunner::success("");
1622        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
1623
1624        // title-only: view() call will fail to deserialize empty stdout, that's fine —
1625        // we only assert on the recorded `gh issue edit` invocation (the first call).
1626        let _ = provider
1627            .edit(
1628                7,
1629                gitflow_core::issue::EditIssueArgs {
1630                    title: Some("T".to_string()),
1631                    body: None,
1632                    milestone: None,
1633                },
1634            )
1635            .await;
1636
1637        assert_eq!(
1638            runner.recorded_calls()[0].1,
1639            vec!["issue", "edit", "7", "--repo", "owner/repo", "--title", "T"]
1640                .into_iter()
1641                .map(String::from)
1642                .collect::<Vec<_>>()
1643        );
1644    }
1645
1646    #[tokio::test]
1647    async fn test_should_return_platform_error_when_gh_fails_for_edit() {
1648        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1649        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1650
1651        let result = provider
1652            .edit(42, gitflow_core::issue::EditIssueArgs::default())
1653            .await;
1654
1655        assert!(result.is_err());
1656        assert!(matches!(
1657            result.unwrap_err(),
1658            gitflow_core::CoreError::Cli(_)
1659        ));
1660    }
1661
1662    #[tokio::test]
1663    async fn test_should_return_platform_error_when_gh_fails_for_remove_label() {
1664        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1665        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1666
1667        let result = provider.remove_label(42, "bug").await;
1668
1669        assert!(result.is_err());
1670        assert!(matches!(
1671            result.unwrap_err(),
1672            gitflow_core::CoreError::Cli(_)
1673        ));
1674    }
1675
1676    // --- extract_missing_labels_from_error: pure-function tests ---
1677
1678    #[test]
1679    fn test_should_extract_single_missing_label_from_gh_stderr() {
1680        let stderr = b"failed to update https://github.com/owner/repo/issues/18: 'type:enhancement' not found\nfailed to update 1 issue";
1681        let missing = extract_missing_labels_from_error(stderr);
1682        assert_eq!(missing, vec!["type:enhancement".to_string()]);
1683    }
1684
1685    #[test]
1686    fn test_should_extract_multiple_missing_labels_from_gh_stderr() {
1687        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";
1688        let missing = extract_missing_labels_from_error(stderr);
1689        assert_eq!(
1690            missing,
1691            vec!["bug".to_string(), "priority:high".to_string()]
1692        );
1693    }
1694
1695    #[test]
1696    fn test_should_return_empty_when_no_label_not_found_in_stderr() {
1697        let stderr = b"gh: Not logged in. Please run `gh auth login`";
1698        let missing = extract_missing_labels_from_error(stderr);
1699        assert!(missing.is_empty());
1700    }
1701
1702    #[test]
1703    fn test_should_return_empty_for_empty_stderr() {
1704        let missing = extract_missing_labels_from_error(b"");
1705        assert!(missing.is_empty());
1706    }
1707
1708    #[test]
1709    fn test_should_handle_label_with_special_characters() {
1710        let stderr = b"failed to update https://github.com/o/r/issues/1: 'type: enhancement / bug' not found";
1711        let missing = extract_missing_labels_from_error(stderr);
1712        assert_eq!(missing, vec!["type: enhancement / bug".to_string()]);
1713    }
1714
1715    // --- add_labels: auto-create missing labels (RED phase) ---
1716
1717    #[tokio::test]
1718    async fn test_should_auto_create_label_and_retry_on_not_found() {
1719        // Sequence:
1720        // 1. `gh issue edit 18 --add-label type:enhancement` → fails (label not found)
1721        // 2. `gh label create type:enhancement --color ededed --repo owner/repo` → succeeds
1722        // 3. `gh issue edit 18 --add-label type:enhancement` → succeeds (retry)
1723        let runner = SequencedMockCommandRunner::from_results(&[
1724            (
1725                false,
1726                "failed to update https://github.com/owner/repo/issues/18: 'type:enhancement' not \
1727                 found\nfailed to update 1 issue",
1728            ),
1729            (true, "Created label type:enhancement"),
1730            (true, ""),
1731        ]);
1732        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1733
1734        let result = provider
1735            .add_labels(18, &["type:enhancement".to_string()])
1736            .await;
1737
1738        assert!(result.is_ok(), "expected Ok, got {result:?}");
1739    }
1740
1741    #[tokio::test]
1742    async fn test_should_auto_create_multiple_labels_and_retry() {
1743        // Sequence:
1744        // 1. `gh issue edit 5 --add-label bug --add-label priority:high` → fails (both missing)
1745        // 2. `gh label create bug` → succeeds
1746        // 3. `gh label create priority:high` → succeeds
1747        // 4. `gh issue edit 5 --add-label bug --add-label priority:high` → succeeds (retry)
1748        let runner = SequencedMockCommandRunner::from_results(&[
1749            (
1750                false,
1751                "failed to update https://github.com/o/r/issues/5: 'bug' not found, \
1752                 'priority:high' not found\nfailed to update 1 issue",
1753            ),
1754            (true, "Created label bug"),
1755            (true, "Created label priority:high"),
1756            (true, ""),
1757        ]);
1758        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1759
1760        let result = provider
1761            .add_labels(5, &["bug".to_string(), "priority:high".to_string()])
1762            .await;
1763
1764        assert!(result.is_ok(), "expected Ok, got {result:?}");
1765    }
1766
1767    #[tokio::test]
1768    async fn test_should_propagate_error_when_label_creation_fails() {
1769        // Sequence:
1770        // 1. `gh issue edit 1 --add-label ghost` → fails (label not found)
1771        // 2. `gh label create ghost` → also fails (permission denied)
1772        let runner = SequencedMockCommandRunner::from_results(&[
1773            (
1774                false,
1775                "failed to update https://github.com/o/r/issues/1: 'ghost' not found",
1776            ),
1777            (false, "gh: 403 Forbidden"),
1778        ]);
1779        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1780
1781        let result = provider.add_labels(1, &["ghost".to_string()]).await;
1782
1783        assert!(result.is_err());
1784        let err = result.unwrap_err();
1785        assert!(
1786            matches!(err, gitflow_core::CoreError::Cli(_)),
1787            "expected CoreError::Cli, got: {err:?}"
1788        );
1789        if let gitflow_core::CoreError::Cli(boxed) = err {
1790            assert!(
1791                boxed.raw_stderr.contains("403") || boxed.raw_stderr.contains("Forbidden"),
1792                "unexpected raw_stderr: {}",
1793                boxed.raw_stderr
1794            );
1795        }
1796    }
1797
1798    #[tokio::test]
1799    async fn test_should_not_retry_on_non_label_not_found_error() {
1800        // An auth error should propagate directly without any label create calls.
1801        // Only one response in the sequence — if the runner tries a second call,
1802        // SequencedMockCommandRunner will return an error ("no more responses").
1803        let runner = SequencedMockCommandRunner::from_results(&[(
1804            false,
1805            "gh: Not logged in. Please run `gh auth login`",
1806        )]);
1807        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1808
1809        let result = provider.add_labels(1, &["bug".to_string()]).await;
1810
1811        assert!(result.is_err());
1812    }
1813
1814    #[tokio::test]
1815    async fn test_should_propagate_retry_error_when_second_add_also_fails() {
1816        // Sequence:
1817        // 1. `gh issue edit 1 --add-label bug` → fails (label not found)
1818        // 2. `gh label create bug` → succeeds
1819        // 3. `gh issue edit 1 --add-label bug` → fails again (unrelated error)
1820        let runner = SequencedMockCommandRunner::from_results(&[
1821            (
1822                false,
1823                "failed to update https://github.com/o/r/issues/1: 'bug' not found",
1824            ),
1825            (true, "Created label bug"),
1826            (false, "gh: 500 Internal Server Error"),
1827        ]);
1828        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1829
1830        let result = provider.add_labels(1, &["bug".to_string()]).await;
1831
1832        assert!(result.is_err());
1833        let err = result.unwrap_err();
1834        assert!(
1835            matches!(err, gitflow_core::CoreError::Cli(_)),
1836            "expected CoreError::Cli, got: {err:?}"
1837        );
1838        if let gitflow_core::CoreError::Cli(boxed) = err {
1839            assert!(
1840                boxed.raw_stderr.contains("500") || boxed.raw_stderr.contains("Internal"),
1841                "unexpected raw_stderr: {}",
1842                boxed.raw_stderr
1843            );
1844        }
1845    }
1846
1847    // --- create: auto-create missing labels (RED phase) ---
1848
1849    fn create_args_with_labels(labels: Vec<String>) -> CreateIssueArgs {
1850        CreateIssueArgs {
1851            title: "New feature".to_string(),
1852            body: Some("Description".to_string()),
1853            labels,
1854            assignees: vec![],
1855            milestone: None,
1856        }
1857    }
1858
1859    #[tokio::test]
1860    async fn test_should_auto_create_label_and_retry_on_create_issue() {
1861        // Sequence:
1862        // 1. `gh issue create` → fails (label not found)
1863        // 2. `gh label create type:enhancement` → succeeds
1864        // 3. `gh issue create` (retry) → succeeds, returns URL
1865        // 4. `gh issue view <number>` → returns issue JSON
1866        let runner = SequencedMockCommandRunner::from_results(&[
1867            (false, "could not add label: 'type:enhancement' not found"),
1868            (true, "Created label type:enhancement"),
1869            (true, "https://github.com/owner/repo/issues/42"),
1870            (
1871                true,
1872                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"}"#,
1873            ),
1874        ]);
1875        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1876
1877        let result = provider
1878            .create(create_args_with_labels(vec![
1879                "type:enhancement".to_string(),
1880            ]))
1881            .await;
1882
1883        assert!(result.is_ok(), "expected Ok, got {result:?}");
1884        let issue = result.expect("already checked");
1885        assert_eq!(issue.number, 42);
1886    }
1887
1888    #[tokio::test]
1889    async fn test_should_propagate_error_when_label_create_fails_on_create_issue() {
1890        // Sequence:
1891        // 1. `gh issue create` → fails (label not found)
1892        // 2. `gh label create ghost` → also fails (permission denied)
1893        let runner = SequencedMockCommandRunner::from_results(&[
1894            (false, "could not add label: 'ghost' not found"),
1895            (false, "gh: 403 Forbidden"),
1896        ]);
1897        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1898
1899        let result = provider
1900            .create(create_args_with_labels(vec!["ghost".to_string()]))
1901            .await;
1902
1903        assert!(result.is_err());
1904    }
1905
1906    #[tokio::test]
1907    async fn test_should_not_retry_create_on_non_label_error() {
1908        // Only one response — any extra call will error with "no more responses".
1909        let runner = SequencedMockCommandRunner::from_results(&[(false, "gh: Not logged in")]);
1910        let provider = GitHubIssueProvider::with_runner("o/r", runner);
1911
1912        let result = provider
1913            .create(create_args_with_labels(vec!["bug".to_string()]))
1914            .await;
1915
1916        assert!(result.is_err());
1917    }
1918
1919    // --- milestone wiring: create/edit/list ---
1920
1921    /// A single-item `gh api repos/.../milestones?...` response resolving to
1922    /// number 3 / title "v2.0", matching `resolve_milestone_identifier`'s contract.
1923    const MILESTONE_LIST_JSON: &str = r#"[
1924        {"number": 3, "title": "v2.0", "state": "open", "description": null}
1925    ]"#;
1926
1927    #[tokio::test]
1928    async fn test_should_wire_resolved_milestone_title_into_issue_create() {
1929        // Sequence:
1930        // 1. milestone resolution: `gh api repos/owner/repo/milestones?...`
1931        //    (GitHubMilestoneProvider::list)
1932        // 2. `gh issue create ... --milestone v2.0`
1933        // 3. `gh issue view <number>` (create() delegates to view())
1934        let runner = SequencedMockCommandRunner::from_results(&[
1935            (true, MILESTONE_LIST_JSON),
1936            (true, "https://github.com/owner/repo/issues/42"),
1937            (
1938                true,
1939                r#"{"number":42,"title":"New feature","body":"Description","state":"open","labels":[],"author":{"login":"octocat","id":"1"},"assignees":[],"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","milestone":{"number":3,"title":"v2.0"},"url":"https://github.com/owner/repo/issues/42"}"#,
1940            ),
1941        ]);
1942        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
1943
1944        let mut args = create_args_with_labels(vec![]);
1945        args.milestone = Some("3".to_string()); // resolve by number
1946
1947        let issue = provider.create(args).await.expect("create should succeed");
1948        assert_eq!(
1949            issue.milestone,
1950            Some(gitflow_core::types::MilestoneRef {
1951                number: 3,
1952                title: "v2.0".into()
1953            })
1954        );
1955
1956        let calls = runner.recorded_calls();
1957        assert_eq!(calls.len(), 3, "expected exactly 3 gh invocations");
1958        assert!(
1959            calls[0].1.first().map(String::as_str) == Some("api"),
1960            "first call must resolve the milestone via `gh api`, got: {:?}",
1961            calls[0].1
1962        );
1963        let create_call = &calls[1].1;
1964        assert!(
1965            create_call
1966                .windows(2)
1967                .any(|w| w[0] == "--milestone" && w[1] == "v2.0"),
1968            "issue create argv must carry the resolved milestone title, got: {create_call:?}"
1969        );
1970    }
1971
1972    #[tokio::test]
1973    async fn test_should_propagate_error_when_milestone_identifier_not_found_on_create() {
1974        // Milestone list resolves to no match for "does-not-exist" → resolve_milestone_identifier
1975        // returns an error before `gh issue create` is ever invoked.
1976        let runner = SequencedMockCommandRunner::from_results(&[(true, MILESTONE_LIST_JSON)]);
1977        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
1978
1979        let mut args = create_args_with_labels(vec![]);
1980        args.milestone = Some("does-not-exist".to_string());
1981
1982        let result = provider.create(args).await;
1983        assert!(result.is_err());
1984    }
1985
1986    #[tokio::test]
1987    async fn test_should_wire_resolved_milestone_title_into_issue_edit() {
1988        // Sequence:
1989        // 1. milestone resolution
1990        // 2. `gh issue edit <number> --milestone v2.0`
1991        // 3. `gh issue view <number>` (edit() delegates to view())
1992        let runner = SequencedMockCommandRunner::from_results(&[
1993            (true, MILESTONE_LIST_JSON),
1994            (true, ""),
1995            (
1996                true,
1997                r#"{"number":42,"title":"T","body":null,"state":"open","labels":[],"author":{"login":"octocat","id":"1"},"assignees":[],"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","milestone":{"number":3,"title":"v2.0"},"url":"https://github.com/owner/repo/issues/42"}"#,
1998            ),
1999        ]);
2000        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
2001
2002        let issue = provider
2003            .edit(
2004                42,
2005                gitflow_core::issue::EditIssueArgs {
2006                    title: None,
2007                    body: None,
2008                    milestone: Some(Some("v2.0".to_string())),
2009                },
2010            )
2011            .await
2012            .expect("edit should succeed");
2013        assert_eq!(issue.milestone.map(|m| m.title), Some("v2.0".to_string()));
2014
2015        let calls = runner.recorded_calls();
2016        let edit_call = &calls[1].1;
2017        assert!(
2018            edit_call
2019                .windows(2)
2020                .any(|w| w[0] == "--milestone" && w[1] == "v2.0"),
2021            "issue edit argv must carry the resolved milestone title, got: {edit_call:?}"
2022        );
2023    }
2024
2025    #[tokio::test]
2026    async fn test_should_send_remove_milestone_flag_without_resolving() {
2027        // `Some(None)` means "clear the milestone" — no cross-provider resolution call
2028        // should happen; the edit call must carry `--remove-milestone` directly.
2029        let runner = MockCommandRunner::success("");
2030        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
2031
2032        let _ = provider
2033            .edit(
2034                7,
2035                gitflow_core::issue::EditIssueArgs {
2036                    title: None,
2037                    body: None,
2038                    milestone: Some(None),
2039                },
2040            )
2041            .await;
2042
2043        let calls = runner.recorded_calls();
2044        // `edit()` always delegates to `view()` afterward — 2 calls total, neither of
2045        // which is a milestone-resolution `gh api` call.
2046        assert_eq!(calls.len(), 2, "no milestone resolution call expected");
2047        assert!(
2048            calls[0].1.iter().any(|a| a == "--remove-milestone"),
2049            "edit argv must carry --remove-milestone, got: {:?}",
2050            calls[0].1
2051        );
2052    }
2053
2054    #[tokio::test]
2055    async fn test_should_wire_resolved_milestone_title_into_issue_list_filter() {
2056        // Sequence:
2057        // 1. milestone resolution
2058        // 2. `gh issue list ... --milestone v2.0`
2059        let runner =
2060            SequencedMockCommandRunner::from_results(&[(true, MILESTONE_LIST_JSON), (true, "[]")]);
2061        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
2062
2063        let args = ListIssueArgs {
2064            milestone: Some("v2.0".to_string()),
2065            ..ListIssueArgs::default()
2066        };
2067        provider.list(args).await.expect("list should succeed");
2068
2069        let calls = runner.recorded_calls();
2070        let list_call = &calls[1].1;
2071        assert!(
2072            list_call
2073                .windows(2)
2074                .any(|w| w[0] == "--milestone" && w[1] == "v2.0"),
2075            "issue list argv must carry the resolved milestone title, got: {list_call:?}"
2076        );
2077    }
2078}
2079
2080#[cfg(test)]
2081mod contract_tests {
2082    use super::*;
2083    use crate::runner::MockCommandRunner;
2084
2085    /// 契约测试:验证 gh v2.94 对 bot author 省略 `id` 字段时仍可反序列化。
2086    ///
2087    /// gh 2.94 对 bot-authored issue 返回 `{"is_bot": true, "login": "app/github-actions"}`
2088    /// 而非人类的 `{"id": "...", "login": "..."}`。`UserSummary::id` 使用 `#[serde(default)]`
2089    /// 兼容该差异,此处用真实 fixture 守护契约。
2090    #[tokio::test]
2091    async fn test_contract_issue_list_github_v294_bot_author() {
2092        let fixture = include_str!("../tests/fixtures/issue_list_github_v294_bot_author.json");
2093        let runner = MockCommandRunner::success(fixture);
2094        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
2095
2096        let issues = provider
2097            .list(ListIssueArgs::default())
2098            .await
2099            .expect("gh v2.94 bot-author fixture must parse");
2100        let issues = issues.items;
2101
2102        assert_eq!(issues.len(), 2);
2103        assert_eq!(issues[0].number, 107);
2104        assert_eq!(issues[0].author.login, "app/github-actions");
2105        assert_eq!(issues[1].number, 42);
2106        assert_eq!(issues[1].author.login, "test-user");
2107    }
2108
2109    /// 契约测试:验证 gh issue list JSON 输出与 `IssueData` 反序列化一致。
2110    ///
2111    /// 夹具来源:gh v2.x `--json` 输出格式。
2112    #[tokio::test]
2113    async fn test_contract_issue_list_github_v2() {
2114        let fixture = include_str!("../tests/fixtures/issue_list_github_v2.json");
2115        let runner = MockCommandRunner::success(fixture);
2116        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
2117
2118        let issues = provider
2119            .list(ListIssueArgs::default())
2120            .await
2121            .expect("contract fixture must parse");
2122        let issues = issues.items;
2123
2124        assert_eq!(issues.len(), 1);
2125        let issue = &issues[0];
2126        assert_eq!(issue.number, 42);
2127        assert!(!issue.title.is_empty());
2128        assert_eq!(issue.state, gitflow_core::types::State::Open);
2129        assert_eq!(issue.author.login, "test-user");
2130    }
2131
2132    /// 契约测试:验证 gh v2.97 混合 author 形状(bot 无 `id` + human 新增 `name`)可反序列化。
2133    ///
2134    /// gh 2.97.0 对 bot author 返回 `{"is_bot": true, "login": "app/github-actions"}`
2135    /// (无 `id`),对 human author 返回
2136    /// `{"id": "...", "is_bot": false, "login": "...", "name": "..."}`(新增 `name` 字段)。
2137    /// `UserSummary::id` 的 `#[serde(default)]` 兜底 bot 缺 `id`,`name` 作为未知字段被忽略。
2138    /// 夹具为 2026-08-03 从 gh 2.97.0 真实捕获(issue #108/#117)并截断 body。
2139    /// 守护 issue #117:修复前该形状触发 `missing field 'id'` 反序列化错误。
2140    #[tokio::test]
2141    async fn test_contract_issue_list_github_v297_mixed_authors() {
2142        let fixture = include_str!("../tests/fixtures/issue_list_github_v297_mixed_authors.json");
2143        let runner = MockCommandRunner::success(fixture);
2144        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
2145
2146        let issues = provider
2147            .list(ListIssueArgs::default())
2148            .await
2149            .expect("gh v2.97 mixed-author fixture must parse");
2150        let issues = issues.items;
2151
2152        assert_eq!(issues.len(), 2);
2153        // bot-authored issue: id omitted by gh → defaults to empty string
2154        assert_eq!(issues[0].number, 108);
2155        assert_eq!(issues[0].author.login, "app/github-actions");
2156        assert_eq!(issues[0].author.id, "");
2157        // human-authored issue: id present, extra `name` field ignored
2158        assert_eq!(issues[1].number, 117);
2159        assert_eq!(issues[1].author.login, "byx-darwin");
2160        assert!(!issues[1].author.id.is_empty());
2161    }
2162
2163    /// 契约测试:验证 gh v2.97 `issue view` 对 bot-authored issue 的输出可反序列化。
2164    ///
2165    /// 夹具为 2026-08-03 从 gh 2.97.0 真实捕获(issue #108,author 为
2166    /// `app/github-actions`)并截断 body。守护 issue #117 的 `close`/`view`
2167    /// 路径:bot-authored issue 的 author 对象缺少 `id` 字段。
2168    #[tokio::test]
2169    async fn test_contract_issue_view_github_v297_bot_author() {
2170        let fixture = include_str!("../tests/fixtures/issue_view_github_v297_bot_author.json");
2171        let runner = MockCommandRunner::success(fixture);
2172        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
2173
2174        let issue = provider
2175            .view(108)
2176            .await
2177            .expect("gh v2.97 bot-author view fixture must parse");
2178
2179        assert_eq!(issue.number, 108);
2180        assert_eq!(issue.author.login, "app/github-actions");
2181        assert_eq!(issue.author.id, "");
2182        assert_eq!(issue.state, gitflow_core::types::State::Open);
2183    }
2184
2185    #[tokio::test]
2186    async fn test_should_request_default_cap_plus_one_when_limit_absent() {
2187        let runner = MockCommandRunner::success("[]");
2188        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
2189        let paged = provider
2190            .list(ListIssueArgs::default())
2191            .await
2192            .expect("list should succeed");
2193        assert!(paged.items.is_empty());
2194        assert!(!paged.truncated);
2195        let args = &runner.recorded_calls()[0].1;
2196        assert!(
2197            args.windows(2).any(|w| w[0] == "--limit" && w[1] == "1001"),
2198            "无 --limit 时必须向 gh 要 DEFAULT_LIST_LIMIT + 1 = 1001 条,实际 argv: {args:?}"
2199        );
2200    }
2201
2202    #[tokio::test]
2203    async fn test_should_pass_user_limit_plus_one_to_gh() {
2204        let runner = MockCommandRunner::success("[]");
2205        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
2206        let args = ListIssueArgs {
2207            limit: Some(10),
2208            ..ListIssueArgs::default()
2209        };
2210        provider.list(args).await.expect("list should succeed");
2211        let recorded = &runner.recorded_calls()[0].1;
2212        assert!(
2213            recorded
2214                .windows(2)
2215                .any(|w| w[0] == "--limit" && w[1] == "11"),
2216            "用户指定 --limit 10 时也要跑 N+1 探测,实际 argv: {recorded:?}"
2217        );
2218    }
2219
2220    #[tokio::test]
2221    async fn test_should_report_truncation_when_gh_returns_more_than_cap() {
2222        // cap = 2 ⇒ 请求 3 条;返回 3 条 ⇒ 截到 2 条并置 truncated
2223        let stdout = r#"[
2224            {"number":1,"title":"a","state":"OPEN","body":"","labels":[],"assignees":[],"author":{"login":"u","id":"1"},"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","url":"https://example.com/1"},
2225            {"number":2,"title":"b","state":"OPEN","body":"","labels":[],"assignees":[],"author":{"login":"u","id":"1"},"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","url":"https://example.com/2"},
2226            {"number":3,"title":"c","state":"OPEN","body":"","labels":[],"assignees":[],"author":{"login":"u","id":"1"},"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","url":"https://example.com/3"}
2227        ]"#;
2228        let runner = MockCommandRunner::success(stdout);
2229        let provider = GitHubIssueProvider::with_runner("owner/repo", runner);
2230        let args = ListIssueArgs {
2231            limit: Some(2),
2232            ..ListIssueArgs::default()
2233        };
2234        let paged = provider.list(args).await.expect("list should succeed");
2235        assert_eq!(paged.items.len(), 2);
2236        assert!(paged.truncated);
2237        assert_eq!(paged.limit, 2);
2238    }
2239
2240    #[tokio::test]
2241    async fn test_should_forward_label_filter_to_gh() {
2242        let runner = MockCommandRunner::success("[]");
2243        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
2244        let args = ListIssueArgs {
2245            labels: vec!["bug".to_string(), "help wanted".to_string()],
2246            ..ListIssueArgs::default()
2247        };
2248        provider.list(args).await.expect("list should succeed");
2249        let recorded = &runner.recorded_calls()[0].1;
2250        assert!(
2251            recorded
2252                .windows(2)
2253                .any(|w| w[0] == "--label" && w[1] == "bug"),
2254            "--label 过滤此前被静默丢弃,必须真正传给 gh,实际 argv: {recorded:?}"
2255        );
2256        assert!(
2257            recorded
2258                .windows(2)
2259                .any(|w| w[0] == "--label" && w[1] == "help wanted"),
2260            "多个标签必须各自重复 --label,实际 argv: {recorded:?}"
2261        );
2262    }
2263
2264    #[tokio::test]
2265    async fn test_should_list_issues_with_state_and_label_using_full_argv() {
2266        let runner = MockCommandRunner::success("[]");
2267        let provider = GitHubIssueProvider::with_runner("owner/repo", runner.clone());
2268
2269        let _ = provider
2270            .list(ListIssueArgs {
2271                state: Some(State::Open),
2272                labels: vec!["bug".to_string()],
2273                ..ListIssueArgs::default()
2274            })
2275            .await;
2276
2277        assert_eq!(
2278            runner.recorded_calls()[0].1,
2279            vec![
2280                "issue",
2281                "list",
2282                "--repo",
2283                "owner/repo",
2284                "--json",
2285                ISSUE_FIELDS,
2286                "--state",
2287                "open",
2288                "--label",
2289                "bug",
2290                "--limit",
2291                "1001"
2292            ]
2293            .into_iter()
2294            .map(String::from)
2295            .collect::<Vec<_>>()
2296        );
2297    }
2298}