gitkraft_core/features/commits/
ops.rs1use anyhow::{Context, Result};
4use git2::Repository;
5use std::collections::HashMap;
6
7use super::types::{CommitInfo, RefKind, RefLabel};
8
9pub(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 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 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
89pub 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
106pub 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 if let Some(refs) = ref_map.get(&oid) {
133 info.refs = refs.clone();
134 }
135 commits.push(info);
136 }
137
138 Ok(commits)
139}
140
141pub fn create_commit(repo: &Repository, message: &str) -> Result<CommitInfo> {
146 let sig = repo.signature().context(
147 "failed to obtain default signature — set user.name and user.email in git config",
148 )?;
149
150 let mut index = repo.index().context("failed to read index")?;
151 let tree_oid = index
152 .write_tree()
153 .context("failed to write index to tree — are there staged changes?")?;
154 let tree = repo
155 .find_tree(tree_oid)
156 .context("failed to find tree written from index")?;
157
158 let parent_commit;
160 let parents: Vec<&git2::Commit<'_>> = if let Ok(head_ref) = repo.head() {
161 let head_oid = head_ref
162 .target()
163 .context("HEAD is not a direct reference")?;
164 parent_commit = repo
165 .find_commit(head_oid)
166 .context("failed to find HEAD commit")?;
167 vec![&parent_commit]
168 } else {
169 vec![]
171 };
172
173 let oid = repo
174 .commit(Some("HEAD"), &sig, &sig, message, &tree, &parents)
175 .context("failed to create commit")?;
176
177 let commit = repo
178 .find_commit(oid)
179 .context("failed to look up newly created commit")?;
180
181 Ok(CommitInfo::from_git2_commit(&commit))
182}
183
184pub fn get_commit_details(repo: &Repository, oid_str: &str) -> Result<CommitInfo> {
186 let oid =
187 git2::Oid::from_str(oid_str).with_context(|| format!("invalid OID string: {oid_str}"))?;
188 let commit = repo
189 .find_commit(oid)
190 .with_context(|| format!("commit {oid_str} not found"))?;
191
192 Ok(CommitInfo::from_git2_commit(&commit))
193}
194
195#[cfg(test)]
196mod tests {
197 #[test]
198 fn cherry_pick_on_nonexistent_repo_returns_error() {
199 let result = super::cherry_pick_commit(std::path::Path::new("/nonexistent"), "abc1234");
200 assert!(result.is_err());
201 }
202
203 use super::*;
204 use tempfile::TempDir;
205
206 fn setup_repo_with_commit() -> (TempDir, Repository) {
208 let dir = TempDir::new().unwrap();
209 let repo = Repository::init(dir.path()).unwrap();
210
211 let mut config = repo.config().unwrap();
213 config.set_str("user.name", "Test User").unwrap();
214 config.set_str("user.email", "test@example.com").unwrap();
215
216 let file_path = dir.path().join("hello.txt");
218 std::fs::write(&file_path, "hello world\n").unwrap();
219 {
220 let mut index = repo.index().unwrap();
221 index.add_path(std::path::Path::new("hello.txt")).unwrap();
222 index.write().unwrap();
223
224 let tree_oid = index.write_tree().unwrap();
225 let tree = repo.find_tree(tree_oid).unwrap();
226 let sig = repo.signature().unwrap();
227 repo.commit(Some("HEAD"), &sig, &sig, "initial commit", &tree, &[])
228 .unwrap();
229 }
230
231 (dir, repo)
232 }
233
234 #[test]
235 fn list_commits_returns_initial_commit() {
236 let (_dir, repo) = setup_repo_with_commit();
237 let commits = list_commits(&repo, 10).unwrap();
238 assert_eq!(commits.len(), 1);
239 assert_eq!(commits[0].summary, "initial commit");
240 assert!(!commits[0].oid.is_empty());
241 assert_eq!(commits[0].short_oid.len(), 7);
242 assert!(commits[0].parent_ids.is_empty());
243 }
244
245 #[test]
246 fn create_commit_works() {
247 let (dir, repo) = setup_repo_with_commit();
248
249 std::fs::write(dir.path().join("hello.txt"), "updated\n").unwrap();
251 let mut index = repo.index().unwrap();
252 index.add_path(std::path::Path::new("hello.txt")).unwrap();
253 index.write().unwrap();
254
255 let info = create_commit(&repo, "second commit").unwrap();
256 assert_eq!(info.summary, "second commit");
257 assert_eq!(info.parent_ids.len(), 1);
258 }
259
260 #[test]
261 fn get_commit_details_works() {
262 let (_dir, repo) = setup_repo_with_commit();
263 let commits = list_commits(&repo, 1).unwrap();
264 let oid_str = &commits[0].oid;
265 let detail = get_commit_details(&repo, oid_str).unwrap();
266 assert_eq!(detail.oid, *oid_str);
267 assert_eq!(detail.summary, "initial commit");
268 }
269
270 #[test]
271 fn get_commit_details_bad_oid() {
272 let (_dir, repo) = setup_repo_with_commit();
273 let result = get_commit_details(&repo, "not-a-valid-oid");
274 assert!(result.is_err());
275 }
276
277 #[test]
278 fn list_commits_respects_max_count() {
279 let (dir, repo) = setup_repo_with_commit();
280
281 std::fs::write(dir.path().join("second.txt"), "two\n").unwrap();
283 let mut index = repo.index().unwrap();
284 index.add_path(std::path::Path::new("second.txt")).unwrap();
285 index.write().unwrap();
286 create_commit(&repo, "second commit").unwrap();
287
288 let one = list_commits(&repo, 1).unwrap();
289 assert_eq!(one.len(), 1);
290 assert_eq!(one[0].summary, "second commit");
291
292 let both = list_commits(&repo, 100).unwrap();
293 assert_eq!(both.len(), 2);
294 }
295
296 #[test]
297 fn list_commits_attaches_head_ref_to_tip() {
298 let (_dir, repo) = setup_repo_with_commit();
299 let commits = list_commits(&repo, 10).unwrap();
300 assert!(!commits[0].refs.is_empty(), "tip commit should have refs");
302 assert!(
303 commits[0]
304 .refs
305 .iter()
306 .any(|r| r.kind == crate::features::commits::types::RefKind::Head),
307 "tip commit should have a Head ref"
308 );
309 }
310
311 #[test]
312 fn list_commits_non_tip_commits_have_no_refs() {
313 let (dir, repo) = setup_repo_with_commit();
314 std::fs::write(dir.path().join("second.txt"), "two\n").unwrap();
316 let mut index = repo.index().unwrap();
317 index.add_path(std::path::Path::new("second.txt")).unwrap();
318 index.write().unwrap();
319 create_commit(&repo, "second commit").unwrap();
320
321 let commits = list_commits(&repo, 100).unwrap();
322 assert_eq!(commits.len(), 2);
323 assert!(!commits[0].refs.is_empty());
325 assert!(
327 commits[1].refs.is_empty(),
328 "non-tip commits should have empty refs"
329 );
330 }
331
332 #[test]
333 fn build_ref_map_includes_tags() {
334 let (_dir, repo) = setup_repo_with_commit();
335 let head_oid = repo.head().unwrap().target().unwrap();
337 let head_commit = repo.find_commit(head_oid).unwrap();
338 repo.tag_lightweight("v1.0.0", head_commit.as_object(), false)
339 .unwrap();
340
341 let ref_map = build_ref_map(&repo);
342 let labels = ref_map.get(&head_oid).expect("HEAD should have refs");
343 assert!(
344 labels
345 .iter()
346 .any(|r| r.name == "v1.0.0"
347 && r.kind == crate::features::commits::types::RefKind::Tag),
348 "tag should appear in ref map"
349 );
350 }
351}