Skip to main content

gitkraft_core/features/commits/
ops.rs

1//! Commit operations — list, create, and inspect commits.
2
3use anyhow::{Context, Result};
4use git2::Repository;
5use std::collections::HashMap;
6
7use super::types::{CommitInfo, RefKind, RefLabel};
8
9// ── ref map ───────────────────────────────────────────────────────────────
10
11/// Build a map of commit OID → ref labels for all refs in the repository.
12///
13/// Used by [`list_commits`] and [`crate::features::log::ops::get_log`] to
14/// attach branch/tag information to each [`CommitInfo`].
15pub(crate) fn build_ref_map(repo: &Repository) -> HashMap<git2::Oid, Vec<RefLabel>> {
16    let mut map: HashMap<git2::Oid, Vec<RefLabel>> = HashMap::new();
17
18    let head_branch: Option<String> = repo
19        .head()
20        .ok()
21        .filter(|h| h.is_branch())
22        .and_then(|h| h.shorthand().map(|s| s.to_string()));
23
24    if let Ok(refs) = repo.references() {
25        for rf in refs.flatten() {
26            let full_name = match rf.name() {
27                Some(n) => n.to_string(),
28                None => continue,
29            };
30            let oid = match rf.peel_to_commit() {
31                Ok(c) => c.id(),
32                Err(_) => continue,
33            };
34            let label = if let Some(branch) = full_name.strip_prefix("refs/heads/") {
35                let kind = if head_branch.as_deref() == Some(branch) {
36                    RefKind::Head
37                } else {
38                    RefKind::LocalBranch
39                };
40                RefLabel {
41                    name: branch.to_string(),
42                    kind,
43                }
44            } else if let Some(rb) = full_name.strip_prefix("refs/remotes/") {
45                if rb.ends_with("/HEAD") {
46                    continue;
47                }
48                RefLabel {
49                    name: rb.to_string(),
50                    kind: RefKind::RemoteBranch,
51                }
52            } else if let Some(tag) = full_name.strip_prefix("refs/tags/") {
53                RefLabel {
54                    name: tag.to_string(),
55                    kind: RefKind::Tag,
56                }
57            } else {
58                continue;
59            };
60            map.entry(oid).or_default().push(label);
61        }
62    }
63
64    // Detached HEAD: synthesise a label for the bare commit.
65    if head_branch.is_none() {
66        if let Ok(head) = repo.head() {
67            if let Ok(commit) = head.peel_to_commit() {
68                map.entry(commit.id()).or_default().push(RefLabel {
69                    name: "HEAD".to_string(),
70                    kind: RefKind::Head,
71                });
72            }
73        }
74    }
75
76    // Sort each bucket: Head first, LocalBranch, RemoteBranch, Tag.
77    for labels in map.values_mut() {
78        labels.sort_by_key(|r| match r.kind {
79            RefKind::Head => 0u8,
80            RefKind::LocalBranch => 1,
81            RefKind::RemoteBranch => 2,
82            RefKind::Tag => 3,
83        });
84    }
85
86    map
87}
88
89// ── cherry-pick ──────────────────────────────────────────────────────────
90pub fn cherry_pick_commit(workdir: &std::path::Path, oid_str: &str) -> anyhow::Result<()> {
91    let output = std::process::Command::new("git")
92        .args(["cherry-pick", oid_str])
93        .current_dir(workdir)
94        .output()
95        .context("failed to run git cherry-pick")?;
96    if output.status.success() {
97        Ok(())
98    } else {
99        Err(anyhow::anyhow!(
100            "cherry-pick failed: {}",
101            String::from_utf8_lossy(&output.stderr).trim()
102        ))
103    }
104}
105
106/// Walk the history from HEAD and return up to `max_count` commits.
107///
108/// Commits are sorted topologically and by time (newest first).
109/// Each commit's [`CommitInfo::refs`] is populated with any branch / tag /
110/// HEAD labels that point directly at it.
111pub fn list_commits(repo: &Repository, max_count: usize) -> Result<Vec<CommitInfo>> {
112    let ref_map = build_ref_map(repo);
113
114    let mut revwalk = repo.revwalk().context("failed to create revwalk")?;
115    revwalk
116        .push_head()
117        .context("failed to push HEAD to revwalk")?;
118    revwalk
119        .set_sorting(git2::Sort::TIME | git2::Sort::TOPOLOGICAL)
120        .context("failed to set revwalk sorting")?;
121
122    let mut commits = Vec::with_capacity(max_count.min(256));
123    for oid_result in revwalk {
124        if commits.len() >= max_count {
125            break;
126        }
127        let oid = oid_result.context("revwalk iteration error")?;
128        let commit = repo
129            .find_commit(oid)
130            .with_context(|| format!("failed to find commit {oid}"))?;
131        let mut info = CommitInfo::from_git2_commit(&commit);
132        // Don't store full multi-line commit bodies in the batch list —
133        // only the summary (first line) is shown in the log view.
134        // The full message is re-loaded on demand via get_commit_details().
135        info.message = String::new();
136        if let Some(refs) = ref_map.get(&oid) {
137            info.refs = refs.clone();
138        }
139        commits.push(info);
140    }
141
142    Ok(commits)
143}
144
145/// Commit the currently staged (index) changes with the given message.
146///
147/// Uses the repository's default signature (`user.name` / `user.email`).
148/// Returns the newly created [`CommitInfo`].
149pub fn create_commit(repo: &Repository, message: &str) -> Result<CommitInfo> {
150    let sig = repo.signature().context(
151        "failed to obtain default signature — set user.name and user.email in git config",
152    )?;
153
154    let mut index = repo.index().context("failed to read index")?;
155    let tree_oid = index
156        .write_tree()
157        .context("failed to write index to tree — are there staged changes?")?;
158    let tree = repo
159        .find_tree(tree_oid)
160        .context("failed to find tree written from index")?;
161
162    // Collect parent commits (HEAD if it exists).
163    let parent_commit;
164    let parents: Vec<&git2::Commit<'_>> = if let Ok(head_ref) = repo.head() {
165        let head_oid = head_ref
166            .target()
167            .context("HEAD is not a direct reference")?;
168        parent_commit = repo
169            .find_commit(head_oid)
170            .context("failed to find HEAD commit")?;
171        vec![&parent_commit]
172    } else {
173        // Initial commit — no parents.
174        vec![]
175    };
176
177    let oid = repo
178        .commit(Some("HEAD"), &sig, &sig, message, &tree, &parents)
179        .context("failed to create commit")?;
180
181    let commit = repo
182        .find_commit(oid)
183        .context("failed to look up newly created commit")?;
184
185    Ok(CommitInfo::from_git2_commit(&commit))
186}
187
188/// Retrieve the full [`CommitInfo`] for a commit identified by its hex OID string.
189pub fn get_commit_details(repo: &Repository, oid_str: &str) -> Result<CommitInfo> {
190    let oid =
191        git2::Oid::from_str(oid_str).with_context(|| format!("invalid OID string: {oid_str}"))?;
192    let commit = repo
193        .find_commit(oid)
194        .with_context(|| format!("commit {oid_str} not found"))?;
195
196    Ok(CommitInfo::from_git2_commit(&commit))
197}
198
199#[cfg(test)]
200mod tests {
201    #[test]
202    fn cherry_pick_on_nonexistent_repo_returns_error() {
203        let result = super::cherry_pick_commit(std::path::Path::new("/nonexistent"), "abc1234");
204        assert!(result.is_err());
205    }
206
207    use super::*;
208    use tempfile::TempDir;
209
210    /// Helper: create a repo with one commit so HEAD exists.
211    fn setup_repo_with_commit() -> (TempDir, Repository) {
212        let dir = TempDir::new().unwrap();
213        let repo = Repository::init(dir.path()).unwrap();
214
215        // Configure signature.
216        let mut config = repo.config().unwrap();
217        config.set_str("user.name", "Test User").unwrap();
218        config.set_str("user.email", "test@example.com").unwrap();
219
220        // Create a file, stage it, and commit.
221        let file_path = dir.path().join("hello.txt");
222        std::fs::write(&file_path, "hello world\n").unwrap();
223        {
224            let mut index = repo.index().unwrap();
225            index.add_path(std::path::Path::new("hello.txt")).unwrap();
226            index.write().unwrap();
227
228            let tree_oid = index.write_tree().unwrap();
229            let tree = repo.find_tree(tree_oid).unwrap();
230            let sig = repo.signature().unwrap();
231            repo.commit(Some("HEAD"), &sig, &sig, "initial commit", &tree, &[])
232                .unwrap();
233        }
234
235        (dir, repo)
236    }
237
238    #[test]
239    fn list_commits_returns_initial_commit() {
240        let (_dir, repo) = setup_repo_with_commit();
241        let commits = list_commits(&repo, 10).unwrap();
242        assert_eq!(commits.len(), 1);
243        assert_eq!(commits[0].summary, "initial commit");
244        assert!(!commits[0].oid.is_empty());
245        assert_eq!(commits[0].short_oid.len(), 7);
246        assert!(commits[0].parent_ids.is_empty());
247    }
248
249    #[test]
250    fn create_commit_works() {
251        let (dir, repo) = setup_repo_with_commit();
252
253        // Make a change, stage it, then commit.
254        std::fs::write(dir.path().join("hello.txt"), "updated\n").unwrap();
255        let mut index = repo.index().unwrap();
256        index.add_path(std::path::Path::new("hello.txt")).unwrap();
257        index.write().unwrap();
258
259        let info = create_commit(&repo, "second commit").unwrap();
260        assert_eq!(info.summary, "second commit");
261        assert_eq!(info.parent_ids.len(), 1);
262    }
263
264    #[test]
265    fn get_commit_details_works() {
266        let (_dir, repo) = setup_repo_with_commit();
267        let commits = list_commits(&repo, 1).unwrap();
268        let oid_str = &commits[0].oid;
269        let detail = get_commit_details(&repo, oid_str).unwrap();
270        assert_eq!(detail.oid, *oid_str);
271        assert_eq!(detail.summary, "initial commit");
272    }
273
274    #[test]
275    fn get_commit_details_bad_oid() {
276        let (_dir, repo) = setup_repo_with_commit();
277        let result = get_commit_details(&repo, "not-a-valid-oid");
278        assert!(result.is_err());
279    }
280
281    #[test]
282    fn list_commits_respects_max_count() {
283        let (dir, repo) = setup_repo_with_commit();
284
285        // Add a second commit.
286        std::fs::write(dir.path().join("second.txt"), "two\n").unwrap();
287        let mut index = repo.index().unwrap();
288        index.add_path(std::path::Path::new("second.txt")).unwrap();
289        index.write().unwrap();
290        create_commit(&repo, "second commit").unwrap();
291
292        let one = list_commits(&repo, 1).unwrap();
293        assert_eq!(one.len(), 1);
294        assert_eq!(one[0].summary, "second commit");
295
296        let both = list_commits(&repo, 100).unwrap();
297        assert_eq!(both.len(), 2);
298    }
299
300    #[test]
301    fn list_commits_attaches_head_ref_to_tip() {
302        let (_dir, repo) = setup_repo_with_commit();
303        let commits = list_commits(&repo, 10).unwrap();
304        // The single commit should carry the HEAD branch label.
305        assert!(!commits[0].refs.is_empty(), "tip commit should have refs");
306        assert!(
307            commits[0]
308                .refs
309                .iter()
310                .any(|r| r.kind == crate::features::commits::types::RefKind::Head),
311            "tip commit should have a Head ref"
312        );
313    }
314
315    #[test]
316    fn list_commits_non_tip_commits_have_no_refs() {
317        let (dir, repo) = setup_repo_with_commit();
318        // Add a second commit — only the tip should have refs.
319        std::fs::write(dir.path().join("second.txt"), "two\n").unwrap();
320        let mut index = repo.index().unwrap();
321        index.add_path(std::path::Path::new("second.txt")).unwrap();
322        index.write().unwrap();
323        create_commit(&repo, "second commit").unwrap();
324
325        let commits = list_commits(&repo, 100).unwrap();
326        assert_eq!(commits.len(), 2);
327        // Tip (newest) should have refs
328        assert!(!commits[0].refs.is_empty());
329        // Parent (older) should have no refs
330        assert!(
331            commits[1].refs.is_empty(),
332            "non-tip commits should have empty refs"
333        );
334    }
335
336    #[test]
337    fn build_ref_map_includes_tags() {
338        let (_dir, repo) = setup_repo_with_commit();
339        // Create a lightweight tag on HEAD
340        let head_oid = repo.head().unwrap().target().unwrap();
341        let head_commit = repo.find_commit(head_oid).unwrap();
342        repo.tag_lightweight("v1.0.0", head_commit.as_object(), false)
343            .unwrap();
344
345        let ref_map = build_ref_map(&repo);
346        let labels = ref_map.get(&head_oid).expect("HEAD should have refs");
347        assert!(
348            labels
349                .iter()
350                .any(|r| r.name == "v1.0.0"
351                    && r.kind == crate::features::commits::types::RefKind::Tag),
352            "tag should appear in ref map"
353        );
354    }
355}