Skip to main content

git_editor/utils/
commit_history.rs

1use crate::utils::types::Result;
2use crate::{args::Args, utils::types::CommitInfo};
3use colored::Colorize;
4use git2::{Repository, Sort};
5
6fn naive_utc(seconds: i64) -> chrono::NaiveDateTime {
7    chrono::DateTime::from_timestamp(seconds, 0)
8        .unwrap_or_default()
9        .naive_utc()
10}
11
12pub fn get_commit_history(args: &Args, print: bool) -> Result<Vec<CommitInfo>> {
13    let repo = Repository::open(args.repo_path.as_ref().unwrap())?;
14
15    // An unborn branch (fresh `git init`) simply has no history.
16    match repo.head() {
17        Ok(_) => {}
18        Err(e)
19            if matches!(
20                e.code(),
21                git2::ErrorCode::UnbornBranch | git2::ErrorCode::NotFound
22            ) =>
23        {
24            return Ok(Vec::new())
25        }
26        Err(e) => return Err(e.into()),
27    }
28
29    let mut revwalk = repo.revwalk()?;
30    revwalk.push_head()?;
31    revwalk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)?;
32
33    // Collect all commits first
34    let mut commits = Vec::new();
35    let mut commit_infos = Vec::new();
36
37    for oid_result in revwalk {
38        let oid = oid_result?;
39        let commit = repo.find_commit(oid)?;
40        let commit_info = {
41            let author = commit.author();
42            let committer = commit.committer();
43            CommitInfo {
44                oid,
45                short_hash: oid.to_string()[..8].to_string(),
46                timestamp: naive_utc(author.when().seconds()),
47                author_offset_min: author.when().offset_minutes(),
48                author_name: String::from_utf8_lossy(author.name_bytes()).into_owned(),
49                author_email: String::from_utf8_lossy(author.email_bytes()).into_owned(),
50                committer_name: String::from_utf8_lossy(committer.name_bytes()).into_owned(),
51                committer_email: String::from_utf8_lossy(committer.email_bytes()).into_owned(),
52                committer_timestamp: naive_utc(committer.when().seconds()),
53                committer_offset_min: committer.when().offset_minutes(),
54                message: String::from_utf8_lossy(commit.message_bytes()).into_owned(),
55                message_is_utf8: commit.message().is_ok(),
56                parent_count: commit.parent_count(),
57            }
58        };
59
60        if print {
61            commits.push((oid, commit));
62        }
63        commit_infos.push(commit_info);
64    }
65
66    // If print is true, calculate and display statistics
67    if print {
68        let total_commits = commit_infos.len();
69
70        if total_commits > 0 {
71            let timestamps: Vec<_> = commit_infos.iter().map(|c| c.timestamp).collect();
72            let mut sorted_timestamps = timestamps.clone();
73            sorted_timestamps.sort();
74
75            let earliest_date = sorted_timestamps[0];
76            let latest_date = sorted_timestamps[sorted_timestamps.len() - 1];
77            let date_span = latest_date.signed_duration_since(earliest_date).num_days();
78
79            let unique_authors: std::collections::HashSet<String> =
80                commit_infos.iter().map(|c| c.author_name.clone()).collect();
81
82            // Print summary
83            crate::say!("\n{}", "Commit History Summary:".bold().green());
84            crate::say!("{}", "-".repeat(60).cyan());
85            crate::say!(
86                "{}: {}",
87                "Total Commits".bold(),
88                total_commits.to_string().yellow()
89            );
90            crate::say!(
91                "{}: {} days",
92                "Date Span".bold(),
93                date_span.to_string().yellow()
94            );
95            crate::say!(
96                "{}: {} to {}",
97                "Date Range".bold(),
98                earliest_date.format("%Y-%m-%d %H:%M:%S").to_string().blue(),
99                latest_date.format("%Y-%m-%d %H:%M:%S").to_string().blue()
100            );
101            crate::say!(
102                "{}: {}",
103                "Unique Authors".bold(),
104                unique_authors.len().to_string().yellow()
105            );
106            if unique_authors.len() <= 5 {
107                crate::say!(
108                    "{}: {}",
109                    "Authors".bold(),
110                    unique_authors
111                        .iter()
112                        .cloned()
113                        .collect::<Vec<_>>()
114                        .join(", ")
115                        .magenta()
116                );
117            }
118            crate::say!("{}", "=".repeat(60).cyan());
119
120            // Print detailed commit history
121            crate::say!("\n{}", "Detailed Commit History:".bold().green());
122            crate::say!("{}", "-".repeat(60).cyan());
123
124            for commit_info in &commit_infos {
125                crate::say!(
126                    "{} {} {} {}",
127                    commit_info.short_hash.yellow().bold(),
128                    commit_info
129                        .timestamp
130                        .format("%Y-%m-%d %H:%M:%S")
131                        .to_string()
132                        .blue(),
133                    crate::utils::sanitize::safe(&commit_info.author_name).magenta(),
134                    crate::utils::sanitize::safe(commit_info.message.lines().next().unwrap_or(""))
135                        .white()
136                );
137            }
138
139            crate::say!("{}", "=".repeat(60).cyan());
140        }
141    }
142
143    Ok(commit_infos)
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149    use std::fs;
150    use tempfile::TempDir;
151
152    fn create_test_repo_with_commits() -> (TempDir, String) {
153        let temp_dir = TempDir::new().unwrap();
154        let repo_path = temp_dir.path().to_str().unwrap().to_string();
155
156        // Initialize git repo
157        let repo = git2::Repository::init(&repo_path).unwrap();
158
159        // Create multiple commits
160        for i in 1..=3 {
161            let file_path = temp_dir.path().join(format!("test{i}.txt"));
162            fs::write(&file_path, format!("test content {i}")).unwrap();
163
164            let mut index = repo.index().unwrap();
165            index
166                .add_path(std::path::Path::new(&format!("test{i}.txt")))
167                .unwrap();
168            index.write().unwrap();
169
170            let tree_id = index.write_tree().unwrap();
171            let tree = repo.find_tree(tree_id).unwrap();
172
173            let sig = git2::Signature::new(
174                "Test User",
175                "test@example.com",
176                &git2::Time::new(1234567890 + i as i64 * 3600, 0),
177            )
178            .unwrap();
179
180            let parents = if i == 1 {
181                vec![]
182            } else {
183                let head = repo.head().unwrap();
184                let parent_commit = head.peel_to_commit().unwrap();
185                vec![parent_commit]
186            };
187
188            repo.commit(
189                Some("HEAD"),
190                &sig,
191                &sig,
192                &format!("Commit {i}"),
193                &tree,
194                &parents.iter().collect::<Vec<_>>(),
195            )
196            .unwrap();
197        }
198
199        (temp_dir, repo_path)
200    }
201
202    #[test]
203    fn test_get_commit_history_without_print() {
204        let (_temp_dir, repo_path) = create_test_repo_with_commits();
205        let args = Args {
206            repo_path: Some(repo_path),
207            ..Default::default()
208        };
209
210        let result = get_commit_history(&args, false);
211        assert!(result.is_ok());
212
213        let commit_infos = result.unwrap();
214        assert_eq!(commit_infos.len(), 3);
215
216        // Check that commits are in reverse chronological order (newest first)
217        assert_eq!(commit_infos[0].message, "Commit 3");
218        assert_eq!(commit_infos[1].message, "Commit 2");
219        assert_eq!(commit_infos[2].message, "Commit 1");
220    }
221
222    #[test]
223    fn test_get_commit_history_with_print() {
224        let (_temp_dir, repo_path) = create_test_repo_with_commits();
225        let args = Args {
226            repo_path: Some(repo_path),
227            show_history: true,
228            ..Default::default()
229        };
230
231        let result = get_commit_history(&args, true);
232        assert!(result.is_ok());
233
234        let commit_infos = result.unwrap();
235        assert_eq!(commit_infos.len(), 3);
236    }
237
238    #[test]
239    fn test_commit_info_fields() {
240        let (_temp_dir, repo_path) = create_test_repo_with_commits();
241        let args = Args {
242            repo_path: Some(repo_path),
243            ..Default::default()
244        };
245
246        let result = get_commit_history(&args, false);
247        assert!(result.is_ok());
248
249        let commit_infos = result.unwrap();
250        let first_commit = &commit_infos[0];
251
252        // Check that all fields are populated correctly
253        assert!(!first_commit.short_hash.is_empty());
254        assert_eq!(first_commit.short_hash.len(), 8);
255        assert_eq!(first_commit.author_name, "Test User");
256        assert_eq!(first_commit.author_email, "test@example.com");
257        assert!(!first_commit.message.is_empty());
258        assert_eq!(first_commit.parent_count, 1); // Second and third commits have parents
259    }
260
261    #[test]
262    fn test_get_commit_history_empty_repo() {
263        let temp_dir = TempDir::new().unwrap();
264        let repo_path = temp_dir.path().to_str().unwrap().to_string();
265
266        // Initialize empty git repo
267        git2::Repository::init(&repo_path).unwrap();
268
269        let args = Args {
270            repo_path: Some(repo_path),
271            ..Default::default()
272        };
273
274        // An unborn branch has no history; callers report "No commits found".
275        let commits = get_commit_history(&args, false).unwrap();
276        assert!(commits.is_empty());
277    }
278
279    #[test]
280    fn test_get_commit_history_invalid_repo() {
281        let args = Args {
282            repo_path: Some("/nonexistent/path".to_string()),
283            ..Default::default()
284        };
285
286        let result = get_commit_history(&args, false);
287        assert!(result.is_err());
288    }
289
290    #[test]
291    fn test_commit_info_parent_count() {
292        let (_temp_dir, repo_path) = create_test_repo_with_commits();
293        let args = Args {
294            repo_path: Some(repo_path),
295            ..Default::default()
296        };
297
298        let result = get_commit_history(&args, false);
299        assert!(result.is_ok());
300
301        let commit_infos = result.unwrap();
302
303        // First commit (chronologically) should have 0 parents
304        assert_eq!(commit_infos[2].parent_count, 0);
305
306        // Second and third commits should have 1 parent each
307        assert_eq!(commit_infos[1].parent_count, 1);
308        assert_eq!(commit_infos[0].parent_count, 1);
309    }
310}