gitflow-gitlab 1.3.0

gf 的 GitLab 适配器,基于 glab CLI 提供 Issue/MR/Release/Review 等能力。GitLab adapter for gf via glab CLI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! GitLab Review 提供者实现。
//!
//! 通过 `glab mr approve` / `glab mr revoke` / `glab mr note` CLI 实现
//! [`ReviewProvider`] trait,支持 MR 审查的评论、批准、要求修改及提交审查。
//! 所有方法通过 `tokio::process::Command` 调用 `glab`,捕获 stdout 并解析 JSON。
//!
//! glab 的审查命令与 gh 不同:
//! - 批准使用 `glab mr approve`
//! - 撤回使用 `glab mr revoke`
//! - 评论使用 `glab mr note`
//!
//! 由于 glab 不提供统一的 `review --json` 输出,本模块在审查操作后
//! 构造符合 [`ReviewData`] 的返回值。

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use gitflow_core::{
    CoreError, Result,
    review::{ReviewData, ReviewProvider, ReviewState},
    types::UserSummary,
};
use serde::Deserialize;
use tracing::debug;

use crate::error::parse_glab_error;

/// GitLab Review 提供者,通过 `glab` CLI 操作。
///
/// # Examples
///
/// ```no_run
/// use gitflow_gitlab::GitLabReviewProvider;
///
/// let provider = GitLabReviewProvider::new("gitlab-org/gitlab");
/// ```
#[derive(Debug, Clone)]
pub struct GitLabReviewProvider {
    /// GitLab `namespace/project`。
    repo: String,
}

impl GitLabReviewProvider {
    /// 创建新的 GitLab Review 提供者。
    ///
    /// `repo` 格式为 `namespace/project`。
    #[must_use]
    pub fn new(repo: impl Into<String>) -> Self {
        Self { repo: repo.into() }
    }
}

// ── 中间 API 响应类型 ──────────────────────────────────────────────

/// `glab mr note --output json` 返回的 JSON 结构(用于获取审查评论 ID)。
#[derive(Debug, Clone, Deserialize)]
struct NoteApiResponse {
    id: u64,
    #[serde(default)]
    body: String,
    #[serde(default)]
    author: Option<ApiUser>,
    #[serde(default)]
    created_at: Option<DateTime<Utc>>,
}

/// JSON 输出中的用户信息。
#[derive(Debug, Clone, Deserialize)]
struct ApiUser {
    username: String,
    #[serde(default)]
    id: u64,
}

impl From<&ApiUser> for UserSummary {
    fn from(u: &ApiUser) -> Self {
        Self {
            login: u.username.clone(),
            id: u.id.to_string(),
        }
    }
}

/// `glab mr view --output json` 返回的 JSON 结构(用于获取当前用户信息)。
#[derive(Debug, Clone, Deserialize)]
struct MrViewResponse {
    #[serde(default)]
    author: Option<ApiUser>,
}

// ── trait 实现 ──────────────────────────────────────────────────────

#[async_trait]
impl ReviewProvider for GitLabReviewProvider {
    /// 在指定 MR 上添加审查评论。
    ///
    /// 调用 `glab mr note` 发布评论,并通过 `glab mr view` 获取当前用户信息
    /// 以构造 [`ReviewData`]。
    async fn comment(&self, pr_number: u64, body: &str) -> Result<ReviewData> {
        debug!(repo = %self.repo, number = pr_number, "spawning `glab mr note`");

        let output = tokio::process::Command::new("glab")
            .args(["mr", "note"])
            .arg(pr_number.to_string())
            .arg("--repo")
            .arg(&self.repo)
            .arg("--body")
            .arg(body)
            .arg("--output")
            .arg("json")
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab: {e}")))?;

        if !output.status.success() {
            return Err(parse_glab_error(&output.stderr).into());
        }

        let note: NoteApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        let author = note.author.as_ref().map_or_else(
            || UserSummary {
                login: "unknown".into(),
                id: "0".to_string(),
            },
            UserSummary::from,
        );

        Ok(ReviewData {
            id: note.id,
            state: ReviewState::Commented,
            body: Some(note.body),
            author,
            submitted_at: note.created_at.unwrap_or_else(Utc::now),
        })
    }

