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