Skip to main content

gitflow_gitlab/
issue.rs

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