    /// 批准指定 MR。
    ///
    /// 调用 `glab mr approve` 批准 MR,然后构造 [`ReviewData`]。
    async fn approve(&self, pr_number: u64, body: Option<&str>) -> Result<ReviewData> {
        debug!(repo = %self.repo, number = pr_number, "spawning `glab mr approve`");

        let mut cmd = tokio::process::Command::new("glab");
        cmd.args(["mr", "approve"])
            .arg(pr_number.to_string())
            .arg("--repo")
            .arg(&self.repo);

        if let Some(b) = body {
            cmd.arg("--comment").arg(b);
        }

        let output = cmd
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab: {e}")))?;

        if !output.status.success() {
            return Err(parse_glab_error(&output.stderr).into());
        }

        let message = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let author = self.get_current_user().await.unwrap_or(UserSummary {
            login: "unknown".into(),
            id: "0".to_string(),
        });

        Ok(ReviewData {
            id: 0,
            state: ReviewState::Approved,
            body: if message.is_empty() {
                body.map(String::from)
            } else {
                Some(message)
            },
            author,
            submitted_at: Utc::now(),
        })
    }

    /// 对指定 MR 要求修改。
    ///
    /// glab 没有直接的 "request changes" 命令,通过 `glab mr note` 发布
    /// 包含要求修改意见的评论,并标记为 `ChangesRequested` 状态。
    async fn request_changes(&self, pr_number: u64, body: &str) -> Result<ReviewData> {
        debug!(
            repo = %self.repo,
            number = pr_number,
            "spawning `glab mr note` (request changes)"
        );

        let changes_body = format!("Changes requested:\n\n{body}");

        let output = tokio::process::Command::new("glab")
            .args(["mr", "note"])
            .arg(pr_number.to_string())
            .arg("--repo")
            .arg(&self.repo)
            .arg("--body")
            .arg(&changes_body)
            .arg("--output")
            .arg("json")
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab: {e}")))?;

        if !output.status.success() {
            return Err(parse_glab_error(&output.stderr).into());
        }

        let note: NoteApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        let author = note.author.as_ref().map_or_else(
            || UserSummary {
                login: "unknown".into(),
                id: "0".to_string(),
            },
            UserSummary::from,
        );

        Ok(ReviewData {
            id: note.id,
            state: ReviewState::ChangesRequested,
            body: Some(note.body),
            author,
            submitted_at: note.created_at.unwrap_or_else(Utc::now),
        })
    }

    /// 提交指定 MR 的审查。
    ///
    /// 根据 `event` 参数分别调用 `glab mr approve`、`glab mr revoke` 或
    /// `glab mr note` 实现不同的审查操作。
    async fn submit_review(
        &self,
        pr_number: u64,
        event: ReviewState,
        body: Option<&str>,
    ) -> Result<ReviewData> {
        debug!(repo = %self.repo, number = pr_number, ?event, "spawning `glab mr review`");

        match event {
            ReviewState::Approved => self.approve(pr_number, body).await,
            ReviewState::ChangesRequested => {
                self.request_changes(pr_number, body.unwrap_or("Changes requested."))
                    .await
            }
            ReviewState::Commented => {
                self.comment(pr_number, body.unwrap_or("Review comment."))
                    .await
            }
        }
    }
}

