Skip to main content

gitflow_gitcode/
issue.rs

1//! GitCode Issue 提供者实现。
2//!
3//! 通过 `gitcode` CLI 实现 [`IssueProvider`] trait。GitCode CLI
4//! 使用 `-R` 指定仓库、`--json` 为布尔标志、`version` 子命令检测版本。
5//! JSON 响应字段名与 GitHub/GitLab CLI 不同(`user` 而非 `author` 等),
6//! 通过 [`IssueApiResponse`] 做字段映射后转换为 core 类型。
7
8use async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use gitflow_core::{
11    CoreError, Result,
12    issue::{CreateIssueArgs, IssueData, IssueProvider, ListIssueArgs},
13    types::{CommentData, Label, State, UserSummary},
14};
15use serde::Deserialize;
16use tracing::debug;
17
18use crate::{
19    error::parse_gitcode_error,
20    runner::{CommandRunner, RealCommandRunner},
21};
22
23/// gitcode CLI `issue list --json` 的响应类型。
24#[derive(Debug, Clone, Deserialize)]
25#[serde(rename_all = "lowercase")]
26struct IssueApiResponse {
27    number: String,
28    title: String,
29    body: Option<String>,
30    state: String,
31    #[serde(default)]
32    labels: Option<Vec<LabelApi>>,
33    user: Option<UserApi>,
34    #[serde(default)]
35    assignees: Option<Vec<UserApi>>,
36    created_at: Option<String>,
37    updated_at: Option<String>,
38    html_url: String,
39}
40
41#[derive(Debug, Clone, Deserialize)]
42#[serde(rename_all = "lowercase")]
43struct LabelApi {
44    name: String,
45    #[serde(default)]
46    color: Option<String>,
47    #[serde(default)]
48    description: Option<String>,
49}
50
51#[derive(Debug, Clone, Deserialize)]
52struct UserApi {
53    login: String,
54    #[serde(default)]
55    id: Option<String>,
56}
57
58impl From<IssueApiResponse> for IssueData {
59    fn from(api: IssueApiResponse) -> Self {
60        Self {
61            number: api.number.parse().unwrap_or(0),
62            title: api.title,
63            body: api.body,
64            state: match api.state.as_str() {
65                "closed" => State::Closed,
66                _ => State::Open,
67            },
68            labels: api
69                .labels
70                .unwrap_or_default()
71                .into_iter()
72                .map(Label::from)
73                .collect(),
74            author: api.user.map_or(
75                UserSummary {
76                    login: "unknown".into(),
77                    id: String::new(),
78                },
79                UserSummary::from,
80            ),
81            assignees: api
82                .assignees
83                .unwrap_or_default()
84                .into_iter()
85                .map(UserSummary::from)
86                .collect(),
87            created_at: api
88                .created_at
89                .and_then(|s| {
90                    DateTime::parse_from_rfc3339(&s)
91                        .ok()
92                        .map(|d| d.with_timezone(&Utc))
93                })
94                .unwrap_or_else(Utc::now),
95            updated_at: api
96                .updated_at
97                .and_then(|s| {
98                    DateTime::parse_from_rfc3339(&s)
99                        .ok()
100                        .map(|d| d.with_timezone(&Utc))
101                })
102                .unwrap_or_else(Utc::now),
103            url: api.html_url,
104        }
105    }
106}
107
108impl From<LabelApi> for Label {
109    fn from(api: LabelApi) -> Self {
110        Self {
111            name: api.name,
112            color: api.color,
113            description: api.description,
114        }
115    }
116}
117
118impl From<UserApi> for UserSummary {
119    fn from(api: UserApi) -> Self {
120        Self {
121            login: api.login,
122            id: api.id.unwrap_or_default(),
123        }
124    }
125}
126
127/// gitcode CLI `issue comment --json` 的响应类型,兼容两种已观测形态:
128/// - v0.6.x:`user` 为对象(含 `login`/`id`)、`id` 为数值、`created_at` 为带偏移 RFC3339
129/// - 旧版本:`author` 为纯字符串(用户名)、`id` 为字符串、`created_at` 为 `YYYY-MM-DD HH:MM:SS`
130#[derive(Debug, Clone, Deserialize)]
131struct CommentApiResponse {
132    #[serde(deserialize_with = "gitflow_core::types::deserialize_u64_or_string")]
133    id: u64,
134    #[serde(default)]
135    body: String,
136    #[serde(default)]
137    author: Option<String>,
138    #[serde(default)]
139    user: Option<UserApi>,
140    #[serde(default)]
141    created_at: Option<String>,
142}
143
144impl From<CommentApiResponse> for CommentData {
145    fn from(api: CommentApiResponse) -> Self {
146        let author = api.user.map_or_else(
147            || UserSummary {
148                login: api.author.unwrap_or_else(|| "unknown".into()),
149                id: String::new(),
150            },
151            UserSummary::from,
152        );
153        let created_at = api.created_at.as_deref().map_or_else(Utc::now, |s| {
154            DateTime::parse_from_rfc3339(s)
155                .map(|dt| dt.with_timezone(&Utc))
156                .or_else(|_| {
157                    chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
158                        .map(|ndt| ndt.and_utc())
159                })
160                .unwrap_or_else(|_| Utc::now())
161        });
162        Self {
163            id: api.id,
164            body: api.body,
165            author,
166            created_at,
167        }
168    }
169}
170
171/// gitcode CLI `issue close/reopen --json` 的响应类型。
172///
173/// GitCode close/reopen 返回的字段比 list/view 少很多,
174/// `number` 为 integer,没有 `title`/`body`/`labels` 等字段。
175#[derive(Debug, Clone, Deserialize)]
176struct CloseApiResponse {
177    number: u64,
178    state: String,
179    url: String,
180}
181
182impl From<CloseApiResponse> for IssueData {
183    fn from(api: CloseApiResponse) -> Self {
184        Self {
185            number: api.number,
186            title: String::new(),
187            body: None,
188            state: match api.state.as_str() {
189                "closed" => State::Closed,
190                _ => State::Open,
191            },
192            labels: Vec::new(),
193            author: UserSummary {
194                login: "unknown".into(),
195                id: String::new(),
196            },
197            assignees: Vec::new(),
198            created_at: Utc::now(),
199            updated_at: Utc::now(),
200            url: api.url,
201        }
202    }
203}
204
205/// GitCode Issue 提供者,通过 `gitcode` CLI 操作。
206///
207/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
208/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
209#[derive(Debug, Clone)]
210pub struct GitCodeIssueProvider<R: CommandRunner = RealCommandRunner> {
211    /// GitCode `owner/repo`。
212    repo: String,
213    /// 用于执行 `gitcode` CLI 命令的 runner。
214    runner: R,
215}
216
217impl GitCodeIssueProvider<RealCommandRunner> {
218    /// 创建一个新的 `GitCodeIssueProvider`,使用真实的进程执行器。
219    #[must_use]
220    pub fn new(repo: impl Into<String>) -> Self {
221        Self {
222            repo: repo.into(),
223            runner: RealCommandRunner,
224        }
225    }
226}
227
228impl<R: CommandRunner> GitCodeIssueProvider<R> {
229    /// 使用自定义 [`CommandRunner`] 创建提供者。
230    ///
231    /// 主要用于测试,可注入模拟 runner 以控制 `gitcode` CLI 的输出。
232    #[must_use]
233    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
234        Self {
235            repo: repo.into(),
236            runner,
237        }
238    }
239
240    /// 创建缺失的标签(使用 `--force` 保持幂等)。
241    ///
242    /// # Errors
243    ///
244    /// 当 `gitcode label create` 调用失败时返回错误。
245    async fn ensure_label_exists(&self, name: &str) -> Result<()> {
246        let binary = crate::gitcode_binary();
247        debug!(repo = %self.repo, name, "auto-creating missing label via `gc label create`");
248
249        let output = self
250            .runner
251            .run(
252                &binary,
253                &[
254                    "label", "create", name, "--color", "ededed", "-R", &self.repo,
255                ],
256            )
257            .await
258            .map_err(|e| {
259                CoreError::Platform(format!("Failed to spawn gitcode label create: {e}"))
260            })?;
261
262        if !output.status.success() {
263            let gitcode_err = parse_gitcode_error(&output.stderr);
264            tracing::debug!(error = %gitcode_err, "Failed to auto-create label");
265            return Err(CoreError::Platform(format!(
266                "Failed to auto-create label '{name}': {}",
267                gitcode_err.user_message
268            )));
269        }
270
271        Ok(())
272    }
273}
274
275#[async_trait]
276impl<R: CommandRunner + 'static> IssueProvider for GitCodeIssueProvider<R> {
277    async fn create(&self, args: CreateIssueArgs) -> Result<IssueData> {
278        let binary = crate::gitcode_binary();
279        let mut cmd_args: Vec<&str> = vec![
280            "issue",
281            "create",
282            "-R",
283            &self.repo,
284            "--title",
285            &args.title,
286            "--json",
287        ];
288
289        if let Some(body) = &args.body {
290            cmd_args.push("--body");
291            cmd_args.push(body);
292        }
293        for label in &args.labels {
294            cmd_args.push("--label");
295            cmd_args.push(label);
296        }
297        for assignee in &args.assignees {
298            cmd_args.push("--assignee");
299            cmd_args.push(assignee);
300        }
301
302        debug!(repo = %self.repo, title = %args.title, "spawning gitcode issue create");
303        let output = self
304            .runner
305            .run(&binary, &cmd_args)
306            .await
307            .map_err(|e| CoreError::Platform(format!("{e}")))?;
308        if !output.status.success() {
309            // gc issue create fails when a requested label doesn't exist.
310            // Auto-create missing labels and retry once.
311            let missing = extract_missing_labels_from_error(&output.stderr);
312            if !missing.is_empty() {
313                debug!(
314                    repo = %self.repo,
315                    missing_count = missing.len(),
316                    "auto-creating missing label(s) before retrying issue create"
317                );
318                for label in &missing {
319                    self.ensure_label_exists(label).await?;
320                }
321
322                let retry_output = self.runner.run(&binary, &cmd_args).await.map_err(|e| {
323                    CoreError::Platform(format!("Failed to spawn gitcode on retry: {e}"))
324                })?;
325                if !retry_output.status.success() {
326                    return Err(parse_gitcode_error(&retry_output.stderr).into());
327                }
328                return serde_json::from_slice::<IssueApiResponse>(&retry_output.stdout)
329                    .map(IssueData::from)
330                    .map_err(CoreError::Serialization);
331            }
332
333            return Err(parse_gitcode_error(&output.stderr).into());
334        }
335        serde_json::from_slice::<IssueApiResponse>(&output.stdout)
336            .map(IssueData::from)
337            .map_err(CoreError::Serialization)
338    }
339
340    async fn list(&self, args: ListIssueArgs) -> Result<Vec<IssueData>> {
341        let binary = crate::gitcode_binary();
342        let mut cmd_args: Vec<&str> = vec!["issue", "list", "-R", &self.repo, "--json"];
343
344        if let Some(ref state) = args.state {
345            cmd_args.push("--state");
346            cmd_args.push(match state {
347                State::Open => "open",
348                State::Closed => "closed",
349            });
350        }
351        if let Some(ref search) = args.search {
352            cmd_args.push("--search");
353            cmd_args.push(search);
354        }
355        let limit_str = args.limit.map(|limit| limit.to_string());
356        if let Some(ref limit) = limit_str {
357            cmd_args.push("--limit");
358            cmd_args.push(limit);
359        }
360        for label in &args.labels {
361            cmd_args.push("--label");
362            cmd_args.push(label);
363        }
364
365        debug!(repo = %self.repo, "spawning gitcode issue list");
366        let output = self
367            .runner
368            .run(&binary, &cmd_args)
369            .await
370            .map_err(|e| CoreError::Platform(format!("{e}")))?;
371        if !output.status.success() {
372            return Err(parse_gitcode_error(&output.stderr).into());
373        }
374        let issues: Vec<IssueApiResponse> =
375            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
376        Ok(issues.into_iter().map(IssueData::from).collect())
377    }
378
379    async fn view(&self, number: u64) -> Result<IssueData> {
380        let binary = crate::gitcode_binary();
381        let number_str = number.to_string();
382        debug!(repo = %self.repo, number, "spawning gitcode issue view");
383        let output = self
384            .runner
385            .run(
386                &binary,
387                &["issue", "view", &number_str, "-R", &self.repo, "--json"],
388            )
389            .await
390            .map_err(|e| CoreError::Platform(format!("{e}")))?;
391
392        if !output.status.success() {
393            return Err(parse_gitcode_error(&output.stderr).into());
394        }
395        serde_json::from_slice::<IssueApiResponse>(&output.stdout)
396            .map(IssueData::from)
397            .map_err(CoreError::Serialization)
398    }
399
400    async fn close(&self, number: u64) -> Result<IssueData> {
401        let binary = crate::gitcode_binary();
402        let number_str = number.to_string();
403        debug!(repo = %self.repo, number, "spawning gitcode issue close");
404        let output = self
405            .runner
406            .run(
407                &binary,
408                &[
409                    "issue",
410                    "close",
411                    &number_str,
412                    "-R",
413                    &self.repo,
414                    "--yes",
415                    "--json",
416                ],
417            )
418            .await
419            .map_err(|e| CoreError::Platform(format!("{e}")))?;
420
421        if !output.status.success() {
422            return Err(parse_gitcode_error(&output.stderr).into());
423        }
424        serde_json::from_slice::<CloseApiResponse>(&output.stdout)
425            .map(IssueData::from)
426            .map_err(CoreError::Serialization)
427    }
428
429    async fn reopen(&self, number: u64) -> Result<IssueData> {
430        let binary = crate::gitcode_binary();
431        let number_str = number.to_string();
432        debug!(repo = %self.repo, number, "spawning gitcode issue reopen");
433        let output = self
434            .runner
435            .run(
436                &binary,
437                &[
438                    "issue",
439                    "reopen",
440                    &number_str,
441                    "-R",
442                    &self.repo,
443                    "--yes",
444                    "--json",
445                ],
446            )
447            .await
448            .map_err(|e| CoreError::Platform(format!("{e}")))?;
449
450        if !output.status.success() {
451            return Err(parse_gitcode_error(&output.stderr).into());
452        }
453        serde_json::from_slice::<CloseApiResponse>(&output.stdout)
454            .map(IssueData::from)
455            .map_err(CoreError::Serialization)
456    }
457
458    /// 在指定 Issue 上添加评论。
459    ///
460    /// 调用 `gitcode issue comment <number> -R <repo> --body "<body>" --json`
461    /// 发布评论,并返回新建评论的数据。
462    ///
463    /// # Errors
464    ///
465    /// 当 Issue 不存在、`body` 为空或 `gitcode` CLI 调用失败时返回错误。
466    async fn comment(&self, number: u64, body: &str) -> Result<CommentData> {
467        let binary = crate::gitcode_binary();
468        let number_str = number.to_string();
469        debug!(repo = %self.repo, number, "spawning `gc issue comment`");
470
471        let output = self
472            .runner
473            .run(
474                &binary,
475                &[
476                    "issue",
477                    "comment",
478                    &number_str,
479                    "-R",
480                    &self.repo,
481                    "--body",
482                    body,
483                    "--json",
484                ],
485            )
486            .await
487            .map_err(|e| CoreError::Platform(format!("Failed to spawn gitcode: {e}")))?;
488
489        if !output.status.success() {
490            return Err(parse_gitcode_error(&output.stderr).into());
491        }
492
493        let api: CommentApiResponse =
494            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
495
496        Ok(CommentData::from(api))
497    }
498
499    /// 为指定 Issue 添加一个或多个标签。
500    ///
501    /// 调用 `gitcode issue label <number> --add <labels> -R <repo>` 添加标签
502    ///(逗号分隔的 `--add` 是 gitcode v0.6.x 的专用标签子命令;`issue edit`
503    /// 不支持 gh 风格的 `--add-label` flag)。`labels` 为空时不进行任何调用。
504    ///
505    /// # 自动创建缺失标签
506    ///
507    /// 当添加因标签不存在而失败时,本方法会自动调用 `gitcode label create`
508    /// 创建缺失的标签(默认颜色 `ededed`),然后重试一次。
509    ///
510    /// # Errors
511    ///
512    /// 当 Issue 不存在、标签创建失败或 `gitcode` CLI 调用失败时返回错误。
513    async fn add_labels(&self, number: u64, labels: &[String]) -> Result<()> {
514        if labels.is_empty() {
515            return Ok(());
516        }
517
518        let binary = crate::gitcode_binary();
519        let number_str = number.to_string();
520        let joined = labels.join(",");
521        debug!(
522            repo = %self.repo,
523            number,
524            label_count = labels.len(),
525            "spawning `gitcode issue label --add`"
526        );
527
528        let cmd_args: Vec<&str> = vec![
529            "issue",
530            "label",
531            &number_str,
532            "--add",
533            &joined,
534            "-R",
535            &self.repo,
536        ];
537
538        let output = self
539            .runner
540            .run(&binary, &cmd_args)
541            .await
542            .map_err(|e| CoreError::Platform(format!("Failed to spawn gitcode: {e}")))?;
543
544        if output.status.success() {
545            return Ok(());
546        }
547
548        // Auto-create missing labels and retry once.
549        let missing = extract_missing_labels_from_error(&output.stderr);
550        if missing.is_empty() {
551            return Err(parse_gitcode_error(&output.stderr).into());
552        }
553
554        debug!(
555            repo = %self.repo,
556            missing_count = missing.len(),
557            "auto-creating missing label(s) before retry"
558        );
559
560        for label in &missing {
561            self.ensure_label_exists(label).await?;
562        }
563
564        let retry_output =
565            self.runner.run(&binary, &cmd_args).await.map_err(|e| {
566                CoreError::Platform(format!("Failed to spawn gitcode on retry: {e}"))
567            })?;
568
569        if !retry_output.status.success() {
570            return Err(parse_gitcode_error(&retry_output.stderr).into());
571        }
572
573        Ok(())
574    }
575
576    /// 从指定 Issue 移除一个标签。
577    ///
578    /// 调用 `gitcode issue label <number> --remove <label> -R <repo>` 移除标签。
579    ///
580    /// # Errors
581    ///
582    /// 当 Issue 不存在、标签未附加到该 Issue 或 `gitcode` CLI 调用失败时返回错误。
583    async fn remove_label(&self, number: u64, label: &str) -> Result<()> {
584        let binary = crate::gitcode_binary();
585        let number_str = number.to_string();
586        debug!(repo = %self.repo, number, label, "spawning `gitcode issue label --remove`");
587
588        let output = self
589            .runner
590            .run(
591                &binary,
592                &[
593                    "issue",
594                    "label",
595                    &number_str,
596                    "--remove",
597                    label,
598                    "-R",
599                    &self.repo,
600                ],
601            )
602            .await
603            .map_err(|e| CoreError::Platform(format!("Failed to spawn gitcode: {e}")))?;
604
605        if !output.status.success() {
606            return Err(parse_gitcode_error(&output.stderr).into());
607        }
608
609        Ok(())
610    }
611}
612
613/// 从 `gc issue label --add` 的 stderr 中提取缺失的标签名。
614///
615/// GitCode CLI 是 `gh` 的分支,错误格式与 `gh` 一致:
616/// `'<label>' not found`。
617fn extract_missing_labels_from_error(stderr: &[u8]) -> Vec<String> {
618    let text = String::from_utf8_lossy(stderr);
619    let mut labels = Vec::new();
620    let mut search_from: usize = 0;
621
622    while let Some(rel_open) = text[search_from..].find('\'') {
623        let open_pos = search_from + rel_open + 1;
624        let Some(rel_close) = text[open_pos..].find('\'') else {
625            break;
626        };
627        let close_pos = open_pos + rel_close;
628        let after_close = &text[close_pos + 1..];
629
630        if after_close.starts_with(" not found") {
631            let label = text[open_pos..close_pos].to_string();
632            if !label.is_empty() {
633                labels.push(label);
634            }
635        }
636        search_from = close_pos + 1;
637    }
638
639    labels
640}
641
642#[cfg(test)]
643mod tests {
644    use gitflow_core::types::UserSummary;
645
646    use super::*;
647    use crate::runner::{MockCommandRunner, RecordingMockRunner, SequencedMockCommandRunner};
648
649    #[test]
650    fn test_should_construct_gitcode_issue_provider() {
651        let provider = GitCodeIssueProvider::new("octocat/hello-world");
652        assert_eq!(provider.repo, "octocat/hello-world");
653    }
654
655    #[test]
656    fn test_should_construct_gitcode_issue_provider_from_string() {
657        let repo = String::from("octocat/hello-world");
658        let provider = GitCodeIssueProvider::new(repo);
659        assert_eq!(provider.repo, "octocat/hello-world");
660    }
661
662    #[test]
663    fn test_should_deserialize_issue_data_from_gc_output() {
664        let gc_json = br#"{
665            "number": 42,
666            "title": "Fix login bug",
667            "body": "Reproduced on v1.2.3",
668            "state": "open",
669            "labels": [
670                {"name": "bug", "color": "d73a4a", "description": "Something isn't working"}
671            ],
672            "author": {"login": "octocat", "id": "1"},
673            "assignees": [{"login": "alice", "id": "7"}],
674            "createdAt": "2026-01-15T09:30:00Z",
675            "updatedAt": "2026-01-16T11:00:00Z",
676            "url": "https://gitcode.com/octocat/hello-world/issues/42"
677        }"#;
678
679        let issue: IssueData = serde_json::from_slice(gc_json).expect("valid IssueData JSON");
680        assert_eq!(issue.number, 42);
681        assert_eq!(issue.title, "Fix login bug");
682        assert_eq!(issue.state, State::Open);
683        assert_eq!(issue.labels.len(), 1);
684        assert_eq!(issue.author.login, "octocat");
685        assert_eq!(issue.assignees.len(), 1);
686        assert_eq!(
687            issue.url,
688            "https://gitcode.com/octocat/hello-world/issues/42"
689        );
690    }
691
692    #[test]
693    fn test_should_deserialize_empty_issue_list_from_gc_output() {
694        let gc_json = b"[]";
695        let issues: Vec<IssueData> = serde_json::from_slice(gc_json).expect("valid IssueData list");
696        assert!(issues.is_empty());
697    }
698
699    #[test]
700    fn test_should_debug_format_provider() {
701        let provider = GitCodeIssueProvider::new("octocat/hello-world");
702        let debug = format!("{provider:?}");
703        assert!(debug.contains("GitCodeIssueProvider"));
704        assert!(debug.contains("octocat/hello-world"));
705    }
706
707    #[test]
708    fn test_should_deserialize_closed_issue_from_gc_close_output() {
709        let gc_json = br#"{
710            "number": 10,
711            "title": "Fixed typo",
712            "body": null,
713            "state": "closed",
714            "labels": [],
715            "author": {"login": "dev", "id": "5"},
716            "assignees": [],
717            "createdAt": "2026-06-01T08:00:00Z",
718            "updatedAt": "2026-06-02T12:00:00Z",
719            "url": "https://gitcode.com/octocat/hello-world/issues/10"
720        }"#;
721
722        let issue: IssueData = serde_json::from_slice(gc_json).expect("valid closed IssueData");
723        assert_eq!(issue.number, 10);
724        assert_eq!(issue.state, State::Closed);
725    }
726
727    #[test]
728    fn test_should_deserialize_reopened_issue_from_gc_reopen_output() {
729        let gc_json = br#"{
730            "number": 10,
731            "title": "Fixed typo",
732            "body": null,
733            "state": "open",
734            "labels": [],
735            "author": {"login": "dev", "id": "5"},
736            "assignees": [],
737            "createdAt": "2026-06-01T08:00:00Z",
738            "updatedAt": "2026-06-03T09:00:00Z",
739            "url": "https://gitcode.com/octocat/hello-world/issues/10"
740        }"#;
741
742        let issue: IssueData = serde_json::from_slice(gc_json).expect("valid reopened IssueData");
743        assert_eq!(issue.number, 10);
744        assert_eq!(issue.state, State::Open);
745    }
746
747    #[test]
748    fn test_should_deserialize_comment_data_from_gc_comment_output() {
749        let gc_json = br#"{
750            "id": "1001",
751            "body": "Thanks for reporting, looking into it.",
752            "author": "maintainer",
753            "created_at": "2026-06-15 14:00:00"
754        }"#;
755
756        let api: CommentApiResponse =
757            serde_json::from_slice(gc_json).expect("valid CommentApiResponse");
758        let comment = CommentData::from(api);
759        assert_eq!(comment.id, 1001);
760        assert_eq!(comment.body, "Thanks for reporting, looking into it.");
761        assert_eq!(comment.author.login, "maintainer");
762    }
763
764    #[test]
765    fn test_should_roundtrip_comment_data_via_serde() {
766        let comment = CommentData {
767            id: 77,
768            body: "reviewed".into(),
769            author: UserSummary {
770                login: "alice".into(),
771                id: "3".to_string(),
772            },
773            created_at: "2026-05-01T00:00:00Z".parse().expect("valid date"),
774        };
775        let json = serde_json::to_string(&comment).expect("serialize");
776        let round_tripped: CommentData = serde_json::from_str(&json).expect("deserialize");
777        assert_eq!(round_tripped.id, comment.id);
778        assert_eq!(round_tripped.body, comment.body);
779        assert_eq!(round_tripped.author.login, comment.author.login);
780    }
781
782    #[test]
783    fn test_should_create_provider_with_different_repos() {
784        let r1 = GitCodeIssueProvider::new("org/repo-a");
785        let r2 = GitCodeIssueProvider::new("org/repo-b");
786        assert_eq!(r1.repo, "org/repo-a");
787        assert_eq!(r2.repo, "org/repo-b");
788    }
789
790    #[test]
791    fn test_should_clone_gitcode_issue_provider() {
792        let original = GitCodeIssueProvider::new("owner/repo");
793        let cloned = original.clone();
794        assert_eq!(original.repo, cloned.repo);
795    }
796
797    // --- Failure-path tests using an injected MockCommandRunner ---
798
799    fn sample_create_args() -> CreateIssueArgs {
800        CreateIssueArgs {
801            title: "Bug report".to_string(),
802            body: Some("Steps to reproduce".to_string()),
803            labels: vec!["bug".to_string()],
804            assignees: vec!["alice".to_string()],
805        }
806    }
807
808    #[tokio::test]
809    async fn test_should_return_platform_error_when_gc_fails_for_view() {
810        let runner = MockCommandRunner::failure("issue not found", 256);
811        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
812
813        let result = provider.view(999).await;
814
815        assert!(matches!(
816            result.unwrap_err(),
817            gitflow_core::CoreError::Cli(_)
818        ));
819    }
820
821    #[tokio::test]
822    async fn test_should_return_serialization_error_on_invalid_json_for_view() {
823        let runner = MockCommandRunner::success("not valid json");
824        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
825
826        let result = provider.view(1).await;
827
828        assert!(matches!(
829            result.unwrap_err(),
830            gitflow_core::CoreError::Serialization(_)
831        ));
832    }
833
834    #[tokio::test]
835    async fn test_should_return_platform_error_when_gc_fails_for_list() {
836        let runner = MockCommandRunner::failure("forbidden", 256);
837        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
838
839        let result = provider.list(ListIssueArgs::default()).await;
840
841        assert!(matches!(
842            result.unwrap_err(),
843            gitflow_core::CoreError::Cli(_)
844        ));
845    }
846
847    #[tokio::test]
848    async fn test_should_return_serialization_error_on_invalid_json_for_list() {
849        let runner = MockCommandRunner::success("invalid");
850        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
851
852        let result = provider.list(ListIssueArgs::default()).await;
853
854        assert!(matches!(
855            result.unwrap_err(),
856            gitflow_core::CoreError::Serialization(_)
857        ));
858    }
859
860    #[tokio::test]
861    async fn test_should_return_platform_error_when_gc_fails_for_create() {
862        let runner = MockCommandRunner::failure("validation failed", 256);
863        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
864
865        let result = provider.create(sample_create_args()).await;
866
867        assert!(matches!(
868            result.unwrap_err(),
869            gitflow_core::CoreError::Cli(_)
870        ));
871    }
872
873    #[tokio::test]
874    async fn test_should_return_serialization_error_on_invalid_json_for_create() {
875        let runner = MockCommandRunner::success("not valid json");
876        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
877
878        let result = provider.create(sample_create_args()).await;
879
880        assert!(matches!(
881            result.unwrap_err(),
882            gitflow_core::CoreError::Serialization(_)
883        ));
884    }
885
886    #[tokio::test]
887    async fn test_should_return_platform_error_when_gc_fails_for_close() {
888        let runner = MockCommandRunner::failure("not found", 256);
889        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
890
891        let result = provider.close(42).await;
892
893        assert!(matches!(
894            result.unwrap_err(),
895            gitflow_core::CoreError::Cli(_)
896        ));
897    }
898
899    #[tokio::test]
900    async fn test_should_return_platform_error_when_gc_fails_for_reopen() {
901        let runner = MockCommandRunner::failure("not found", 256);
902        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
903
904        let result = provider.reopen(42).await;
905
906        assert!(matches!(
907            result.unwrap_err(),
908            gitflow_core::CoreError::Cli(_)
909        ));
910    }
911
912    #[tokio::test]
913    async fn test_should_return_platform_error_when_gc_fails_for_comment() {
914        let runner = MockCommandRunner::failure("not found", 256);
915        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
916
917        let result = provider.comment(42, "a comment").await;
918
919        assert!(matches!(
920            result.unwrap_err(),
921            gitflow_core::CoreError::Cli(_)
922        ));
923    }
924
925    #[tokio::test]
926    async fn test_should_return_platform_error_when_gc_fails_for_add_labels() {
927        let runner = MockCommandRunner::failure("not found", 256);
928        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
929
930        let result = provider.add_labels(42, &["bug".to_string()]).await;
931
932        assert!(matches!(
933            result.unwrap_err(),
934            gitflow_core::CoreError::Cli(_)
935        ));
936    }
937
938    #[tokio::test]
939    async fn test_should_return_platform_error_when_gc_fails_for_remove_label() {
940        let runner = MockCommandRunner::failure("not found", 256);
941        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
942
943        let result = provider.remove_label(42, "bug").await;
944
945        assert!(matches!(
946            result.unwrap_err(),
947            gitflow_core::CoreError::Cli(_)
948        ));
949    }
950
951    // --- extract_missing_labels_from_error: pure-function tests ---
952
953    #[test]
954    fn test_should_extract_single_missing_label_from_gc_stderr() {
955        let stderr =
956            b"failed to update https://gitcode.com/owner/repo/issues/18: 'type:enhancement' not found";
957        let missing = extract_missing_labels_from_error(stderr);
958        assert_eq!(missing, vec!["type:enhancement".to_string()]);
959    }
960
961    #[test]
962    fn test_should_return_empty_when_no_label_not_found_in_gc_stderr() {
963        let stderr = b"gitcode: Not logged in";
964        let missing = extract_missing_labels_from_error(stderr);
965        assert!(missing.is_empty());
966    }
967
968    // --- add_labels: auto-create missing labels ---
969
970    #[tokio::test]
971    async fn test_should_auto_create_label_and_retry_on_add_labels() {
972        // Sequence:
973        // 1. `gc issue edit 18 --add-label type:enhancement` → fails
974        // 2. `gc label create type:enhancement --color ededed -R owner/repo` → succeeds
975        // 3. `gc issue edit 18 --add-label type:enhancement` → succeeds (retry)
976        let runner = SequencedMockCommandRunner::from_results(&[
977            (
978                false,
979                "failed to update https://gitcode.com/owner/repo/issues/18: 'type:enhancement' \
980                 not found",
981            ),
982            (true, ""),
983            (true, ""),
984        ]);
985        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
986
987        let result = provider
988            .add_labels(18, &["type:enhancement".to_string()])
989            .await;
990
991        assert!(result.is_ok(), "expected Ok, got {result:?}");
992    }
993
994    #[tokio::test]
995    async fn test_should_propagate_error_when_gc_label_create_fails() {
996        let runner = SequencedMockCommandRunner::from_results(&[
997            (false, "failed to update ...: 'ghost' not found"),
998            (false, "gitcode: 403 Forbidden"),
999        ]);
1000        let provider = GitCodeIssueProvider::with_runner("o/r", runner);
1001
1002        let result = provider.add_labels(1, &["ghost".to_string()]).await;
1003
1004        assert!(result.is_err());
1005    }
1006
1007    #[tokio::test]
1008    async fn test_should_not_retry_on_non_label_error_gc() {
1009        let runner = SequencedMockCommandRunner::from_results(&[(false, "gitcode: Not logged in")]);
1010        let provider = GitCodeIssueProvider::with_runner("o/r", runner);
1011
1012        let result = provider.add_labels(1, &["bug".to_string()]).await;
1013
1014        assert!(result.is_err());
1015    }
1016
1017    #[tokio::test]
1018    async fn test_should_invoke_issue_label_subcommand_for_add_labels() {
1019        let runner = RecordingMockRunner::success("");
1020        let provider = GitCodeIssueProvider::with_runner("o/r", runner.clone());
1021
1022        provider
1023            .add_labels(54, &["type:bug".to_string(), "priority:high".to_string()])
1024            .await
1025            .expect("add_labels should succeed");
1026
1027        let calls = runner.calls();
1028        assert_eq!(calls.len(), 1);
1029        assert_eq!(
1030            calls[0],
1031            vec![
1032                "issue",
1033                "label",
1034                "54",
1035                "--add",
1036                "type:bug,priority:high",
1037                "-R",
1038                "o/r"
1039            ],
1040            r"gitcode v0.6.1 的 issue edit 没有 --add-label flag(Issue #90)"
1041        );
1042    }
1043
1044    #[tokio::test]
1045    async fn test_should_return_ok_without_any_call_for_empty_labels() {
1046        let runner = RecordingMockRunner::success("");
1047        let provider = GitCodeIssueProvider::with_runner("o/r", runner.clone());
1048
1049        provider
1050            .add_labels(1, &[])
1051            .await
1052            .expect("empty labels is a no-op");
1053
1054        assert!(runner.calls().is_empty());
1055    }
1056
1057    #[tokio::test]
1058    async fn test_should_invoke_issue_label_subcommand_for_remove_label() {
1059        let runner = RecordingMockRunner::success("");
1060        let provider = GitCodeIssueProvider::with_runner("o/r", runner.clone());
1061
1062        provider
1063            .remove_label(54, "triage:done")
1064            .await
1065            .expect("remove should succeed");
1066
1067        assert_eq!(
1068            runner.calls()[0],
1069            vec![
1070                "issue",
1071                "label",
1072                "54",
1073                "--remove",
1074                "triage:done",
1075                "-R",
1076                "o/r"
1077            ]
1078        );
1079    }
1080
1081    #[tokio::test]
1082    async fn test_should_auto_create_missing_label_and_retry_via_issue_label() {
1083        // 1. issue label --add 失败,报告标签缺失
1084        // 2. label create 成功(自动创建)
1085        // 3. issue label --add 重试成功
1086        let runner = SequencedMockCommandRunner::from_results(&[
1087            (false, "HTTP 404: 'type:new' not found"),
1088            (true, r#"{"name": "type:new", "color": "ededed"}"#),
1089            (true, ""),
1090        ]);
1091        let provider = GitCodeIssueProvider::with_runner("o/r", runner);
1092
1093        provider
1094            .add_labels(18, &["type:new".to_string()])
1095            .await
1096            .expect("should recover by auto-creating the label");
1097    }
1098
1099    #[test]
1100    fn test_should_parse_issue_comment_with_user_object() {
1101        let json = r#"{"id": 12, "body": "hi", "user": {"login": "bob", "id": "u2"}, "created_at": "2026-07-30T12:00:00+08:00"}"#;
1102        let api: CommentApiResponse = serde_json::from_str(json).expect("user-object shape");
1103        let comment: CommentData = api.into();
1104        assert_eq!(comment.id, 12);
1105        assert_eq!(comment.author.login, "bob");
1106        assert_eq!(comment.author.id, "u2");
1107    }
1108}
1109
1110#[cfg(test)]
1111mod contract_tests {
1112    use super::*;
1113    use crate::runner::MockCommandRunner;
1114
1115    /// 契约测试:验证 gitcode issue list JSON 输出与反序列化一致。
1116    ///
1117    /// 夹具来源:gitcode v0.6.x 真实 CLI 输出。
1118    #[tokio::test]
1119    async fn test_contract_issue_list_gitcode_v0_6() {
1120        let fixture = include_str!("../tests/fixtures/issue_list_gitcode_v0.6.json");
1121        let runner = MockCommandRunner::success(fixture);
1122        let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
1123
1124        let issues = provider
1125            .list(ListIssueArgs::default())
1126            .await
1127            .expect("contract fixture must parse");
1128
1129        assert_eq!(issues.len(), 1);
1130        let issue = &issues[0];
1131        assert_eq!(issue.number, 15);
1132        assert!(!issue.title.is_empty());
1133        assert_eq!(issue.state, gitflow_core::types::State::Open);
1134    }
1135}