Skip to main content

diffler_core/
git.rs

1//! git2 backend for the [`Vcs`] trait: the only module that may touch git2
2//! (test fixtures aside).
3
4use std::collections::HashMap;
5use std::fs;
6use std::path::{Path, PathBuf};
7
8use crate::model::{DiffLine, DiffModel, FileDiff, FileStatus, Hunk, HunkId, LineKind, hunk_id};
9use crate::vcs::{
10    BlameSpan, BranchInfo, HeadInfo, LogEntry, NetworkOp, StatusModel, Vcs, VcsError,
11};
12
13/// git's own default amount of context around hunks.
14pub const DEFAULT_CONTEXT_LINES: u32 = 3;
15
16pub struct GitVcs {
17    repo: git2::Repository,
18    context_lines: u32,
19}
20
21impl GitVcs {
22    pub fn open(root: &Path) -> Result<Self, VcsError> {
23        Self::open_with_context(root, DEFAULT_CONTEXT_LINES)
24    }
25
26    /// Open with a custom number of context lines around diff hunks.
27    pub fn open_with_context(root: &Path, context_lines: u32) -> Result<Self, VcsError> {
28        let repo = git2::Repository::open(root)?;
29        if repo.workdir().is_none() {
30            return Err(VcsError::NoWorkdir);
31        }
32        Ok(Self {
33            repo,
34            context_lines,
35        })
36    }
37
38    /// HEAD tree, or `None` on an unborn branch (fresh repo).
39    fn head_tree(&self) -> Result<Option<git2::Tree<'_>>, VcsError> {
40        match self.repo.head() {
41            Ok(head) => Ok(Some(head.peel_to_tree()?)),
42            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => Ok(None),
43            Err(err) => Err(err.into()),
44        }
45    }
46
47    fn workdir_path(&self) -> Result<&Path, VcsError> {
48        self.repo.workdir().ok_or(VcsError::NoWorkdir)
49    }
50
51    /// `base` tree vs workdir+index including untracked, renames folded in.
52    /// `None` is the empty tree (an unborn branch).
53    fn workdir_diff(&self, base: Option<&git2::Tree<'_>>) -> Result<DiffModel, VcsError> {
54        let mut diff = self.repo.diff_tree_to_workdir_with_index(
55            base,
56            Some(&mut workdir_diff_options(self.context_lines)),
57        )?;
58        let mut find = git2::DiffFindOptions::new();
59        find.renames(true);
60        diff.find_similar(Some(&mut find))?;
61        diff_to_model(&self.repo, &mut diff)
62    }
63
64    fn walk_entries(
65        &self,
66        walk: git2::Revwalk<'_>,
67        limit: usize,
68    ) -> Result<Vec<LogEntry>, VcsError> {
69        let mut entries = Vec::new();
70        for oid in walk.take(limit) {
71            let oid = oid?;
72            let commit = self.repo.find_commit(oid)?;
73            let full = oid.to_string();
74            entries.push(LogEntry {
75                oid7: short7(&full),
76                oid: full,
77                refs: Vec::new(),
78                subject: commit.summary()?.unwrap_or_default().to_owned(),
79                author: commit.author().name().unwrap_or_default().to_owned(),
80                time_unix: commit.time().seconds(),
81            });
82        }
83        Ok(entries)
84    }
85
86    /// Whether any tracked file differs from HEAD or the index, i.e. there is
87    /// something `git stash` would save. Untracked files don't count, matching
88    /// stash's default.
89    fn has_tracked_changes(&self) -> Result<bool, VcsError> {
90        let mut opts = git2::StatusOptions::new();
91        opts.include_untracked(false).include_ignored(false);
92        let statuses = self.repo.statuses(Some(&mut opts))?;
93        Ok(statuses.iter().next().is_some())
94    }
95}
96
97impl Vcs for GitVcs {
98    fn git_dir(&self) -> Result<PathBuf, VcsError> {
99        // libgit2 resolves gitlink files, so linked worktrees come back as
100        // their external gitdir under the main repo's .git/worktrees/
101        Ok(self.repo.path().to_path_buf())
102    }
103
104    fn head(&self) -> Result<HeadInfo, VcsError> {
105        match self.repo.head() {
106            Ok(head) => {
107                let branch = if head.is_branch() {
108                    Some(head.shorthand()?.to_owned())
109                } else {
110                    None
111                };
112                let commit = head.peel_to_commit()?;
113                let tracking = branch.as_deref().and_then(|name| {
114                    let local = self.repo.find_branch(name, git2::BranchType::Local).ok()?;
115                    let upstream = local.upstream().ok()?;
116                    let name = upstream.name().ok().flatten()?.to_owned();
117                    Some((name, upstream.get().target()))
118                });
119                let (upstream, ahead, behind) = match tracking {
120                    Some((name, Some(target))) => {
121                        let (ahead, behind) = self
122                            .repo
123                            .graph_ahead_behind(commit.id(), target)
124                            .unwrap_or((0, 0));
125                        (Some(name), ahead, behind)
126                    }
127                    Some((name, None)) => (Some(name), 0, 0),
128                    None => (None, 0, 0),
129                };
130                Ok(HeadInfo {
131                    branch,
132                    oid7: short7(&commit.id().to_string()),
133                    subject: commit.summary()?.unwrap_or_default().to_owned(),
134                    upstream,
135                    ahead,
136                    behind,
137                })
138            }
139            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
140                let branch = self
141                    .repo
142                    .find_reference("HEAD")
143                    .ok()
144                    .and_then(|r| r.symbolic_target().ok().flatten().map(str::to_owned))
145                    .and_then(|t| t.strip_prefix("refs/heads/").map(str::to_owned));
146                Ok(HeadInfo {
147                    branch,
148                    oid7: String::new(),
149                    subject: String::new(),
150                    upstream: None,
151                    ahead: 0,
152                    behind: 0,
153                })
154            }
155            Err(err) => Err(err.into()),
156        }
157    }
158
159    fn status(&self) -> Result<StatusModel, VcsError> {
160        // index vs workdir classifies "untracked" against the index, so a
161        // staged new file lands in staged only, not here
162        let mut workdir = self
163            .repo
164            .diff_index_to_workdir(None, Some(&mut workdir_diff_options(self.context_lines)))?;
165        let workdir_model = diff_to_model(&self.repo, &mut workdir)?;
166        let (untracked, unstaged): (Vec<_>, Vec<_>) = workdir_model
167            .files
168            .into_iter()
169            .partition(|f| f.status == FileStatus::Untracked);
170
171        let head_tree = self.head_tree()?;
172        let mut opts = git2::DiffOptions::new();
173        opts.context_lines(self.context_lines);
174        let mut staged = self
175            .repo
176            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
177        let staged = diff_to_model(&self.repo, &mut staged)?;
178
179        Ok(StatusModel {
180            untracked: DiffModel { files: untracked },
181            unstaged: DiffModel { files: unstaged },
182            staged,
183        })
184    }
185
186    fn working_tree_diff(&self) -> Result<DiffModel, VcsError> {
187        self.workdir_diff(self.head_tree()?.as_ref())
188    }
189
190    fn tree_to_workdir_diff(&self, base_oid: &str) -> Result<DiffModel, VcsError> {
191        let base = self.repo.find_commit(git2::Oid::from_str(base_oid)?)?;
192        self.workdir_diff(Some(&base.tree()?))
193    }
194
195    fn commit_diff(&self, oid: &str) -> Result<DiffModel, VcsError> {
196        let oid = git2::Oid::from_str(oid)?;
197        let commit = self.repo.find_commit(oid)?;
198        let tree = commit.tree()?;
199        // root commit: first-parent tree is the empty tree
200        let parent_tree = commit.parent(0).ok().map(|p| p.tree()).transpose()?;
201        let mut opts = git2::DiffOptions::new();
202        opts.context_lines(self.context_lines);
203        let mut diff =
204            self.repo
205                .diff_tree_to_tree(parent_tree.as_ref(), Some(&tree), Some(&mut opts))?;
206        diff_to_model(&self.repo, &mut diff)
207    }
208
209    fn tree_diff(&self, base_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError> {
210        let base = self.repo.find_commit(git2::Oid::from_str(base_oid)?)?;
211        let newest = self.repo.find_commit(git2::Oid::from_str(newest_oid)?)?;
212        let mut opts = git2::DiffOptions::new();
213        opts.context_lines(self.context_lines);
214        let mut diff = self.repo.diff_tree_to_tree(
215            Some(&base.tree()?),
216            Some(&newest.tree()?),
217            Some(&mut opts),
218        )?;
219        diff_to_model(&self.repo, &mut diff)
220    }
221
222    fn merge_base(&self, a: &str, b: &str) -> Result<String, VcsError> {
223        let base = self
224            .repo
225            .merge_base(git2::Oid::from_str(a)?, git2::Oid::from_str(b)?)?;
226        Ok(base.to_string())
227    }
228
229    fn resolve(&self, revision: &str) -> Result<String, VcsError> {
230        let object = self.repo.revparse_single(revision)?;
231        let commit = object.peel_to_commit()?;
232        Ok(commit.id().to_string())
233    }
234
235    fn range_diff(&self, oldest_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError> {
236        let oldest = self.repo.find_commit(git2::Oid::from_str(oldest_oid)?)?;
237        let newest = self.repo.find_commit(git2::Oid::from_str(newest_oid)?)?;
238        let newest_tree = newest.tree()?;
239        // the range starts before the oldest commit, so its base is that
240        // commit's first parent; a root commit has none and diffs against the
241        // empty tree, matching commit_diff
242        let base_tree = oldest.parent(0).ok().map(|p| p.tree()).transpose()?;
243        let mut opts = git2::DiffOptions::new();
244        opts.context_lines(self.context_lines);
245        let mut diff =
246            self.repo
247                .diff_tree_to_tree(base_tree.as_ref(), Some(&newest_tree), Some(&mut opts))?;
248        diff_to_model(&self.repo, &mut diff)
249    }
250
251    fn log(&self, limit: usize) -> Result<Vec<LogEntry>, VcsError> {
252        if self.head_tree()?.is_none() {
253            return Ok(Vec::new());
254        }
255        let mut refs_by_oid: HashMap<git2::Oid, Vec<String>> = HashMap::new();
256        for reference in self.repo.references()?.flatten() {
257            let Ok(name) = reference.shorthand().map(str::to_owned) else {
258                continue;
259            };
260            // peel through symbolic refs and annotated tags to the commit
261            let Some(target) = reference.peel_to_commit().ok().map(|c| c.id()) else {
262                continue;
263            };
264            refs_by_oid.entry(target).or_default().push(name);
265        }
266
267        let mut walk = self.repo.revwalk()?;
268        walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
269        walk.push_head()?;
270        let mut entries = Vec::new();
271        for oid in walk.take(limit) {
272            let oid = oid?;
273            let commit = self.repo.find_commit(oid)?;
274            let full = oid.to_string();
275            entries.push(LogEntry {
276                oid7: short7(&full),
277                oid: full,
278                refs: refs_by_oid.get(&oid).cloned().unwrap_or_default(),
279                subject: commit.summary()?.unwrap_or_default().to_owned(),
280                author: commit.author().name().unwrap_or_default().to_owned(),
281                time_unix: commit.time().seconds(),
282            });
283        }
284        Ok(entries)
285    }
286
287    fn default_branch(&self, remote: &str) -> Result<Option<String>, VcsError> {
288        // the remote's own HEAD is authoritative; it exists once the remote
289        // has been cloned or fetched with `--set-head`
290        let head_ref = format!("refs/remotes/{remote}/HEAD");
291        let prefix = format!("refs/remotes/{remote}/");
292        if let Ok(reference) = self.repo.find_reference(&head_ref)
293            && let Ok(Some(target)) = reference.symbolic_target()
294            // the whole remainder, so a branch named `release/2.x` survives
295            && let Some(name) = target.strip_prefix(prefix.as_str())
296        {
297            return Ok(Some(name.to_owned()));
298        }
299        for name in ["main", "master"] {
300            if self
301                .repo
302                .find_branch(name, git2::BranchType::Local)
303                .or_else(|_| {
304                    self.repo
305                        .find_branch(&format!("{remote}/{name}"), git2::BranchType::Remote)
306                })
307                .is_ok()
308            {
309                return Ok(Some(name.to_owned()));
310            }
311        }
312        Ok(None)
313    }
314
315    fn commits_between(&self, base: &str, head: &str) -> Result<Vec<LogEntry>, VcsError> {
316        let (base, head) = (
317            self.repo.revparse_single(base)?,
318            self.repo.revparse_single(head)?,
319        );
320        let mut walk = self.repo.revwalk()?;
321        walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
322        walk.push(head.id())?;
323        walk.hide(base.id())?;
324        self.walk_entries(walk, usize::MAX)
325    }
326
327    fn unpushed(&self, limit: usize) -> Result<Option<Vec<LogEntry>>, VcsError> {
328        let Ok(head) = self.repo.head() else {
329            return Ok(None);
330        };
331        let mut walk = self.repo.revwalk()?;
332        walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
333        walk.push(head.peel_to_commit()?.id())?;
334        let mut remotes = 0;
335        for reference in self.repo.references()? {
336            let reference = reference?;
337            // a symbolic ref (origin/HEAD) has no target of its own and its
338            // destination is hidden anyway
339            if let (true, Some(oid)) = (reference.is_remote(), reference.target()) {
340                remotes += 1;
341                walk.hide(oid)?;
342            }
343        }
344        if remotes == 0 {
345            return Ok(None);
346        }
347        self.walk_entries(walk, limit).map(Some)
348    }
349
350    fn blame(&self, rel: &Path) -> Result<Vec<BlameSpan>, VcsError> {
351        let mut options = git2::BlameOptions::new();
352        options.track_copies_same_file(true);
353        let blame = self.repo.blame_file(rel, Some(&mut options))?;
354        // blame_file only knows committed content, so an edited worktree would
355        // report the wrong line for everything below the edit; blame_buffer
356        // re-maps the spans onto what is actually on disk.
357        let workdir = self.workdir()?.join(rel);
358        let blame = match fs::read(&workdir) {
359            Ok(bytes) => blame.blame_buffer(&bytes)?,
360            Err(_) => blame,
361        };
362
363        let mut out = Vec::new();
364        for hunk in blame.iter() {
365            let oid = hunk.final_commit_id();
366            let commit = self.repo.find_commit(oid).ok();
367            let full = oid.to_string();
368            out.push(BlameSpan {
369                start_line: u32::try_from(hunk.final_start_line()).unwrap_or(u32::MAX),
370                line_count: u32::try_from(hunk.lines_in_hunk()).unwrap_or(u32::MAX),
371                oid7: short7(&full),
372                oid: full,
373                author: commit
374                    .as_ref()
375                    .map(|c| c.author().name().unwrap_or_default().to_owned())
376                    .unwrap_or_default(),
377                time_unix: commit.as_ref().map_or(0, |c| c.time().seconds()),
378                summary: commit
379                    .as_ref()
380                    .and_then(|c| c.summary().ok().flatten().map(str::to_owned))
381                    .unwrap_or_default(),
382                committed: !oid.is_zero(),
383            });
384        }
385        out.sort_by_key(|span| span.start_line);
386        Ok(out)
387    }
388
389    fn tracked_files(&self) -> Result<Vec<PathBuf>, VcsError> {
390        let index = self.repo.index()?;
391        let mut out: Vec<PathBuf> = index
392            .iter()
393            .filter_map(|entry| {
394                std::str::from_utf8(&entry.path)
395                    .ok()
396                    .map(|path| PathBuf::from(path.to_owned()))
397            })
398            .collect();
399        out.sort_unstable();
400        out.dedup();
401        Ok(out)
402    }
403
404    fn branches(&self) -> Result<Vec<BranchInfo>, VcsError> {
405        let mut out = Vec::new();
406        for entry in self.repo.branches(Some(git2::BranchType::Local))? {
407            let (branch, _) = entry?;
408            let Some(name) = branch.name()?.map(str::to_owned) else {
409                continue;
410            };
411            let tip = branch.get().peel_to_commit().ok();
412            let tip_unix = tip.as_ref().map_or(0, |c| c.time().seconds());
413            let upstream_target = branch.upstream().ok().and_then(|u| u.get().target());
414            let (ahead, behind) = match (&tip, upstream_target) {
415                (Some(tip), Some(target)) => self
416                    .repo
417                    .graph_ahead_behind(tip.id(), target)
418                    .unwrap_or((0, 0)),
419                _ => (0, 0),
420            };
421            out.push(BranchInfo {
422                name,
423                is_head: branch.is_head(),
424                tip_unix,
425                ahead,
426                behind,
427            });
428        }
429        Ok(out)
430    }
431
432    fn all_branches(&self) -> Result<Vec<String>, VcsError> {
433        let mut out = Vec::new();
434        for entry in self.repo.branches(None)? {
435            let (branch, _) = entry?;
436            let Some(name) = branch.name()?.map(str::to_owned) else {
437                continue;
438            };
439            // refs/remotes/<remote>/HEAD is a symbolic alias, not a branch
440            if name.ends_with("/HEAD") {
441                continue;
442            }
443            out.push(name);
444        }
445        Ok(out)
446    }
447
448    fn stage(&self, rel: &Path) -> Result<(), VcsError> {
449        let root = self.workdir_path()?;
450        let mut index = self.repo.index()?;
451        if root.join(rel).exists() {
452            index.add_path(rel)?;
453        } else {
454            index.remove_path(rel)?;
455        }
456        index.write()?;
457        Ok(())
458    }
459
460    fn stage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError> {
461        let diff = self
462            .repo
463            .diff_index_to_workdir(None, Some(&mut workdir_diff_options(self.context_lines)))?;
464        let patch = synthesize_patch(&diff, rel, hunk, false)?;
465        let diff = git2::Diff::from_buffer(&patch)?;
466        self.repo.apply(&diff, git2::ApplyLocation::Index, None)?;
467        Ok(())
468    }
469
470    fn unstage(&self, rel: &Path) -> Result<(), VcsError> {
471        match self.repo.head() {
472            Ok(head) => {
473                let target = head.peel(git2::ObjectType::Commit)?;
474                self.repo.reset_default(Some(&target), [rel])?;
475            }
476            // unborn branch: there is no HEAD entry to restore, drop from index
477            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
478                let mut index = self.repo.index()?;
479                index.remove_path(rel)?;
480                index.write()?;
481            }
482            Err(err) => return Err(err.into()),
483        }
484        Ok(())
485    }
486
487    fn unstage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError> {
488        let head_tree = self.head_tree()?;
489        let mut opts = git2::DiffOptions::new();
490        opts.context_lines(self.context_lines);
491        let diff = self
492            .repo
493            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
494        let patch = synthesize_patch(&diff, rel, hunk, true)?;
495        let diff = git2::Diff::from_buffer(&patch)?;
496        self.repo.apply(&diff, git2::ApplyLocation::Index, None)?;
497        Ok(())
498    }
499
500    fn discard(&self, rel: &Path) -> Result<(), VcsError> {
501        let head_tree = self.head_tree()?;
502        let mut opts = git2::DiffOptions::new();
503        opts.pathspec(rel).disable_pathspec_match(true);
504        let staged = self
505            .repo
506            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
507        if staged.deltas().len() > 0 {
508            return Err(VcsError::Rejected(
509                "file has staged changes; unstage first".into(),
510            ));
511        }
512        let status = self.repo.status_file(rel)?;
513        if status.contains(git2::Status::WT_NEW) {
514            fs::remove_file(self.workdir_path()?.join(rel))?;
515            return Ok(());
516        }
517        // refresh the index stat cache to match the file we just wrote. with
518        // autocrlf the checkout smudges LF->CRLF, growing the file; leaving the
519        // cached stat stale makes git report a phantom modification (size
520        // mismatch defeats the racy-clean check) even though the content is
521        // identical to HEAD. the file has no staged changes here, so the index
522        // blob already equals HEAD and updating it only corrects the metadata.
523        let mut checkout = git2::build::CheckoutBuilder::new();
524        checkout.path(rel).force().update_index(true);
525        self.repo.checkout_head(Some(&mut checkout))?;
526        Ok(())
527    }
528
529    fn commit(&self, message: &str) -> Result<String, VcsError> {
530        if message.trim().is_empty() {
531            return Err(VcsError::Rejected("empty commit message".into()));
532        }
533        let mut index = self.repo.index()?;
534        let tree_id = index.write_tree()?;
535        let tree = self.repo.find_tree(tree_id)?;
536        let signature = self.repo.signature()?;
537        let parent = match self.repo.head() {
538            Ok(head) => Some(head.peel_to_commit()?),
539            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => None,
540            Err(err) => return Err(err.into()),
541        };
542        let parents: Vec<&git2::Commit<'_>> = parent.iter().collect();
543        let oid = self.repo.commit(
544            Some("HEAD"),
545            &signature,
546            &signature,
547            message,
548            &tree,
549            &parents,
550        )?;
551        Ok(oid.to_string())
552    }
553
554    fn head_message(&self) -> Result<String, VcsError> {
555        let commit = self.repo.head()?.peel_to_commit()?;
556        Ok(commit.message().unwrap_or_default().to_owned())
557    }
558
559    fn amend(&self, message: Option<&str>, use_index: bool) -> Result<String, VcsError> {
560        if let Some(message) = message
561            && message.trim().is_empty()
562        {
563            return Err(VcsError::Rejected("empty commit message".into()));
564        }
565        let head = self.repo.head()?.peel_to_commit()?;
566        // extend/amend fold the staged index into the new tree; a pure reword
567        // keeps HEAD's tree so only the message changes
568        let tree = if use_index {
569            let mut index = self.repo.index()?;
570            let tree_id = index.write_tree()?;
571            self.repo.find_tree(tree_id)?
572        } else {
573            head.tree()?
574        };
575        let oid = head.amend(Some("HEAD"), None, None, None, message, Some(&tree))?;
576        Ok(oid.to_string())
577    }
578
579    fn create_branch(&self, name: &str, checkout: bool) -> Result<(), VcsError> {
580        let head = self.repo.head()?.peel_to_commit()?;
581        self.repo.branch(name, &head, false)?;
582        if checkout {
583            self.checkout(name)?;
584        }
585        Ok(())
586    }
587
588    fn delete_branch(&self, name: &str) -> Result<(), VcsError> {
589        let mut branch = self.repo.find_branch(name, git2::BranchType::Local)?;
590        if branch.is_head() {
591            return Err(VcsError::Rejected(
592                "cannot delete the checked-out branch".into(),
593            ));
594        }
595        branch.delete()?;
596        Ok(())
597    }
598
599    fn checkout(&self, name: &str) -> Result<(), VcsError> {
600        let branch = self.repo.find_branch(name, git2::BranchType::Local)?;
601        let target = branch.get().peel(git2::ObjectType::Commit)?;
602        // safe (non-force) checkout: refuses to clobber local modifications
603        self.repo.checkout_tree(&target, None)?;
604        self.repo.set_head(&format!("refs/heads/{name}"))?;
605        Ok(())
606    }
607
608    fn stash_push(&self, message: Option<&str>) -> Result<(), VcsError> {
609        if !self.has_tracked_changes()? {
610            return Err(VcsError::Rejected("nothing to stash".into()));
611        }
612        // git2 stash mutates the repo, but the trait is &self; a fresh handle on
613        // the same workdir gives the &mut without threading mutability everywhere
614        let mut repo = git2::Repository::open(self.workdir_path()?)?;
615        let signature = repo.signature()?;
616        repo.stash_save2(&signature, message, None)?;
617        Ok(())
618    }
619
620    fn stash_pop(&self) -> Result<(), VcsError> {
621        let mut repo = git2::Repository::open(self.workdir_path()?)?;
622        match repo.stash_pop(0, None) {
623            Ok(()) => Ok(()),
624            Err(err) if err.code() == git2::ErrorCode::NotFound => {
625                Err(VcsError::Rejected("no stash to pop".into()))
626            }
627            // a conflicting pop leaves the merge in the worktree and keeps the
628            // stash entry; say so rather than surfacing a bare libgit2 error
629            Err(err) if err.code() == git2::ErrorCode::Conflict => Err(VcsError::Rejected(
630                "stash applied with conflicts; resolve them (the stash was kept)".into(),
631            )),
632            Err(err) => Err(err.into()),
633        }
634    }
635
636    fn network_argv(&self, op: NetworkOp) -> Vec<String> {
637        // shelling to `git` (not git2) so the user's credential helper, SSH
638        // agent, and config drive auth
639        let args: &[&str] = match op {
640            NetworkOp::Fetch => &["fetch"],
641            NetworkOp::FetchAll => &["fetch", "--all"],
642        };
643        std::iter::once("git")
644            .chain(args.iter().copied())
645            .map(str::to_owned)
646            .collect()
647    }
648
649    fn workdir(&self) -> Result<PathBuf, VcsError> {
650        Ok(self.workdir_path()?.to_path_buf())
651    }
652
653    fn remote_url(&self, name: &str) -> Result<Option<String>, VcsError> {
654        match self.repo.find_remote(name) {
655            // url() errs only on a non-UTF-8 remote URL; treat that as no URL
656            Ok(remote) => Ok(remote.url().ok().map(str::to_owned)),
657            Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
658            Err(err) => Err(err.into()),
659        }
660    }
661
662    fn remotes(&self) -> Result<Vec<String>, VcsError> {
663        let array = self.repo.remotes()?;
664        let mut names = Vec::new();
665        for i in 0..array.len() {
666            if let Ok(Some(name)) = array.get(i) {
667                names.push(name.to_owned());
668            }
669        }
670        Ok(names)
671    }
672}
673
674/// Render one hunk of `rel` as a unified patch libgit2 can apply to the
675/// index. `reverse` flips the patch so applying it undoes a staged hunk.
676/// Built from the raw git2 patch lines (not the display model) so original
677/// line endings and missing-trailing-newline markers survive intact.
678fn synthesize_patch(
679    diff: &git2::Diff<'_>,
680    rel: &Path,
681    target: &HunkId,
682    reverse: bool,
683) -> Result<Vec<u8>, VcsError> {
684    let rel = rel.to_string_lossy();
685    for idx in 0..diff.deltas().len() {
686        let Some(patch) = git2::Patch::from_diff(diff, idx)? else {
687            continue;
688        };
689        let delta = patch.delta();
690        if delta.flags().is_binary() || delta_new_path(&delta) != rel {
691            continue;
692        }
693        for h in 0..patch.num_hunks() {
694            if hunk_id(&rel, &hunk_model_lines(&patch, h)?) == *target {
695                return render_hunk_patch(&patch, h, &rel, delta.status(), reverse);
696            }
697        }
698    }
699    Err(VcsError::Rejected("hunk not found (diff changed?)".into()))
700}
701
702fn render_hunk_patch(
703    patch: &git2::Patch<'_>,
704    h: usize,
705    rel: &str,
706    status: git2::Delta,
707    reverse: bool,
708) -> Result<Vec<u8>, VcsError> {
709    let added = matches!(status, git2::Delta::Added | git2::Delta::Untracked);
710    let deleted = status == git2::Delta::Deleted;
711    let mut out = Vec::new();
712    out.extend_from_slice(format!("diff --git a/{rel} b/{rel}\n").as_bytes());
713    // whole-file adds and deletes must keep that identity (with the sides
714    // swapped under reverse) so applying creates or drops the index entry
715    // instead of leaving an empty blob behind
716    if (added && !reverse) || (deleted && reverse) {
717        out.extend_from_slice(
718            format!("new file mode 100644\n--- /dev/null\n+++ b/{rel}\n").as_bytes(),
719        );
720    } else if (deleted && !reverse) || (added && reverse) {
721        out.extend_from_slice(
722            format!("deleted file mode 100644\n--- a/{rel}\n+++ /dev/null\n").as_bytes(),
723        );
724    } else {
725        out.extend_from_slice(format!("--- a/{rel}\n+++ b/{rel}\n").as_bytes());
726    }
727    let (hunk, line_count) = patch.hunk(h)?;
728    let (old, new) = (
729        (hunk.old_start(), hunk.old_lines()),
730        (hunk.new_start(), hunk.new_lines()),
731    );
732    let ((minus_start, minus_lines), (plus_start, plus_lines)) =
733        if reverse { (new, old) } else { (old, new) };
734    out.extend_from_slice(
735        format!("@@ -{minus_start},{minus_lines} +{plus_start},{plus_lines} @@\n").as_bytes(),
736    );
737    for l in 0..line_count {
738        let line = patch.line_in_hunk(h, l)?;
739        let origin = match (line.origin(), reverse) {
740            (' ', _) => Some(b' '),
741            ('+', false) | ('-', true) => Some(b'+'),
742            ('-', false) | ('+', true) => Some(b'-'),
743            // EOF-newline markers already carry the full "\ No newline at
744            // end of file" text, including the newline that terminates the
745            // preceding unterminated line, so they pass through unprefixed
746            ('=' | '>' | '<', _) => None,
747            _ => continue,
748        };
749        if let Some(origin) = origin {
750            out.push(origin);
751        }
752        out.extend_from_slice(line.content());
753    }
754    Ok(out)
755}
756
757fn workdir_diff_options(context_lines: u32) -> git2::DiffOptions {
758    let mut opts = git2::DiffOptions::new();
759    opts.include_untracked(true)
760        .recurse_untracked_dirs(true)
761        .show_untracked_content(true)
762        .context_lines(context_lines);
763    opts
764}
765
766fn short7(oid: &str) -> String {
767    oid.get(..7).unwrap_or(oid).to_owned()
768}
769
770fn diff_to_model(
771    repo: &git2::Repository,
772    diff: &mut git2::Diff<'_>,
773) -> Result<DiffModel, VcsError> {
774    let mut files = Vec::new();
775    for idx in 0..diff.deltas().len() {
776        if let Some(file) = build_file(repo, diff, idx)? {
777            files.push(file);
778        }
779    }
780    // intra-line emphasis is a render-time concern: the TUI enriches the
781    // file it is about to draw (see crate::pairing::enrich_file), so the
782    // backend leaves `.emphasis` empty.
783    Ok(DiffModel { files })
784}
785
786fn build_file(
787    repo: &git2::Repository,
788    diff: &mut git2::Diff<'_>,
789    idx: usize,
790) -> Result<Option<FileDiff>, VcsError> {
791    let Some(patch) = git2::Patch::from_diff(diff, idx)? else {
792        // binary or unreadable: fall back to delta metadata only
793        return Ok(build_binary_file(diff, idx));
794    };
795    let delta = patch.delta();
796    if delta.flags().is_binary() {
797        return Ok(build_binary_file(diff, idx));
798    }
799    let file_path = delta_new_path(&delta);
800    let status = map_status(delta.status());
801    let old_path = if status == FileStatus::Renamed {
802        delta
803            .old_file()
804            .path()
805            .map(|p| p.to_string_lossy().into_owned())
806    } else {
807        None
808    };
809
810    let old_text = blob_text(repo, delta.old_file().id());
811    let new_text = new_side_text(repo, &delta, &file_path);
812
813    let hunks = patch_hunks(&patch, &file_path)?;
814
815    Ok(Some(FileDiff {
816        path: file_path,
817        old_path,
818        status,
819        binary: false,
820        old_text,
821        new_text,
822        hunks,
823        hashes: crate::model::HashCache::default(),
824    }))
825}
826
827/// Re-diff a file's own old/new text at `context` lines of surrounding context
828/// (`u32::MAX` for the whole file), yielding the hunks the diff pane would show
829/// at that context. `None` for binary files or when a side's text is absent, so
830/// the caller keeps its current hunks.
831pub fn rehunk_file(file: &FileDiff, context: u32) -> Option<Vec<Hunk>> {
832    if file.binary {
833        return None;
834    }
835    let (old, new) = (file.old_text.as_deref()?, file.new_text.as_deref()?);
836    let as_path = Path::new(&file.path);
837    // libgit2's context math overflows on a huge value (the whole-file
838    // sentinel u32::MAX), yielding zero context on some platforms; the line
839    // count is enough to show the whole file and stays in range everywhere
840    let cap = u32::try_from(old.lines().count().max(new.lines().count())).unwrap_or(u32::MAX);
841    let mut opts = git2::DiffOptions::new();
842    opts.context_lines(context.min(cap));
843    let patch = git2::Patch::from_buffers(
844        old.as_bytes(),
845        Some(as_path),
846        new.as_bytes(),
847        Some(as_path),
848        Some(&mut opts),
849    )
850    .ok()?;
851    patch_hunks(&patch, &file.path).ok()
852}
853
854/// Assemble model hunks from a git2 patch. Shared by the initial diff and the
855/// context re-diff so line numbers, ids, and section headings can't drift.
856fn patch_hunks(patch: &git2::Patch<'_>, file_path: &str) -> Result<Vec<Hunk>, VcsError> {
857    let mut hunks = Vec::with_capacity(patch.num_hunks());
858    for h in 0..patch.num_hunks() {
859        let (hunk, _) = patch.hunk(h)?;
860        let lines = hunk_model_lines(patch, h)?;
861        let id = hunk_id(file_path, &lines);
862        hunks.push(Hunk {
863            id,
864            old_start: hunk.old_start(),
865            old_lines: hunk.old_lines(),
866            new_start: hunk.new_start(),
867            new_lines: hunk.new_lines(),
868            context: hunk_context(&hunk),
869            lines,
870        });
871    }
872    Ok(hunks)
873}
874
875/// git's section heading for a hunk: the text git appends after the second
876/// `@@` of the header (`@@ -a,b +c,d @@ <context>`), typically the enclosing
877/// function or section. Empty when git emits none (e.g. a top-of-file hunk).
878fn hunk_context(hunk: &git2::DiffHunk<'_>) -> String {
879    let header = String::from_utf8_lossy(hunk.header());
880    match header.split_once(" @@") {
881        Some((_, rest)) => rest.trim_matches(['\n', '\r', ' ']).to_owned(),
882        None => String::new(),
883    }
884}
885
886/// Content lines of one hunk as model lines (headers and EOF-newline markers
887/// excluded). Shared by model building and hunk lookup so the hunk ids
888/// computed in both places agree.
889fn hunk_model_lines(patch: &git2::Patch<'_>, h: usize) -> Result<Vec<DiffLine>, VcsError> {
890    let (_, line_count) = patch.hunk(h)?;
891    let mut lines = Vec::with_capacity(line_count);
892    for l in 0..line_count {
893        let line = patch.line_in_hunk(h, l)?;
894        let kind = match line.origin() {
895            '-' => LineKind::Deleted,
896            '+' => LineKind::Added,
897            ' ' => LineKind::Context,
898            // headers, EOF-newline markers etc. are not content lines
899            _ => continue,
900        };
901        let text = String::from_utf8_lossy(line.content())
902            .trim_end_matches(['\n', '\r'])
903            .to_owned();
904        lines.push(DiffLine::new(
905            kind,
906            line.old_lineno(),
907            line.new_lineno(),
908            text,
909        ));
910    }
911    Ok(lines)
912}
913
914fn build_binary_file(diff: &git2::Diff<'_>, idx: usize) -> Option<FileDiff> {
915    let delta = diff.get_delta(idx)?;
916    Some(FileDiff {
917        path: delta_new_path(&delta),
918        old_path: None,
919        status: map_status(delta.status()),
920        binary: true,
921        old_text: None,
922        new_text: None,
923        hunks: Vec::new(),
924        hashes: crate::model::HashCache::default(),
925    })
926}
927
928fn delta_new_path(delta: &git2::DiffDelta<'_>) -> String {
929    delta
930        .new_file()
931        .path()
932        .or_else(|| delta.old_file().path())
933        .map(|p| p.to_string_lossy().into_owned())
934        .unwrap_or_default()
935}
936
937fn map_status(status: git2::Delta) -> FileStatus {
938    match status {
939        git2::Delta::Added => FileStatus::Added,
940        git2::Delta::Deleted => FileStatus::Deleted,
941        git2::Delta::Renamed => FileStatus::Renamed,
942        git2::Delta::Untracked => FileStatus::Untracked,
943        _ => FileStatus::Modified,
944    }
945}
946
947fn blob_text(repo: &git2::Repository, oid: git2::Oid) -> Option<String> {
948    if oid.is_zero() {
949        return None;
950    }
951    let blob = repo.find_blob(oid).ok()?;
952    if blob.is_binary() {
953        return None;
954    }
955    String::from_utf8(blob.content().to_vec()).ok()
956}
957
958/// New-side content: the recorded blob when the diff target is a tree or the
959/// index (where the workdir may differ), the workdir file otherwise.
960fn new_side_text(
961    repo: &git2::Repository,
962    delta: &git2::DiffDelta<'_>,
963    rel: &str,
964) -> Option<String> {
965    if delta.status() == git2::Delta::Deleted {
966        return None;
967    }
968    if let Some(text) = blob_text(repo, delta.new_file().id()) {
969        return Some(text);
970    }
971    let root = repo.workdir()?;
972    fs::read_to_string(root.join(rel)).ok()
973}