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