impl GitLabReviewProvider {
    /// 获取当前登录用户信息(内部辅助方法)。
    async fn get_current_user(&self) -> Result<UserSummary> {
        let output = tokio::process::Command::new("glab")
            .args(["mr", "list"])
            .arg("--repo")
            .arg(&self.repo)
            .arg("--output")
            .arg("json")
            .arg("--per-page")
            .arg("1")
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab: {e}")))?;

        if !output.status.success() {
            return Ok(UserSummary {
                login: "unknown".into(),
                id: "0".to_string(),
            });
        }

        let mrs: Vec<MrViewResponse> =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        if let Some(mr) = mrs.into_iter().next()
            && let Some(author) = mr.author
        {
            return Ok(UserSummary::from(&author));
        }

        Ok(UserSummary {
            login: "unknown".into(),
            id: "0".to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_should_construct_gitlab_review_provider() {
        let provider = GitLabReviewProvider::new("gitlab-org/gitlab");
        assert_eq!(provider.repo, "gitlab-org/gitlab");
    }

    #[test]
    fn test_should_construct_gitlab_review_provider_from_string() {
        let repo = String::from("gitlab-org/gitlab");
        let provider = GitLabReviewProvider::new(repo);
        assert_eq!(provider.repo, "gitlab-org/gitlab");
    }

    #[test]
    fn test_should_deserialize_note_api_response() {
        let json = br#"{
            "id": 2001,
            "body": "Looks great, LGTM!",
            "author": {"username": "reviewer", "id": 42},
            "created_at": "2026-05-20T14:30:00Z"
        }"#;

        let note: NoteApiResponse = serde_json::from_slice(json).expect("valid NoteApiResponse");
        assert_eq!(note.id, 2001);
        assert_eq!(note.body, "Looks great, LGTM!");
        assert_eq!(note.author.as_ref().map(|a| &*a.username), Some("reviewer"));
    }

    #[test]
    fn test_should_deserialize_note_without_author() {
        let json = br#"{
            "id": 2002,
            "body": "Anonymous comment",
            "author": null,
            "created_at": "2026-05-21T09:00:00Z"
        }"#;

        let note: NoteApiResponse = serde_json::from_slice(json).expect("valid NoteApiResponse");
        assert!(note.author.is_none());
    }

    #[test]
    fn test_should_convert_note_to_review_data() {
        let note = NoteApiResponse {
            id: 100,
            body: "LGTM".into(),
            author: Some(ApiUser {
                username: "reviewer".into(),
                id: 5,
            }),
            created_at: Some("2026-01-01T00:00:00Z".parse().expect("valid date")),
        };

        let author = note
            .author
            .as_ref()
            .map(UserSummary::from)
            .expect("has author");
        let review = ReviewData {
            id: note.id,
            state: ReviewState::Commented,
            body: Some(note.body),
            author,
            submitted_at: note.created_at.expect("has date"),
        };

        assert_eq!(review.id, 100);
        assert_eq!(review.state, ReviewState::Commented);
        assert_eq!(review.author.login, "reviewer");
    }

    #[test]
    fn test_should_debug_format_provider() {
        let provider = GitLabReviewProvider::new("gitlab-org/gitlab");
        let debug = format!("{provider:?}");
        assert!(debug.contains("GitLabReviewProvider"));
        assert!(debug.contains("gitlab-org/gitlab"));
    }

    #[test]
    fn test_should_clone_gitlab_review_provider() {
        let original = GitLabReviewProvider::new("owner/repo");
        let cloned = original.clone();
        assert_eq!(original.repo, cloned.repo);
    }

    #[test]
    fn test_should_deserialize_mr_view_response() {
        let json = br#"{
            "author": {"username": "maintainer", "id": 99}
        }"#;

        let mr: MrViewResponse = serde_json::from_slice(json).expect("valid MrViewResponse");
        assert!(mr.author.is_some());
        let author = mr.author.as_ref().expect("author present");
        assert_eq!(author.username, "maintainer");
        assert_eq!(author.id, 99);
    }

    #[test]
    fn test_should_deserialize_mr_view_response_without_author() {
        let json = br#"{"author": null}"#;

        let mr: MrViewResponse = serde_json::from_slice(json).expect("valid MrViewResponse");
        assert!(mr.author.is_none());
    }

    #[test]
    fn test_should_deserialize_note_without_created_at() {
        let json = br#"{
            "id": 3001,
            "body": "No timestamp",
            "author": null,
            "created_at": null
        }"#;

        let note: NoteApiResponse = serde_json::from_slice(json).expect("valid NoteApiResponse");
        assert!(note.created_at.is_none());
        assert!(note.author.is_none());
    }

    #[test]
    fn test_should_convert_api_user_to_user_summary() {
        let user = ApiUser {
            username: "reviewer".into(),
            id: 42,
        };
        let summary: UserSummary = (&user).into();
        assert_eq!(summary.login, "reviewer");
        assert_eq!(summary.id, "42");
    }

    #[test]
    fn test_should_convert_api_user_with_zero_id_to_user_summary() {
        let user = ApiUser {
            username: "bot".into(),
            id: 0,
        };
        let summary: UserSummary = (&user).into();
        assert_eq!(summary.login, "bot");
        assert_eq!(summary.id, "0");
    }
}