Skip to main content

commit_wizard/infra/git/
mod.rs

1//! Git repository implementation.
2//!
3//! This module provides concrete implementations of Git operation traits.
4//! It uses both the `git2` library and Git CLI for operations.
5//!
6//! The main entry point is the [`Git`] struct which implements all Git operation traits.
7
8use std::{
9    collections::{BTreeMap, HashMap},
10    io::Write as _,
11    path::{Path, PathBuf},
12    process::{Command, Output, Stdio},
13};
14
15use git2::{
16    DiffFormat, DiffOptions, IndexAddOption, ObjectType, Oid, Repository, Sort, Status,
17    StatusEntry, StatusOptions,
18};
19
20use crate::engine::{
21    Error, ErrorCode,
22    models::{
23        git::{Change, CommitSummary, FileStatus},
24        policy::versioning::Version,
25    },
26};
27
28/// A tag boundary with all commits that fall in the range `(prev_tag, tag]`.
29/// The `tag` field is either a version string or `"Unreleased"` for commits
30/// that have not yet been tagged.
31#[derive(Debug, Clone)]
32pub struct TaggedCommits {
33    pub tag: String,
34    pub commits: Vec<CommitSummary>,
35}
36
37#[derive(Debug, Clone)]
38pub struct Git {
39    cwd: PathBuf,
40}
41
42impl Git {
43    pub fn new(cwd: impl Into<PathBuf>) -> Self {
44        Self { cwd: cwd.into() }
45    }
46
47    pub fn is_installed(&self) -> bool {
48        self.run(["--version"])
49            .is_some_and(|output| output.status.success())
50    }
51
52    pub fn is_inside_work_tree(&self) -> bool {
53        Repository::discover(&self.cwd).is_ok()
54    }
55
56    pub fn repo_root(&self) -> Option<PathBuf> {
57        Repository::discover(&self.cwd).ok().and_then(|repo| {
58            // workdir() returns None for bare repos; for all others it returns
59            // the working tree root (may have a trailing slash, so canonicalize).
60            repo.workdir().and_then(|p| std::fs::canonicalize(p).ok())
61        })
62    }
63
64    pub fn commit(&self, message: &str, allow_empty: bool) -> Result<(), Error> {
65        let mut cmd = Command::new("git");
66        cmd.current_dir(&self.cwd);
67        cmd.arg("commit");
68
69        if allow_empty {
70            cmd.arg("--allow-empty");
71        }
72
73        cmd.arg("-F").arg("-");
74
75        let mut child = cmd
76            .stdin(Stdio::piped())
77            .stdout(Stdio::inherit())
78            .stderr(Stdio::inherit())
79            .spawn()
80            .map_err(|err| {
81                ErrorCode::ProcessFailure
82                    .error()
83                    .with_context("command", "git commit -F -")
84                    .with_context("cwd", self.cwd.display().to_string())
85                    .with_context("error", err.to_string())
86            })?;
87
88        if let Some(stdin) = child.stdin.as_mut() {
89            stdin.write_all(message.as_bytes()).map_err(|err| {
90                ErrorCode::ProcessFailure
91                    .error()
92                    .with_context("command", "git commit -F -")
93                    .with_context("cwd", self.cwd.display().to_string())
94                    .with_context("error", err.to_string())
95            })?;
96        }
97
98        let status = child.wait().map_err(|err| {
99            ErrorCode::ProcessFailure
100                .error()
101                .with_context("command", "git commit -F -")
102                .with_context("cwd", self.cwd.display().to_string())
103                .with_context("error", err.to_string())
104        })?;
105
106        if status.success() {
107            Ok(())
108        } else {
109            Err(ErrorCode::ProcessFailure
110                .error()
111                .with_context("command", "git commit -F -")
112                .with_context("cwd", self.cwd.display().to_string())
113                .with_context("status", status.to_string()))
114        }
115    }
116
117    pub fn list_commits(&self, from: Option<&str>, to: &str) -> Result<Vec<CommitSummary>, Error> {
118        let repo = self.repo()?;
119        let to_oid = self.revparse_oid(&repo, to)?;
120        let from_oid = match from {
121            Some(value) => Some(self.revparse_oid(&repo, value)?),
122            None => None,
123        };
124
125        let mut revwalk = repo
126            .revwalk()
127            .map_err(|err| self.git2_error("revwalk", err))?;
128        revwalk
129            .push(to_oid)
130            .map_err(|err| self.git2_error("revwalk.push", err))?;
131
132        if let Some(oid) = from_oid {
133            revwalk
134                .hide(oid)
135                .map_err(|err| self.git2_error("revwalk.hide", err))?;
136        }
137
138        revwalk
139            .set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
140            .map_err(|err| self.git2_error("revwalk.set_sorting", err))?;
141
142        let mut out = Vec::new();
143        for oid in revwalk {
144            let oid = oid.map_err(|err| self.git2_error("revwalk.next", err))?;
145            let commit = repo
146                .find_commit(oid)
147                .map_err(|err| self.git2_error("find_commit", err))?;
148
149            out.push(CommitSummary {
150                hash: commit.id().to_string(),
151                summary: commit.summary().unwrap_or("").to_string(),
152                full_message: commit.message().map(|m| m.to_string()),
153            });
154        }
155
156        Ok(out)
157    }
158
159    pub fn latest_tag(&self) -> Result<Option<String>, Error> {
160        let repo = self.repo()?;
161        let tags = repo
162            .tag_names(None)
163            .map_err(|err| self.git2_error("tag_names", err))?;
164
165        // Only tags reachable from HEAD count, so tags from other branches
166        // never become the base of a version bump.
167        let Some(head) = repo.head().ok().and_then(|head| head.target()) else {
168            return Ok(None);
169        };
170
171        let mut latest: Option<(String, git2::Time)> = None;
172        let version_of = |tag: &str| Version::parse(tag, "v");
173
174        for tag_name in tags.iter().flatten() {
175            let tag_ref = format!("refs/tags/{tag_name}");
176            let Ok(reference) = repo.find_reference(&tag_ref) else {
177                continue;
178            };
179            let Ok(obj) = reference.peel(ObjectType::Commit) else {
180                continue;
181            };
182            let Some(commit) = obj.as_commit() else {
183                continue;
184            };
185
186            let reachable =
187                commit.id() == head || repo.graph_descendant_of(head, commit.id()).unwrap_or(false);
188            if !reachable {
189                continue;
190            }
191
192            let time = commit.time();
193
194            // Newest commit wins; tags on the same second (or commit) fall
195            // back to the higher version instead of iteration order.
196            match &latest {
197                Some((_, prev)) if time.seconds() < prev.seconds() => {}
198                Some((prev_name, prev))
199                    if time.seconds() == prev.seconds()
200                        && version_of(tag_name) <= version_of(prev_name) => {}
201                _ => latest = Some((tag_name.to_string(), time)),
202            }
203        }
204
205        Ok(latest.map(|(name, _)| name))
206    }
207
208    pub fn tag_date(&self, tag: &str) -> Result<Option<String>, Error> {
209        let repo = self.repo()?;
210        let reference = match repo.find_reference(&format!("refs/tags/{tag}")) {
211            Ok(reference) => reference,
212            Err(_) => return Ok(None),
213        };
214
215        let obj = match reference.peel(ObjectType::Commit) {
216            Ok(obj) => obj,
217            Err(_) => return Ok(None),
218        };
219
220        let Some(commit) = obj.as_commit() else {
221            return Ok(None);
222        };
223
224        let ts = commit.time().seconds();
225        let Some(dt) = chrono::DateTime::<chrono::Utc>::from_timestamp(ts, 0) else {
226            return Ok(None);
227        };
228
229        Ok(Some(dt.format("%Y-%m-%d").to_string()))
230    }
231
232    pub fn create_tag(&self, name: &str, message: &str) -> Result<(), Error> {
233        let repo = self.repo()?;
234        let obj = repo
235            .revparse_single("HEAD")
236            .map_err(|err| self.git2_error("revparse_single HEAD", err))?;
237        let sig = repo
238            .signature()
239            .map_err(|err| self.git2_error("signature", err))?;
240
241        repo.tag(name, &obj, &sig, message, false)
242            .map_err(|err| match err.code() {
243                git2::ErrorCode::Exists => ErrorCode::ReleaseTagExists
244                    .error()
245                    .with_context("tag", name.to_string()),
246                _ => self.git2_error("tag", err),
247            })?;
248
249        Ok(())
250    }
251
252    pub fn create_signed_tag(&self, name: &str, message: &str) -> Result<(), Error> {
253        let output = self
254            .run_dynamic(["tag", "-s", "-m", message, name])
255            .ok_or_else(|| {
256                ErrorCode::ProcessFailure
257                    .error()
258                    .with_context("command", "git tag -s")
259                    .with_context("cwd", self.cwd.display().to_string())
260            })?;
261
262        self.ensure_success("git tag -s", output)
263    }
264
265    pub fn create_branch(&self, name: &str, from: Option<&str>) -> Result<(), Error> {
266        let repo = self.repo()?;
267        let from_ref = from.unwrap_or("HEAD");
268        let target_oid = self.revparse_oid(&repo, from_ref)?;
269        let commit = repo
270            .find_commit(target_oid)
271            .map_err(|err| self.git2_error("find_commit", err))?;
272        repo.branch(name, &commit, false)
273            .map_err(|err| self.git2_error("branch", err))?;
274        Ok(())
275    }
276
277    pub fn checkout_branch(&self, name: &str) -> Result<(), Error> {
278        let output = self.run_dynamic(["checkout", name]).ok_or_else(|| {
279            ErrorCode::ProcessFailure
280                .error()
281                .with_context("command", "git checkout <branch>")
282                .with_context("cwd", self.cwd.display().to_string())
283        })?;
284        self.ensure_success("git checkout <branch>", output)
285    }
286
287    pub fn list_branches(&self) -> Result<Vec<String>, Error> {
288        let repo = self.repo()?;
289        let mut names = Vec::new();
290        for branch in repo
291            .branches(Some(git2::BranchType::Local))
292            .map_err(|err| self.git2_error("branches", err))?
293        {
294            let (b, _) = branch.map_err(|err| self.git2_error("branch_iter", err))?;
295            if let Some(name) = b
296                .name()
297                .map_err(|err| self.git2_error("branch.name", err))?
298            {
299                names.push(name.to_string());
300            }
301        }
302        Ok(names)
303    }
304
305    pub fn rename_branch(&self, old_name: &str, new_name: &str) -> Result<(), Error> {
306        let output = self
307            .run_dynamic(["branch", "-m", old_name, new_name])
308            .ok_or_else(|| {
309                ErrorCode::ProcessFailure
310                    .error()
311                    .with_context("command", "git branch -m <old> <new>")
312                    .with_context("cwd", self.cwd.display().to_string())
313            })?;
314        self.ensure_success("git branch -m <old> <new>", output)
315    }
316
317    pub fn delete_branch(&self, name: &str, force: bool) -> Result<(), Error> {
318        let flag = if force { "-D" } else { "-d" };
319        let output = self.run_dynamic(["branch", flag, name]).ok_or_else(|| {
320            ErrorCode::ProcessFailure
321                .error()
322                .with_context("command", format!("git branch {} <name>", flag))
323                .with_context("cwd", self.cwd.display().to_string())
324        })?;
325        self.ensure_success(&format!("git branch {} <name>", flag), output)
326    }
327
328    pub fn fetch(&self, remote: &str) -> Result<(), Error> {
329        let output = self.run_dynamic(["fetch", remote]).ok_or_else(|| {
330            ErrorCode::ProcessFailure
331                .error()
332                .with_context("command", "git fetch <remote>")
333                .with_context("cwd", self.cwd.display().to_string())
334        })?;
335        self.ensure_success("git fetch <remote>", output)
336    }
337
338    pub fn rebase(&self, onto: &str) -> Result<(), Error> {
339        let output = self.run_dynamic(["rebase", onto]).ok_or_else(|| {
340            ErrorCode::ProcessFailure
341                .error()
342                .with_context("command", "git rebase <onto>")
343                .with_context("cwd", self.cwd.display().to_string())
344        })?;
345        self.ensure_success("git rebase <onto>", output)
346    }
347
348    pub fn merge(&self, branch: &str) -> Result<(), Error> {
349        let output = self.run_dynamic(["merge", branch]).ok_or_else(|| {
350            ErrorCode::ProcessFailure
351                .error()
352                .with_context("command", "git merge <branch>")
353                .with_context("cwd", self.cwd.display().to_string())
354        })?;
355        self.ensure_success("git merge <branch>", output)
356    }
357
358    pub fn prune_remote_tracking(&self, remote: &str) -> Result<(), Error> {
359        let output = self
360            .run_dynamic(["remote", "prune", remote])
361            .ok_or_else(|| {
362                ErrorCode::ProcessFailure
363                    .error()
364                    .with_context("command", "git remote prune <remote>")
365                    .with_context("cwd", self.cwd.display().to_string())
366            })?;
367        self.ensure_success("git remote prune <remote>", output)
368    }
369
370    pub fn is_branch_merged(&self, name: &str) -> Result<bool, Error> {
371        let output = self.run_dynamic(["branch", "--merged"]).ok_or_else(|| {
372            ErrorCode::ProcessFailure
373                .error()
374                .with_context("command", "git branch --merged")
375                .with_context("cwd", self.cwd.display().to_string())
376        })?;
377        if !output.status.success() {
378            return Ok(false);
379        }
380        let stdout = String::from_utf8_lossy(&output.stdout);
381        Ok(stdout
382            .lines()
383            .any(|line| line.trim().trim_start_matches('*').trim() == name))
384    }
385
386    pub fn push_branch(&self, remote: &str, branch: &str) -> Result<(), Error> {
387        let output = self.run_dynamic(["push", remote, branch]).ok_or_else(|| {
388            ErrorCode::ProcessFailure
389                .error()
390                .with_context("command", "git push <remote> <branch>")
391                .with_context("cwd", self.cwd.display().to_string())
392        })?;
393
394        self.ensure_success("git push <remote> <branch>", output)
395    }
396
397    pub fn push_tag(&self, remote: &str, tag: &str) -> Result<(), Error> {
398        let output = self.run_dynamic(["push", remote, tag]).ok_or_else(|| {
399            ErrorCode::ProcessFailure
400                .error()
401                .with_context("command", "git push <remote> <tag>")
402                .with_context("cwd", self.cwd.display().to_string())
403        })?;
404
405        self.ensure_success("git push <remote> <tag>", output)
406    }
407
408    pub fn stage_path(&self, path: &str) -> Result<(), Error> {
409        self.stage_paths(&[path.to_string()])
410    }
411
412    pub fn unstage_path(&self, path: &str) -> Result<(), Error> {
413        self.unstage_paths(&[path.to_string()])
414    }
415
416    pub fn list_changes(&self) -> Result<Vec<Change>, Error> {
417        let repo = self.repo()?;
418        let mut opts = StatusOptions::new();
419        opts.include_untracked(true)
420            .include_ignored(false)
421            .include_unmodified(false)
422            .renames_head_to_index(true)
423            .renames_index_to_workdir(true)
424            .renames_from_rewrites(true)
425            .recurse_untracked_dirs(true)
426            .show(git2::StatusShow::IndexAndWorkdir);
427
428        let statuses = repo
429            .statuses(Some(&mut opts))
430            .map_err(|err| self.git2_error("statuses", err))?;
431
432        let mut seen: BTreeMap<String, Change> = BTreeMap::new();
433
434        for entry in statuses.iter() {
435            let st = entry.status();
436            let staged = st.is_index_new()
437                || st.is_index_modified()
438                || st.is_index_deleted()
439                || st.is_index_renamed()
440                || st.is_index_typechange();
441
442            let status = Self::map_status(&entry);
443            let path = match &status {
444                FileStatus::Renamed { new, .. } => new.clone(),
445                _ => Self::best_new_path(&entry)
446                    .unwrap_or_else(|| entry.path().unwrap_or_default().to_string()),
447            };
448
449            seen.entry(path.clone()).or_insert(Change {
450                path,
451                staged,
452                status,
453            });
454        }
455
456        Ok(seen.into_values().collect())
457    }
458
459    pub fn list_tags_sorted(&self) -> Result<Vec<String>, Error> {
460        let output = self
461            .run(["tag", "--list", "--sort=creatordate"])
462            .ok_or_else(|| {
463                ErrorCode::ProcessFailure
464                    .error()
465                    .with_context("command", "git tag --list --sort=creatordate")
466                    .with_context("cwd", self.cwd.display().to_string())
467            })?;
468
469        if !output.status.success() {
470            return Err(ErrorCode::ProcessFailure
471                .error()
472                .with_context("command", "git tag --list --sort=creatordate")
473                .with_context("cwd", self.cwd.display().to_string())
474                .with_context("status", output.status.to_string())
475                .with_context(
476                    "stderr",
477                    String::from_utf8_lossy(&output.stderr).trim().to_string(),
478                ));
479        }
480
481        Ok(String::from_utf8_lossy(&output.stdout)
482            .lines()
483            .map(|s| s.trim().to_string())
484            .filter(|s| !s.is_empty())
485            .collect())
486    }
487
488    pub fn latest_tag_ancestor_of(&self, rev: &str) -> Result<Option<String>, Error> {
489        let output = self
490            .run_dynamic(["describe", "--tags", "--abbrev=0", rev])
491            .ok_or_else(|| {
492                ErrorCode::ProcessFailure
493                    .error()
494                    .with_context("command", "git describe --tags --abbrev=0 <rev>")
495                    .with_context("cwd", self.cwd.display().to_string())
496            })?;
497
498        if !output.status.success() {
499            return Ok(None);
500        }
501
502        let tag = String::from_utf8_lossy(&output.stdout).trim().to_string();
503        Ok(if tag.is_empty() { None } else { Some(tag) })
504    }
505
506    /// Returns commits grouped by tag boundary, ordered newest-first.
507    ///
508    /// Each entry contains the tag name (or `"Unreleased"` for the leading
509    /// segment) and the commits that fall in that range.  The ranges are
510    /// computed as half-open intervals `(prev_tag, tag]` so every commit
511    /// appears in exactly one entry.
512    ///
513    /// `to` is the tip of the walk (usually `"HEAD"`).
514    pub fn commits_by_tag(&self, to: &str) -> Result<Vec<TaggedCommits>, Error> {
515        let tags = self.list_tags_sorted().unwrap_or_default();
516        let mut result: Vec<TaggedCommits> = Vec::new();
517
518        // Unreleased: commits since last tag up to `to`
519        let unreleased = self.list_commits(tags.last().map(|s| s.as_str()), to)?;
520        if !unreleased.is_empty() {
521            result.push(TaggedCommits {
522                tag: "Unreleased".to_string(),
523                commits: unreleased,
524            });
525        }
526
527        // One entry per tag (newest first), each covering (prev_tag, this_tag]
528        for (idx, tag) in tags.iter().enumerate().rev() {
529            let prev = if idx > 0 {
530                Some(tags[idx - 1].as_str())
531            } else {
532                None
533            };
534            let commits = self.list_commits(prev, tag)?;
535            if !commits.is_empty() {
536                result.push(TaggedCommits {
537                    tag: tag.clone(),
538                    commits,
539                });
540            }
541        }
542
543        Ok(result)
544    }
545
546    pub fn stage_all(&self) -> Result<(), Error> {
547        let repo = self.repo()?;
548        let mut index = repo.index().map_err(|err| self.git2_error("index", err))?;
549        index
550            .add_all(["*"].iter(), IndexAddOption::DEFAULT, None)
551            .map_err(|err| self.git2_error("index.add_all", err))?;
552        index
553            .write()
554            .map_err(|err| self.git2_error("index.write", err))?;
555        Ok(())
556    }
557
558    pub fn unstage_all(&self) -> Result<(), Error> {
559        let repo = self.repo()?;
560        let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok());
561        let mut index = repo.index().map_err(|err| self.git2_error("index", err))?;
562
563        if let Some(tree) = head_tree {
564            index
565                .read_tree(&tree)
566                .map_err(|err| self.git2_error("index.read_tree", err))?;
567        } else {
568            index
569                .clear()
570                .map_err(|err| self.git2_error("index.clear", err))?;
571        }
572
573        index
574            .write()
575            .map_err(|err| self.git2_error("index.write", err))?;
576
577        Ok(())
578    }
579
580    pub fn stage_paths(&self, paths: &[String]) -> Result<(), Error> {
581        if paths.is_empty() {
582            return Ok(());
583        }
584
585        let repo = self.repo()?;
586        let mut index = repo.index().map_err(|err| self.git2_error("index", err))?;
587
588        let mut opts = StatusOptions::new();
589        opts.include_untracked(true)
590            .include_ignored(false)
591            .include_unmodified(false)
592            .renames_head_to_index(true)
593            .renames_index_to_workdir(true)
594            .renames_from_rewrites(true)
595            .recurse_untracked_dirs(true)
596            .show(git2::StatusShow::IndexAndWorkdir);
597
598        let statuses = repo
599            .statuses(Some(&mut opts))
600            .map_err(|err| self.git2_error("statuses", err))?;
601
602        let mut info: HashMap<String, (Status, Option<(String, String)>)> = HashMap::new();
603
604        for entry in statuses.iter() {
605            let st = entry.status();
606            let path = Self::best_new_path(&entry)
607                .or_else(|| entry.path().map(|s| s.to_string()))
608                .unwrap_or_default();
609
610            let renamed = if st.intersects(Status::INDEX_RENAMED | Status::WT_RENAMED) {
611                Self::renamed_paths(&entry)
612            } else {
613                None
614            };
615
616            info.insert(path, (st, renamed));
617        }
618
619        for p in paths {
620            let path = Path::new(p);
621
622            if path.is_dir() {
623                index
624                    .add_all([p.as_str()].iter(), IndexAddOption::DEFAULT, None)
625                    .map_err(|err| self.git2_error("index.add_all(dir)", err))?;
626                continue;
627            }
628
629            if path.exists() {
630                index
631                    .add_path(path)
632                    .map_err(|err| self.git2_error("index.add_path", err))?;
633                continue;
634            }
635
636            match info.get(p) {
637                Some((st, renamed)) => {
638                    if st.intersects(Status::WT_DELETED | Status::INDEX_DELETED) {
639                        index
640                            .remove_path(path)
641                            .map_err(|err| self.git2_error("index.remove_path", err))?;
642                        continue;
643                    }
644
645                    if let Some((old, new)) = renamed {
646                        let new_path = Path::new(new);
647
648                        if new_path.is_dir() {
649                            index
650                                .add_all([new.as_str()].iter(), IndexAddOption::DEFAULT, None)
651                                .map_err(|err| self.git2_error("index.add_all(rename dir)", err))?;
652                        } else if new_path.exists() {
653                            index.add_path(new_path).map_err(|err| {
654                                self.git2_error("index.add_path(rename new)", err)
655                            })?;
656                        } else {
657                            index
658                                .add_all([new.as_str()].iter(), IndexAddOption::DEFAULT, None)
659                                .map_err(|err| {
660                                    self.git2_error("index.add_all(rename fallback)", err)
661                                })?;
662                        }
663
664                        index
665                            .remove_path(Path::new(old))
666                            .map_err(|err| self.git2_error("index.remove_path(rename old)", err))?;
667                        continue;
668                    }
669
670                    index
671                        .add_all([p.as_str()].iter(), IndexAddOption::DEFAULT, None)
672                        .map_err(|err| self.git2_error("index.add_all(fallback)", err))?;
673                }
674                None => {
675                    index
676                        .add_all([p.as_str()].iter(), IndexAddOption::DEFAULT, None)
677                        .map_err(|err| self.git2_error("index.add_all(missing)", err))?;
678                }
679            }
680        }
681
682        index
683            .write()
684            .map_err(|err| self.git2_error("index.write", err))?;
685
686        Ok(())
687    }
688
689    pub fn unstage_paths(&self, paths: &[String]) -> Result<(), Error> {
690        if paths.is_empty() {
691            return Ok(());
692        }
693
694        let repo = self.repo()?;
695        let head_exists = repo.head().is_ok();
696
697        if head_exists {
698            let mut chunk: Vec<&str> = Vec::new();
699            const CHUNK_SIZE: usize = 200;
700
701            for path in paths {
702                chunk.push(path.as_str());
703
704                if chunk.len() >= CHUNK_SIZE {
705                    self.git_reset_head_paths(&chunk)?;
706                    chunk.clear();
707                }
708            }
709
710            if !chunk.is_empty() {
711                self.git_reset_head_paths(&chunk)?;
712            }
713
714            Ok(())
715        } else {
716            let mut index = repo.index().map_err(|err| self.git2_error("index", err))?;
717
718            for path in paths {
719                index
720                    .remove_all([path.as_str()].iter(), None)
721                    .map_err(|err| {
722                        ErrorCode::ProcessFailure
723                            .error()
724                            .with_context("command", "git rm --cached / index.remove_all")
725                            .with_context("cwd", self.cwd.display().to_string())
726                            .with_context("path", path.clone())
727                            .with_context("error", err.to_string())
728                    })?;
729            }
730
731            index
732                .write()
733                .map_err(|err| self.git2_error("index.write", err))?;
734
735            Ok(())
736        }
737    }
738
739    pub fn diff_unstaged(&self, path: &str) -> Result<Option<String>, Error> {
740        let repo = self.repo()?;
741        let mut opts = DiffOptions::new();
742        opts.pathspec(path);
743
744        let diff = repo
745            .diff_index_to_workdir(None, Some(&mut opts))
746            .map_err(|err| self.git2_error("diff_index_to_workdir", err))?;
747
748        if diff.deltas().len() == 0 {
749            return Ok(None);
750        }
751
752        let mut buf = String::new();
753        diff.print(DiffFormat::Patch, |_delta, _hunk, line| {
754            let origin = line.origin();
755            let text = std::str::from_utf8(line.content()).unwrap_or("");
756
757            match origin {
758                '+' | '-' | ' ' => {
759                    buf.push(origin);
760                    buf.push_str(text);
761                }
762                _ => buf.push_str(text),
763            }
764
765            true
766        })
767        .map_err(|err| self.git2_error("diff.print", err))?;
768
769        Ok(Some(buf))
770    }
771
772    pub fn show_unstaged_diff(&self, path: &str) -> Result<String, Error> {
773        Ok(self.diff_unstaged(path)?.unwrap_or_default())
774    }
775
776    pub fn github_web_url(&self) -> Result<Option<String>, Error> {
777        let repo = self.repo()?;
778        let remotes = repo
779            .remotes()
780            .map_err(|err| self.git2_error("remotes", err))?;
781
782        let remote = remotes.iter().flatten().find(|r| *r == "origin");
783        let Some(remote) = remote else {
784            return Ok(None);
785        };
786
787        let remote_obj = repo
788            .find_remote(remote)
789            .map_err(|err| self.git2_error("find_remote", err))?;
790        let Some(url) = remote_obj.url() else {
791            return Ok(None);
792        };
793
794        let https = if url.starts_with("git@github.com:") {
795            url.replacen("git@github.com:", "https://github.com/", 1)
796                .trim_end_matches(".git")
797                .to_string()
798        } else if url.starts_with("https://github.com/") {
799            url.trim_end_matches(".git").to_string()
800        } else {
801            return Ok(None);
802        };
803
804        Ok(Some(https))
805    }
806
807    pub fn current_branch(&self) -> Result<String, Error> {
808        let repo = self.repo()?;
809        let head = repo.head().map_err(|err| {
810            ErrorCode::ProcessFailure
811                .error()
812                .with_context("command", "git symbolic-ref --short HEAD")
813                .with_context("cwd", self.cwd.display().to_string())
814                .with_context("error", err.to_string())
815                .with_context("reason", "failed to read HEAD")
816        })?;
817
818        if head.is_branch() {
819            head.shorthand().map(|s| s.to_string()).ok_or_else(|| {
820                ErrorCode::ProcessFailure
821                    .error()
822                    .with_context("command", "git symbolic-ref --short HEAD")
823                    .with_context("cwd", self.cwd.display().to_string())
824                    .with_context("reason", "unable to determine branch name from HEAD")
825            })
826        } else {
827            let oid = head
828                .target()
829                .map(|id| id.to_string())
830                .unwrap_or_else(|| "<unknown>".to_string());
831
832            Err(ErrorCode::ProcessFailure
833                .error()
834                .with_context("command", "git symbolic-ref --short HEAD")
835                .with_context("cwd", self.cwd.display().to_string())
836                .with_context("reason", "detached HEAD")
837                .with_context("head", oid))
838        }
839    }
840
841    fn repo(&self) -> Result<Repository, Error> {
842        Repository::discover(&self.cwd).map_err(|err| {
843            ErrorCode::ProcessFailure
844                .error()
845                .with_context("command", "git rev-parse --git-dir")
846                .with_context("cwd", self.cwd.display().to_string())
847                .with_context("error", err.to_string())
848                .with_context("reason", "failed to discover git repository")
849        })
850    }
851
852    fn revparse_oid(&self, repo: &Repository, rev: &str) -> Result<Oid, Error> {
853        repo.revparse_single(rev)
854            .map_err(|err| {
855                ErrorCode::ProcessFailure
856                    .error()
857                    .with_context("command", "git rev-parse <rev>")
858                    .with_context("cwd", self.cwd.display().to_string())
859                    .with_context("rev", rev.to_string())
860                    .with_context("error", err.to_string())
861            })
862            .and_then(|obj| {
863                // Peel annotated tags down to the underlying commit object
864                obj.peel(ObjectType::Commit).map(|c| c.id()).map_err(|err| {
865                    ErrorCode::ProcessFailure
866                        .error()
867                        .with_context("command", "git rev-parse <rev>")
868                        .with_context("cwd", self.cwd.display().to_string())
869                        .with_context("rev", rev.to_string())
870                        .with_context("error", err.to_string())
871                })
872            })
873    }
874
875    fn git_reset_head_paths(&self, paths: &[&str]) -> Result<(), Error> {
876        let mut args = vec!["reset", "-q", "HEAD", "--"];
877        args.extend(paths.iter().copied());
878
879        let output = Command::new("git")
880            .current_dir(&self.cwd)
881            .args(&args)
882            .output()
883            .map_err(|err| {
884                ErrorCode::ProcessFailure
885                    .error()
886                    .with_context("command", format!("git {}", args.join(" ")))
887                    .with_context("cwd", self.cwd.display().to_string())
888                    .with_context("error", err.to_string())
889            })?;
890
891        if output.status.success() {
892            Ok(())
893        } else {
894            Err(ErrorCode::ProcessFailure
895                .error()
896                .with_context("command", format!("git {}", args.join(" ")))
897                .with_context("cwd", self.cwd.display().to_string())
898                .with_context("status", output.status.to_string())
899                .with_context(
900                    "stderr",
901                    String::from_utf8_lossy(&output.stderr).trim().to_string(),
902                ))
903        }
904    }
905
906    fn git2_error(&self, operation: &str, err: git2::Error) -> Error {
907        ErrorCode::ProcessFailure
908            .error()
909            .with_context("operation", operation.to_string())
910            .with_context("cwd", self.cwd.display().to_string())
911            .with_context("error", err.to_string())
912    }
913
914    fn ensure_success(&self, command: &str, output: Output) -> Result<(), Error> {
915        if output.status.success() {
916            return Ok(());
917        }
918
919        Err(ErrorCode::ProcessFailure
920            .error()
921            .with_context("command", command.to_string())
922            .with_context("cwd", self.cwd.display().to_string())
923            .with_context("status", output.status.to_string())
924            .with_context(
925                "stderr",
926                String::from_utf8_lossy(&output.stderr).trim().to_string(),
927            ))
928    }
929
930    fn is_staged_bits(status: Status) -> bool {
931        status.intersects(
932            Status::INDEX_NEW
933                | Status::INDEX_MODIFIED
934                | Status::INDEX_DELETED
935                | Status::INDEX_RENAMED
936                | Status::INDEX_TYPECHANGE,
937        )
938    }
939
940    fn renamed_paths(entry: &StatusEntry<'_>) -> Option<(String, String)> {
941        if let Some(delta) = entry.head_to_index() {
942            let old = delta.old_file().path()?.to_string_lossy().into_owned();
943            let new = delta.new_file().path()?.to_string_lossy().into_owned();
944            return Some((old, new));
945        }
946
947        if let Some(delta) = entry.index_to_workdir() {
948            let old = delta.old_file().path()?.to_string_lossy().into_owned();
949            let new = delta.new_file().path()?.to_string_lossy().into_owned();
950            return Some((old, new));
951        }
952
953        None
954    }
955
956    fn best_new_path(entry: &StatusEntry<'_>) -> Option<String> {
957        if let Some(delta) = entry.head_to_index()
958            && let Some(path) = delta.new_file().path()
959        {
960            return Some(path.to_string_lossy().into_owned());
961        }
962
963        if let Some(delta) = entry.index_to_workdir()
964            && let Some(path) = delta.new_file().path()
965        {
966            return Some(path.to_string_lossy().into_owned());
967        }
968
969        entry.path().map(|p| p.to_string())
970    }
971
972    fn map_status(entry: &StatusEntry<'_>) -> FileStatus {
973        let status = entry.status();
974
975        if status.contains(Status::IGNORED) {
976            return FileStatus::Unknown;
977        }
978
979        let staged = Self::is_staged_bits(status);
980
981        if status.contains(Status::WT_NEW) && !staged {
982            return FileStatus::Untracked;
983        }
984
985        if status.intersects(Status::INDEX_RENAMED | Status::WT_RENAMED) {
986            if let Some((old, new)) = Self::renamed_paths(entry) {
987                return FileStatus::Renamed { old, new };
988            }
989            return FileStatus::Unknown;
990        }
991
992        if status.intersects(Status::INDEX_DELETED | Status::WT_DELETED) {
993            return FileStatus::Deleted;
994        }
995
996        if status.intersects(Status::INDEX_TYPECHANGE | Status::WT_TYPECHANGE) {
997            return FileStatus::TypeChange;
998        }
999
1000        if status.intersects(Status::INDEX_MODIFIED | Status::WT_MODIFIED) {
1001            return FileStatus::Modified;
1002        }
1003
1004        if status.intersects(Status::INDEX_NEW | Status::WT_NEW) {
1005            return FileStatus::Added;
1006        }
1007
1008        FileStatus::Unknown
1009    }
1010
1011    fn run<const N: usize>(&self, args: [&str; N]) -> Option<Output> {
1012        Command::new("git")
1013            .current_dir(&self.cwd)
1014            .args(args)
1015            .output()
1016            .ok()
1017    }
1018
1019    fn run_dynamic<const N: usize>(&self, args: [&str; N]) -> Option<Output> {
1020        Command::new("git")
1021            .current_dir(&self.cwd)
1022            .args(args)
1023            .output()
1024            .ok()
1025    }
1026}