Skip to main content

gitflow_gitcode/
commit.rs

1//! GitCode Commit 提供者实现。
2//!
3//! 通过 `gc api` CLI 命令实现 [`CommitProvider`] trait,
4//! 支持 Commit 查看、Diff/Patch 获取及评论功能。
5
6use async_trait::async_trait;
7use gitflow_core::{
8    CoreError, Result,
9    commit::{CommitDetail, CommitFile, CommitProvider},
10    types::UserSummary,
11};
12use serde::Deserialize;
13use tracing::debug;
14
15use crate::error::parse_gitcode_error;
16
17/// GitCode Commit 提供者,通过 `gc api` 查看提交信息。
18///
19/// # Examples
20///
21/// ```no_run
22/// use gitflow_gitcode::GitCodeCommitProvider;
23///
24/// let provider = GitCodeCommitProvider::new("octocat/hello-world");
25/// ```
26#[derive(Debug, Clone)]
27pub struct GitCodeCommitProvider {
28    /// GitCode `owner/repo`。
29    repo: String,
30}
31
32impl GitCodeCommitProvider {
33    /// 创建新的 GitCode Commit 提供者。
34    ///
35    /// `repo` 格式为 `owner/repo`。
36    #[must_use]
37    pub fn new(repo: impl Into<String>) -> Self {
38        Self { repo: repo.into() }
39    }
40}
41
42/// `gc api repos/<repo>/commits/<sha>` 返回的 JSON 结构。
43#[derive(Debug, Clone, Deserialize)]
44#[serde(rename_all = "camelCase")]
45#[allow(
46    dead_code,
47    reason = "Fields are deserialized but not all used directly"
48)]
49struct CommitApiResponse {
50    sha: String,
51    commit: CommitInner,
52    author: Option<ApiUser>,
53    committer: Option<ApiUser>,
54    #[serde(default)]
55    stats: Option<CommitStats>,
56    #[serde(default)]
57    files: Vec<CommitFileResponse>,
58}
59
60#[derive(Debug, Clone, Deserialize)]
61#[serde(rename_all = "camelCase")]
62#[allow(
63    dead_code,
64    reason = "Fields are deserialized but not all used directly"
65)]
66struct CommitInner {
67    message: String,
68    author: Option<CommitAuthorInner>,
69    committer: Option<CommitAuthorInner>,
70}
71
72#[derive(Debug, Clone, Deserialize)]
73#[serde(rename_all = "camelCase")]
74#[allow(
75    dead_code,
76    reason = "Fields are deserialized but not all used directly"
77)]
78struct CommitAuthorInner {
79    #[serde(default)]
80    date: Option<String>,
81}
82
83#[derive(Debug, Clone, Deserialize)]
84#[serde(rename_all = "camelCase")]
85#[allow(
86    dead_code,
87    reason = "Fields are deserialized but not all used directly"
88)]
89struct CommitStats {
90    #[serde(default)]
91    additions: u64,
92    #[serde(default)]
93    deletions: u64,
94    #[serde(default)]
95    total: u64,
96}
97
98#[derive(Debug, Clone, Deserialize)]
99#[serde(rename_all = "camelCase")]
100struct CommitFileResponse {
101    filename: String,
102    #[serde(default)]
103    additions: u64,
104    #[serde(default)]
105    deletions: u64,
106    #[serde(default)]
107    status: String,
108}
109
110/// GitCode API 返回的用户信息。
111#[derive(Debug, Clone, Deserialize)]
112#[serde(rename_all = "camelCase")]
113struct ApiUser {
114    login: String,
115    id: u64,
116}
117
118impl From<&ApiUser> for UserSummary {
119    fn from(u: &ApiUser) -> Self {
120        Self {
121            login: u.login.clone(),
122            id: u.id.to_string(),
123        }
124    }
125}
126
127/// 将 API 响应转换为 `CommitDetail`。
128impl From<CommitApiResponse> for CommitDetail {
129    fn from(api: CommitApiResponse) -> Self {
130        let author = api.author.as_ref().map_or_else(
131            || fallback_user(api.commit.author.as_ref()),
132            UserSummary::from,
133        );
134        let committer = api.committer.as_ref().map_or_else(
135            || fallback_user(api.commit.committer.as_ref()),
136            UserSummary::from,
137        );
138
139        let files: Vec<CommitFile> = api
140            .files
141            .into_iter()
142            .map(|f| CommitFile {
143                filename: f.filename,
144                additions: f.additions,
145                deletions: f.deletions,
146                status: f.status,
147            })
148            .collect();
149
150        Self {
151            sha: api.sha,
152            message: api.commit.message,
153            author,
154            committer,
155            diff: None,
156            files,
157        }
158    }
159}
160
161/// 为 `CommitDetail` 构造后备用户(当 API 未返回用户信息时)。
162fn fallback_user(_inner: Option<&CommitAuthorInner>) -> UserSummary {
163    UserSummary {
164        login: "unknown".into(),
165        id: "0".to_string(),
166    }
167}
168
169#[async_trait]
170impl CommitProvider for GitCodeCommitProvider {
171    async fn view(&self, sha: &str) -> Result<CommitDetail> {
172        debug!(repo = %self.repo, sha, "spawning `gc api commit view`");
173
174        let api_path = format!("repos/{repo}/commits/{sha}", repo = self.repo);
175
176        let output = tokio::process::Command::new(crate::gitcode_binary())
177            .args(["api", &api_path])
178            .output()
179            .await
180            .map_err(|e| {
181                CoreError::Platform(format!("Failed to spawn gitcode api commit view: {e}"))
182            })?;
183
184        if !output.status.success() {
185            return Err(parse_gitcode_error(&output.stderr).into());
186        }
187
188        let api_response: CommitApiResponse =
189            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
190
191        Ok(api_response.into())
192    }
193
194    async fn diff(&self, sha: &str) -> Result<String> {
195        debug!(repo = %self.repo, sha, "spawning `gc commit diff`");
196
197        let output = tokio::process::Command::new(crate::gitcode_binary())
198            .args(["commit", "diff"])
199            .arg(sha)
200            .arg("-R")
201            .arg(&self.repo)
202            .output()
203            .await
204            .map_err(|e| {
205                CoreError::Platform(format!("Failed to spawn gitcode commit diff: {e}"))
206            })?;
207
208        if !output.status.success() {
209            return Err(parse_gitcode_error(&output.stderr).into());
210        }
211
212        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
213    }
214
215    async fn patch(&self, sha: &str) -> Result<String> {
216        debug!(repo = %self.repo, sha, "spawning `gc commit patch`");
217
218        let output = tokio::process::Command::new(crate::gitcode_binary())
219            .args(["commit", "patch"])
220            .arg(sha)
221            .arg("-R")
222            .arg(&self.repo)
223            .output()
224            .await
225            .map_err(|e| {
226                CoreError::Platform(format!("Failed to spawn gitcode commit patch: {e}"))
227            })?;
228
229        if !output.status.success() {
230            return Err(parse_gitcode_error(&output.stderr).into());
231        }
232
233        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
234    }
235
236    async fn comment(&self, sha: &str, body: &str, path: &str, line: u64) -> Result<()> {
237        debug!(repo = %self.repo, sha, "spawning `gc api commit comment`");
238
239        let api_path = format!("repos/{repo}/commits/{sha}/comments", repo = self.repo);
240
241        let mut cmd = tokio::process::Command::new(crate::gitcode_binary());
242        cmd.args(["api", &api_path, "-X", "POST"])
243            .arg("-f")
244            .arg(format!("body={body}"))
245            .arg("-f")
246            .arg(format!("path={path}"))
247            .arg("-f")
248            .arg(format!("line={line}"))
249            .arg("-f")
250            .arg("position=1");
251
252        let output = cmd.output().await.map_err(|e| {
253            CoreError::Platform(format!("Failed to spawn gitcode api commit comment: {e}"))
254        })?;
255
256        if !output.status.success() {
257            return Err(parse_gitcode_error(&output.stderr).into());
258        }
259
260        Ok(())
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    // --- GitCodeCommitProvider tests ---
269
270    #[test]
271    fn test_should_construct_gitcode_commit_provider() {
272        let provider = GitCodeCommitProvider::new("octocat/hello-world");
273        assert_eq!(provider.repo, "octocat/hello-world");
274    }
275
276    #[test]
277    fn test_should_construct_gitcode_commit_provider_from_string() {
278        let repo = String::from("octocat/hello-world");
279        let provider = GitCodeCommitProvider::new(repo);
280        assert_eq!(provider.repo, "octocat/hello-world");
281    }
282
283    #[test]
284    fn test_should_debug_format_commit_provider() {
285        let provider = GitCodeCommitProvider::new("owner/repo");
286        let debug = format!("{provider:?}");
287        assert!(debug.contains("GitCodeCommitProvider"));
288        assert!(debug.contains("owner/repo"));
289    }
290
291    #[test]
292    fn test_should_clone_gitcode_commit_provider() {
293        let original = GitCodeCommitProvider::new("owner/repo");
294        let cloned = original.clone();
295        assert_eq!(original.repo, cloned.repo);
296    }
297
298    // --- API response deserialization tests ---
299
300    #[test]
301    fn test_should_deserialize_commit_api_response() {
302        let json = br#"{
303            "sha": "abc123def456",
304            "commit": {
305                "message": "Fix login bug\n\nMore details here.",
306                "author": {"date": "2026-01-15T09:30:00Z"},
307                "committer": {"date": "2026-01-15T09:30:00Z"}
308            },
309            "author": {"login": "alice", "id": 7},
310            "committer": {"login": "bob", "id": 12},
311            "stats": {"additions": 15, "deletions": 3, "total": 18},
312            "files": [
313                {"filename": "auth.rs", "additions": 10, "deletions": 0, "status": "modified"},
314                {"filename": "tests/auth.rs", "additions": 5, "deletions": 3, "status": "modified"}
315            ]
316        }"#;
317
318        let api: CommitApiResponse = serde_json::from_slice(json).expect("valid CommitApiResponse");
319        assert_eq!(api.sha, "abc123def456");
320        assert!(api.commit.message.contains("Fix login bug"));
321        assert_eq!(api.author.as_ref().map(|u| &*u.login), Some("alice"));
322        assert_eq!(api.files.len(), 2);
323        assert_eq!(api.files[0].filename, "auth.rs");
324        assert_eq!(api.stats.as_ref().map(|s| s.additions), Some(15));
325    }
326
327    #[test]
328    fn test_should_deserialize_commit_detail_from_api() {
329        let json = br#"{
330            "sha": "deadbeef",
331            "commit": {
332                "message": "Add feature",
333                "author": null,
334                "committer": null
335            },
336            "author": null,
337            "committer": null,
338            "stats": null,
339            "files": []
340        }"#;
341
342        let api: CommitApiResponse = serde_json::from_slice(json).expect("valid CommitApiResponse");
343        let detail: CommitDetail = api.into();
344
345        assert_eq!(detail.sha, "deadbeef");
346        assert_eq!(detail.message, "Add feature");
347        assert_eq!(detail.author.login, "unknown");
348        assert!(detail.diff.is_none());
349        assert!(detail.files.is_empty());
350    }
351
352    #[test]
353    fn test_should_deserialize_commit_file_response() {
354        let json = br#"{"filename":"src/main.rs","additions":5,"deletions":2,"status":"modified"}"#;
355
356        let file: CommitFileResponse =
357            serde_json::from_slice(json).expect("valid CommitFileResponse");
358        assert_eq!(file.filename, "src/main.rs");
359        assert_eq!(file.additions, 5);
360        assert_eq!(file.deletions, 2);
361        assert_eq!(file.status, "modified");
362    }
363
364    #[test]
365    fn test_should_deserialize_api_user() {
366        let json = br#"{"login":"octocat","id":583231}"#;
367        let user: ApiUser = serde_json::from_slice(json).expect("valid ApiUser");
368        assert_eq!(user.login, "octocat");
369        assert_eq!(user.id, 583_231);
370    }
371
372    #[test]
373    fn test_should_convert_api_user_to_user_summary() {
374        let user = ApiUser {
375            login: "alice".into(),
376            id: 42,
377        };
378        let summary: UserSummary = (&user).into();
379        assert_eq!(summary.login, "alice");
380        assert_eq!(summary.id, "42");
381    }
382
383    #[test]
384    fn test_should_convert_commit_api_to_detail() {
385        let api = CommitApiResponse {
386            sha: "sha123".into(),
387            commit: CommitInner {
388                message: "Test commit".into(),
389                author: None,
390                committer: None,
391            },
392            author: Some(ApiUser {
393                login: "dev".into(),
394                id: 1,
395            }),
396            committer: Some(ApiUser {
397                login: "dev".into(),
398                id: 1,
399            }),
400            stats: Some(CommitStats {
401                additions: 10,
402                deletions: 2,
403                total: 12,
404            }),
405            files: vec![CommitFileResponse {
406                filename: "lib.rs".into(),
407                additions: 10,
408                deletions: 2,
409                status: "modified".into(),
410            }],
411        };
412
413        let detail: CommitDetail = api.into();
414        assert_eq!(detail.sha, "sha123");
415        assert_eq!(detail.message, "Test commit");
416        assert_eq!(detail.author.login, "dev");
417        assert_eq!(detail.files.len(), 1);
418        assert_eq!(detail.files[0].filename, "lib.rs");
419    }
420
421    #[test]
422    fn test_should_fallback_user_when_api_returns_no_user_info() {
423        let summary = fallback_user(None);
424        assert_eq!(summary.login, "unknown");
425        assert_eq!(summary.id, "0");
426    }
427
428    #[test]
429    fn test_should_convert_commit_api_to_detail_with_mixed_author_committer() {
430        // author present, committer absent -> committer should fallback to unknown
431        let api = CommitApiResponse {
432            sha: "sha_mixed".into(),
433            commit: CommitInner {
434                message: "Mixed authors".into(),
435                author: None,
436                committer: None,
437            },
438            author: Some(ApiUser {
439                login: "author_only".into(),
440                id: 10,
441            }),
442            committer: None,
443            stats: None,
444            files: vec![],
445        };
446
447        let detail: CommitDetail = api.into();
448        assert_eq!(detail.author.login, "author_only");
449        assert_eq!(detail.committer.login, "unknown");
450
451        // committer present, author absent -> author should fallback to unknown
452        let api2 = CommitApiResponse {
453            sha: "sha_mixed2".into(),
454            commit: CommitInner {
455                message: "Mixed authors 2".into(),
456                author: None,
457                committer: None,
458            },
459            author: None,
460            committer: Some(ApiUser {
461                login: "committer_only".into(),
462                id: 20,
463            }),
464            stats: None,
465            files: vec![],
466        };
467
468        let detail2: CommitDetail = api2.into();
469        assert_eq!(detail2.author.login, "unknown");
470        assert_eq!(detail2.committer.login, "committer_only");
471    }
472}