Skip to main content

gitflow_github/
commit.rs

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