Skip to main content

gitflow_core/
commit.rs

1//! Commit resource types with platform abstraction.
2//!
3//! Defines data types for representing commit summaries, detailed views
4//! with diffs and file-level changes, along with the [`CommitProvider`]
5//! trait for cross-platform implementations (GitHub, GitLab, `GitCode`, etc.).
6
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9
10use crate::{Result, types::UserSummary};
11
12/// A summary of a single commit.
13///
14/// Contains the essential metadata needed for commit listings and
15/// timeline views.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17#[serde(rename_all = "camelCase")]
18pub struct CommitData {
19    /// The full SHA hash of the commit.
20    pub sha: String,
21    /// The commit message (first line + body).
22    pub message: String,
23    /// The commit author (the person who wrote the code).
24    pub author: UserSummary,
25    /// The committer (the person who applied the commit).
26    pub committer: UserSummary,
27    /// The number of lines added in this commit.
28    pub additions: u64,
29    /// The number of lines deleted in this commit.
30    pub deletions: u64,
31    /// The number of files changed in this commit.
32    pub files_changed: u64,
33}
34
35/// A detailed view of a commit, including diff and per-file changes.
36///
37/// Returned by [`CommitProvider::view`] when the caller needs the full
38/// diff payload and file-level breakdown.
39#[derive(Debug, Clone, Serialize, Deserialize)]
40#[serde(rename_all = "camelCase")]
41pub struct CommitDetail {
42    /// The full SHA hash of the commit.
43    pub sha: String,
44    /// The commit message (first line + body).
45    pub message: String,
46    /// The commit author.
47    pub author: UserSummary,
48    /// The committer.
49    pub committer: UserSummary,
50    /// The full unified diff output (if available).
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub diff: Option<String>,
53    /// The list of changed files.
54    #[serde(default)]
55    pub files: Vec<CommitFile>,
56}
57
58/// A single file change within a commit.
59///
60/// Tracks the path, line counts, and status (added, modified, deleted, etc.)
61/// for each file touched by a commit.
62#[derive(Debug, Clone, Serialize, Deserialize)]
63#[serde(rename_all = "camelCase")]
64pub struct CommitFile {
65    /// The file path relative to the repository root.
66    pub filename: String,
67    /// The number of lines added in this file.
68    pub additions: u64,
69    /// The number of lines deleted in this file.
70    pub deletions: u64,
71    /// The file status (e.g. `"added"`, `"modified"`, `"deleted"`, `"renamed"`).
72    pub status: String,
73}
74
75/// Platform abstraction for commit inspection and commenting.
76///
77/// All platform implementations (GitHub/GitLab/GitCode) must implement
78/// this trait to provide unified commit viewing, diffing, patch retrieval,
79/// and commenting capabilities.
80///
81/// # Errors
82///
83/// All methods return [`CoreError`](crate::CoreError) on platform API
84/// failure, deserialization errors, or authentication failures.
85#[async_trait]
86pub trait CommitProvider: std::fmt::Debug + Send + Sync {
87    /// View the details of a commit by SHA.
88    ///
89    /// # Errors
90    ///
91    /// Returns an error if the commit does not exist or the platform API call fails.
92    async fn view(&self, sha: &str) -> Result<CommitDetail>;
93
94    /// Retrieve the unified diff for a commit by SHA.
95    ///
96    /// # Errors
97    ///
98    /// Returns an error if the commit does not exist or the platform API call fails.
99    async fn diff(&self, sha: &str) -> Result<String>;
100
101    /// Retrieve the raw patch content for a commit by SHA.
102    ///
103    /// # Errors
104    ///
105    /// Returns an error if the commit does not exist or the platform API call fails.
106    async fn patch(&self, sha: &str) -> Result<String>;
107
108    /// Comment on a specific file line within a commit.
109    ///
110    /// # Arguments
111    ///
112    /// * `sha` - The commit SHA to comment on.
113    /// * `body` - The comment body (Markdown).
114    /// * `path` - The file path within the commit.
115    /// * `line` - The line number to comment on (1-based).
116    ///
117    /// # Errors
118    ///
119    /// Returns an error if the commit or file does not exist, the line number
120    /// is out of range, or the platform API call fails.
121    async fn comment(&self, sha: &str, body: &str, path: &str, line: u64) -> Result<()>;
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    // --- CommitData tests ---
129
130    fn sample_commit_json() -> &'static str {
131        r#"{
132            "sha": "abc1234567890def",
133            "message": "Fix login redirect loop\n\nThe auth middleware was missing a redirect check.",
134            "author": {"login": "alice", "id": "7"},
135            "committer": {"login": "bob", "id": "12"},
136            "additions": 15,
137            "deletions": 3,
138            "filesChanged": 2
139        }"#
140    }
141
142    #[test]
143    fn test_should_deserialize_commit_data_from_camel_case_json() {
144        let json = sample_commit_json();
145        let commit: CommitData = serde_json::from_str(json).expect("valid CommitData");
146        assert_eq!(commit.sha, "abc1234567890def");
147        assert!(commit.message.contains("Fix login redirect loop"));
148        assert_eq!(commit.author.login, "alice");
149        assert_eq!(commit.committer.login, "bob");
150        assert_eq!(commit.additions, 15);
151        assert_eq!(commit.deletions, 3);
152        assert_eq!(commit.files_changed, 2);
153    }
154
155    #[test]
156    fn test_should_serialize_commit_data_to_camel_case_json() {
157        let json = sample_commit_json();
158        let commit: CommitData = serde_json::from_str(json).expect("deserialize");
159        let serialized = serde_json::to_string(&commit).expect("serialize");
160        assert!(serialized.contains("\"filesChanged\""));
161        assert!(serialized.contains("\"additions\""));
162        assert!(!serialized.contains("\"files_changed\""));
163    }
164
165    #[test]
166    fn test_should_roundtrip_commit_data_via_serde() {
167        let json = sample_commit_json();
168        let commit: CommitData = serde_json::from_str(json).expect("deserialize");
169        let re_serialized = serde_json::to_string(&commit).expect("serialize");
170        let round_tripped: CommitData =
171            serde_json::from_str(&re_serialized).expect("re-deserialize");
172        assert_eq!(round_tripped.sha, commit.sha);
173        assert_eq!(round_tripped.message, commit.message);
174        assert_eq!(round_tripped.author.login, commit.author.login);
175        assert_eq!(round_tripped.committer.login, commit.committer.login);
176        assert_eq!(round_tripped.additions, commit.additions);
177        assert_eq!(round_tripped.deletions, commit.deletions);
178        assert_eq!(round_tripped.files_changed, commit.files_changed);
179    }
180
181    #[test]
182    fn test_should_derive_debug_for_commit_data() {
183        let commit = CommitData {
184            sha: "abc".into(),
185            message: "test".into(),
186            author: UserSummary {
187                login: "u".into(),
188                id: "1".to_string(),
189            },
190            committer: UserSummary {
191                login: "u".into(),
192                id: "1".to_string(),
193            },
194            additions: 0,
195            deletions: 0,
196            files_changed: 0,
197        };
198        let debug = format!("{commit:?}");
199        assert!(debug.contains("CommitData"));
200        assert!(debug.contains("abc"));
201    }
202
203    // --- CommitDetail tests ---
204
205    fn sample_commit_detail_json() -> &'static str {
206        r#"{
207            "sha": "deadbeef1234",
208            "message": "Add unit tests for auth module",
209            "author": {"login": "tester", "id": "99"},
210            "committer": {"login": "tester", "id": "99"},
211            "diff": "--- a/auth.rs\n+++ b/auth.rs\n@@ -1,3 +1,5 @@\n+use chrono::Utc;\n",
212            "files": [
213                {"filename": "auth.rs", "additions": 10, "deletions": 0, "status": "modified"}
214            ]
215        }"#
216    }
217
218    #[test]
219    fn test_should_deserialize_commit_detail_from_camel_case_json() {
220        let json = sample_commit_detail_json();
221        let detail: CommitDetail = serde_json::from_str(json).expect("valid CommitDetail");
222        assert_eq!(detail.sha, "deadbeef1234");
223        assert_eq!(detail.message, "Add unit tests for auth module");
224        assert!(detail.diff.is_some());
225        assert_eq!(detail.files.len(), 1);
226        assert_eq!(detail.files[0].filename, "auth.rs");
227        assert_eq!(detail.files[0].additions, 10);
228        assert_eq!(detail.files[0].deletions, 0);
229        assert_eq!(detail.files[0].status, "modified");
230    }
231
232    #[test]
233    fn test_should_serialize_commit_detail_to_camel_case_json() {
234        let json = sample_commit_detail_json();
235        let detail: CommitDetail = serde_json::from_str(json).expect("deserialize");
236        let serialized = serde_json::to_string(&detail).expect("serialize");
237        assert!(serialized.contains("\"files\""));
238        assert!(serialized.contains("\"filename\""));
239        assert!(!serialized.contains("\"files\":[{\"filename\":null"));
240    }
241
242    #[test]
243    fn test_should_serialize_commit_detail_skips_null_diff() {
244        let detail = CommitDetail {
245            sha: "abc".into(),
246            message: "no diff".into(),
247            author: UserSummary {
248                login: "u".into(),
249                id: "1".to_string(),
250            },
251            committer: UserSummary {
252                login: "u".into(),
253                id: "1".to_string(),
254            },
255            diff: None,
256            files: vec![],
257        };
258        let json = serde_json::to_string(&detail).expect("serialize");
259        assert!(!json.contains("null"));
260        assert!(!json.contains("\"diff\":null"));
261    }
262
263    #[test]
264    fn test_should_roundtrip_commit_detail_via_serde() {
265        let json = sample_commit_detail_json();
266        let detail: CommitDetail = serde_json::from_str(json).expect("deserialize");
267        let re_serialized = serde_json::to_string(&detail).expect("serialize");
268        let round_tripped: CommitDetail =
269            serde_json::from_str(&re_serialized).expect("re-deserialize");
270        assert_eq!(round_tripped.sha, detail.sha);
271        assert_eq!(round_tripped.message, detail.message);
272        assert_eq!(round_tripped.diff, detail.diff);
273        assert_eq!(round_tripped.files.len(), detail.files.len());
274    }
275
276    #[test]
277    fn test_should_derive_debug_for_commit_detail() {
278        let detail = CommitDetail {
279            sha: "abc".into(),
280            message: "test".into(),
281            author: UserSummary {
282                login: "u".into(),
283                id: "1".to_string(),
284            },
285            committer: UserSummary {
286                login: "u".into(),
287                id: "1".to_string(),
288            },
289            diff: None,
290            files: vec![],
291        };
292        let debug = format!("{detail:?}");
293        assert!(debug.contains("CommitDetail"));
294        assert!(debug.contains("abc"));
295    }
296
297    // --- CommitFile tests ---
298
299    #[test]
300    fn test_should_deserialize_commit_file_from_camel_case_json() {
301        let json = r#"{"filename":"src/main.rs","additions":5,"deletions":2,"status":"modified"}"#;
302        let file: CommitFile = serde_json::from_str(json).expect("valid CommitFile");
303        assert_eq!(file.filename, "src/main.rs");
304        assert_eq!(file.additions, 5);
305        assert_eq!(file.deletions, 2);
306        assert_eq!(file.status, "modified");
307    }
308
309    #[test]
310    fn test_should_serialize_commit_file_to_camel_case_json() {
311        let file = CommitFile {
312            filename: "Cargo.toml".into(),
313            additions: 1,
314            deletions: 0,
315            status: "modified".into(),
316        };
317        let json = serde_json::to_string(&file).expect("serialize CommitFile");
318        assert!(json.contains("\"filename\":\"Cargo.toml\""));
319        assert!(json.contains("\"additions\":1"));
320        assert!(json.contains("\"deletions\":0"));
321        assert!(json.contains("\"status\":\"modified\""));
322    }
323
324    #[test]
325    fn test_should_roundtrip_commit_file_via_serde() {
326        let file = CommitFile {
327            filename: "README.md".into(),
328            additions: 20,
329            deletions: 5,
330            status: "added".into(),
331        };
332        let json = serde_json::to_string(&file).expect("serialize");
333        let round_tripped: CommitFile = serde_json::from_str(&json).expect("deserialize");
334        assert_eq!(round_tripped.filename, file.filename);
335        assert_eq!(round_tripped.additions, file.additions);
336        assert_eq!(round_tripped.deletions, file.deletions);
337        assert_eq!(round_tripped.status, file.status);
338    }
339
340    #[test]
341    fn test_should_derive_debug_for_commit_file() {
342        let file = CommitFile {
343            filename: "test.rs".into(),
344            additions: 0,
345            deletions: 0,
346            status: "added".into(),
347        };
348        let debug = format!("{file:?}");
349        assert!(debug.contains("CommitFile"));
350        assert!(debug.contains("test.rs"));
351    }
352}