Skip to main content

gitflow_gitlab/
commit.rs

1//! GitLab Commit 提供者实现。
2//!
3//! 通过 `glab api` CLI 命令实现 [`CommitProvider`] trait,
4//! 支持 Commit 查看、Diff/Patch 获取及评论功能。
5//!
6//! GitLab API 路径与 GitHub 不同:
7//! - `projects/:id/repository/commits/:sha` — 查看提交
8//! - `projects/:id/repository/commits/:sha/diff` — 获取 diff
9//! - `projects/:id/repository/commits/:sha` + Accept header — 获取 patch
10//! - `projects/:id/repository/commits/:sha/comments` — 评论
11
12use async_trait::async_trait;
13use chrono::{DateTime, Utc};
14use gitflow_core::{
15    CoreError, Result,
16    commit::{CommitDetail, CommitProvider},
17    types::UserSummary,
18};
19use serde::Deserialize;
20use tracing::debug;
21
22use crate::error::parse_glab_error;
23
24/// GitLab Commit 提供者,通过 `glab api` 查看提交信息。
25///
26/// # Examples
27///
28/// ```no_run
29/// use gitflow_gitlab::GitLabCommitProvider;
30///
31/// let provider = GitLabCommitProvider::new("gitlab-org/gitlab");
32/// ```
33#[derive(Debug, Clone)]
34pub struct GitLabCommitProvider {
35    /// GitLab `namespace/project`。
36    repo: String,
37}
38
39impl GitLabCommitProvider {
40    /// 创建新的 GitLab Commit 提供者。
41    ///
42    /// `repo` 格式为 `namespace/project`。
43    #[must_use]
44    pub fn new(repo: impl Into<String>) -> Self {
45        Self { repo: repo.into() }
46    }
47}
48
49// ── 中间 API 响应类型 ──────────────────────────────────────────────
50
51/// GitLab API 返回的提交结构。
52#[derive(Debug, Clone, Deserialize)]
53#[serde(rename_all = "snake_case")]
54#[allow(
55    dead_code,
56    reason = "Used for deserialization; not all fields are read"
57)]
58struct CommitApiResponse {
59    id: String,
60    #[serde(default)]
61    short_id: String,
62    title: String,
63    #[serde(default)]
64    message: String,
65    #[serde(default)]
66    author_name: String,
67    #[serde(default)]
68    author_email: String,
69    #[serde(default)]
70    authored_date: Option<String>,
71    #[serde(default)]
72    committer_name: String,
73    #[serde(default)]
74    committer_email: String,
75    #[serde(default)]
76    committed_date: Option<String>,
77    #[serde(default)]
78    stats: Option<CommitStats>,
79    #[serde(default)]
80    parent_ids: Vec<String>,
81}
82
83#[derive(Debug, Clone, Deserialize)]
84#[serde(rename_all = "snake_case")]
85#[allow(
86    dead_code,
87    reason = "Used for deserialization; not all fields are read"
88)]
89struct CommitStats {
90    #[serde(default)]
91    additions: u64,
92    #[serde(default)]
93    deletions: u64,
94    #[serde(default)]
95    total: u64,
96}
97
98/// GitLab diff 条目。
99#[derive(Debug, Clone, Deserialize)]
100#[serde(rename_all = "snake_case")]
101#[allow(
102    dead_code,
103    reason = "Used for deserialization; not all fields are read"
104)]
105struct DiffResponse {
106    #[serde(default)]
107    old_path: String,
108    #[serde(default)]
109    new_path: String,
110    #[serde(default)]
111    diff: String,
112    #[serde(default)]
113    new_file: bool,
114    #[serde(default)]
115    renamed_file: bool,
116    #[serde(default)]
117    deleted_file: bool,
118}
119
120/// GitLab commit comment 结构。
121#[derive(Debug, Clone, Deserialize)]
122#[serde(rename_all = "snake_case")]
123#[allow(
124    dead_code,
125    reason = "Used for deserialization; not all fields are read"
126)]
127struct CommentApiResponse {
128    #[serde(default)]
129    note: String,
130    #[serde(default)]
131    author: Option<ApiUser>,
132    #[serde(default)]
133    created_at: Option<DateTime<Utc>>,
134}
135
136/// GitLab API 返回的用户信息。
137#[derive(Debug, Clone, Deserialize)]
138#[serde(rename_all = "snake_case")]
139struct ApiUser {
140    username: String,
141    #[serde(default)]
142    id: u64,
143}
144
145impl From<&ApiUser> for UserSummary {
146    fn from(u: &ApiUser) -> Self {
147        Self {
148            login: u.username.clone(),
149            id: u.id.to_string(),
150        }
151    }
152}
153
154/// 将 GitLab API 响应转换为 `CommitDetail`。
155impl From<CommitApiResponse> for CommitDetail {
156    fn from(api: CommitApiResponse) -> Self {
157        let author = UserSummary {
158            login: if api.author_name.is_empty() {
159                "unknown".into()
160            } else {
161                api.author_name.clone()
162            },
163            id: "0".to_string(),
164        };
165        let committer = UserSummary {
166            login: if api.committer_name.is_empty() {
167                "unknown".into()
168            } else {
169                api.committer_name.clone()
170            },
171            id: "0".to_string(),
172        };
173
174        Self {
175            sha: api.id,
176            message: api.message,
177            author,
178            committer,
179            diff: None,
180            files: vec![],
181        }
182    }
183}
184
185// ── 辅助函数 ──────────────────────────────────────────────────────
186
187/// 将 `namespace/project` 转换为 URL 编码的项目路径。
188///
189/// GitLab API 需要 URL 编码的项目路径(如 `namespace%2Fproject`)。
190fn encode_project_path(repo: &str) -> String {
191    repo.replace('/', "%2F")
192}
193
194/// 从 diff 条目推断文件状态。
195#[allow(
196    dead_code,
197    reason = "Used in tests; reserved for future diff formatting"
198)]
199fn diff_status(diff: &DiffResponse) -> String {
200    if diff.new_file {
201        "added".into()
202    } else if diff.deleted_file {
203        "removed".into()
204    } else if diff.renamed_file {
205        "renamed".into()
206    } else {
207        "modified".into()
208    }
209}
210
211// ── trait 实现 ──────────────────────────────────────────────────────
212
213#[async_trait]
214impl CommitProvider for GitLabCommitProvider {
215    async fn view(&self, sha: &str) -> Result<CommitDetail> {
216        debug!(repo = %self.repo, sha, "spawning `glab api commit view`");
217
218        let encoded_path = encode_project_path(&self.repo);
219        let api_path = format!("projects/{encoded_path}/repository/commits/{sha}");
220
221        let output = tokio::process::Command::new("glab")
222            .args(["api", &api_path])
223            .output()
224            .await
225            .map_err(|e| {
226                CoreError::Platform(format!("Failed to spawn glab api commit view: {e}"))
227            })?;
228
229        if !output.status.success() {
230            return Err(parse_glab_error(&output.stderr).into());
231        }
232
233        let api_response: CommitApiResponse =
234            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
235
236        Ok(api_response.into())
237    }
238
239    async fn diff(&self, sha: &str) -> Result<String> {
240        debug!(repo = %self.repo, sha, "spawning `glab api commit diff`");
241
242        let encoded_path = encode_project_path(&self.repo);
243        let api_path = format!("projects/{encoded_path}/repository/commits/{sha}/diff");
244
245        let output = tokio::process::Command::new("glab")
246            .args(["api", &api_path])
247            .output()
248            .await
249            .map_err(|e| {
250                CoreError::Platform(format!("Failed to spawn glab api commit diff: {e}"))
251            })?;
252
253        if !output.status.success() {
254            return Err(parse_glab_error(&output.stderr).into());
255        }
256
257        // GitLab returns a JSON array of diff objects
258        let diffs: Vec<DiffResponse> =
259            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
260
261        let mut result = String::new();
262        for diff in &diffs {
263            use std::fmt::Write as _;
264            let _ = write!(
265                result,
266                "diff --git a/{} b/{}\n{}\n",
267                diff.old_path, diff.new_path, diff.diff
268            );
269        }
270
271        Ok(result)
272    }
273
274    async fn patch(&self, sha: &str) -> Result<String> {
275        debug!(repo = %self.repo, sha, "spawning `glab api commit patch`");
276
277        let encoded_path = encode_project_path(&self.repo);
278        let api_path = format!("projects/{encoded_path}/repository/commits/{sha}.patch");
279
280        let output = tokio::process::Command::new("glab")
281            .args(["api", &api_path])
282            .output()
283            .await
284            .map_err(|e| {
285                CoreError::Platform(format!("Failed to spawn glab api commit patch: {e}"))
286            })?;
287
288        if !output.status.success() {
289            return Err(parse_glab_error(&output.stderr).into());
290        }
291
292        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
293    }
294
295    async fn comment(&self, sha: &str, body: &str, path: &str, line: u64) -> Result<()> {
296        debug!(repo = %self.repo, sha, "spawning `glab api commit comment`");
297
298        let encoded_path = encode_project_path(&self.repo);
299        let api_path = format!("projects/{encoded_path}/repository/commits/{sha}/comments");
300
301        let full_note = format!("{body}\n\nFile: {path}, Line: {line}");
302
303        let output = tokio::process::Command::new("glab")
304            .args(["api", &api_path, "-X", "POST"])
305            .arg("-f")
306            .arg(format!("note={full_note}"))
307            .output()
308            .await
309            .map_err(|e| {
310                CoreError::Platform(format!("Failed to spawn glab api commit comment: {e}"))
311            })?;
312
313        if !output.status.success() {
314            return Err(parse_glab_error(&output.stderr).into());
315        }
316
317        Ok(())
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn test_should_construct_gitlab_commit_provider() {
327        let provider = GitLabCommitProvider::new("gitlab-org/gitlab");
328        assert_eq!(provider.repo, "gitlab-org/gitlab");
329    }
330
331    #[test]
332    fn test_should_construct_gitlab_commit_provider_from_string() {
333        let repo = String::from("gitlab-org/gitlab");
334        let provider = GitLabCommitProvider::new(repo);
335        assert_eq!(provider.repo, "gitlab-org/gitlab");
336    }
337
338    #[test]
339    fn test_should_debug_format_commit_provider() {
340        let provider = GitLabCommitProvider::new("owner/repo");
341        let debug = format!("{provider:?}");
342        assert!(debug.contains("GitLabCommitProvider"));
343        assert!(debug.contains("owner/repo"));
344    }
345
346    #[test]
347    fn test_should_clone_gitlab_commit_provider() {
348        let original = GitLabCommitProvider::new("owner/repo");
349        let cloned = original.clone();
350        assert_eq!(original.repo, cloned.repo);
351    }
352
353    // --- API response deserialization tests ---
354
355    #[test]
356    fn test_should_deserialize_commit_api_response() {
357        let json = br#"{
358            "id": "abc123def456",
359            "short_id": "abc123d",
360            "title": "Fix login bug",
361            "message": "Fix login bug\n\nMore details here.",
362            "author_name": "alice",
363            "author_email": "alice@example.com",
364            "authored_date": "2026-01-15T09:30:00Z",
365            "committer_name": "bob",
366            "committer_email": "bob@example.com",
367            "committed_date": "2026-01-15T09:30:00Z",
368            "parent_ids": ["parent1"]
369        }"#;
370
371        let api: CommitApiResponse = serde_json::from_slice(json).expect("valid CommitApiResponse");
372        assert_eq!(api.id, "abc123def456");
373        assert!(api.message.contains("Fix login bug"));
374        assert_eq!(api.author_name, "alice");
375        assert_eq!(api.committer_name, "bob");
376    }
377
378    #[test]
379    fn test_should_convert_commit_api_to_detail() {
380        let api = CommitApiResponse {
381            id: "sha123".into(),
382            short_id: "sha123".into(),
383            title: "Test commit".into(),
384            message: "Test commit".into(),
385            author_name: "dev".into(),
386            author_email: "dev@example.com".into(),
387            authored_date: Some("2026-01-01T00:00:00Z".into()),
388            committer_name: "dev".into(),
389            committer_email: "dev@example.com".into(),
390            committed_date: Some("2026-01-01T00:00:00Z".into()),
391            stats: None,
392            parent_ids: vec![],
393        };
394
395        let detail: CommitDetail = api.into();
396        assert_eq!(detail.sha, "sha123");
397        assert_eq!(detail.message, "Test commit");
398        assert_eq!(detail.author.login, "dev");
399        assert!(detail.diff.is_none());
400        assert!(detail.files.is_empty());
401    }
402
403    #[test]
404    fn test_should_handle_empty_author_name() {
405        let api = CommitApiResponse {
406            id: "sha456".into(),
407            short_id: "sha456".into(),
408            title: "Test".into(),
409            message: "Test".into(),
410            author_name: String::new(),
411            author_email: String::new(),
412            authored_date: None,
413            committer_name: String::new(),
414            committer_email: String::new(),
415            committed_date: None,
416            stats: None,
417            parent_ids: vec![],
418        };
419
420        let detail: CommitDetail = api.into();
421        assert_eq!(detail.author.login, "unknown");
422        assert_eq!(detail.committer.login, "unknown");
423    }
424
425    #[test]
426    fn test_should_deserialize_diff_response() {
427        let json = br#"{
428            "old_path": "src/main.rs",
429            "new_path": "src/main.rs",
430            "diff": "@@ -1,3 +1,4 @@\n-old line\n+new line",
431            "new_file": false,
432            "renamed_file": false,
433            "deleted_file": false
434        }"#;
435
436        let diff: DiffResponse = serde_json::from_slice(json).expect("valid DiffResponse");
437        assert_eq!(diff.old_path, "src/main.rs");
438        assert_eq!(diff.new_path, "src/main.rs");
439        assert!(!diff.new_file);
440        assert!(!diff.deleted_file);
441    }
442
443    #[test]
444    fn test_should_determine_diff_status() {
445        let new_file = DiffResponse {
446            old_path: String::new(),
447            new_path: "new.rs".into(),
448            diff: String::new(),
449            new_file: true,
450            renamed_file: false,
451            deleted_file: false,
452        };
453        assert_eq!(diff_status(&new_file), "added");
454
455        let deleted = DiffResponse {
456            old_path: "old.rs".into(),
457            new_path: String::new(),
458            diff: String::new(),
459            new_file: false,
460            renamed_file: false,
461            deleted_file: true,
462        };
463        assert_eq!(diff_status(&deleted), "removed");
464
465        let modified = DiffResponse {
466            old_path: "main.rs".into(),
467            new_path: "main.rs".into(),
468            diff: String::new(),
469            new_file: false,
470            renamed_file: false,
471            deleted_file: false,
472        };
473        assert_eq!(diff_status(&modified), "modified");
474    }
475
476    #[test]
477    fn test_should_encode_project_path() {
478        assert_eq!(
479            encode_project_path("gitlab-org/gitlab"),
480            "gitlab-org%2Fgitlab"
481        );
482        assert_eq!(
483            encode_project_path("group/subgroup/project"),
484            "group%2Fsubgroup%2Fproject"
485        );
486    }
487}