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 stage_everything(&self) -> Result<(), VcsError> {
471        let mut index = self.repo.index()?;
472        // update_all catches deletions and edits to files already tracked;
473        // add_all then picks up whatever is untracked
474        index.update_all(["*"], None)?;
475        index.add_all(["*"], git2::IndexAddOption::DEFAULT, None)?;
476        index.write()?;
477        Ok(())
478    }
479
480    fn unstage_everything(&self) -> Result<(), VcsError> {
481        match self.repo.head() {
482            Ok(head) => {
483                let target = head.peel(git2::ObjectType::Commit)?;
484                self.repo.reset_default(Some(&target), ["*"])?;
485            }
486            // unborn branch: nothing in HEAD to restore, so empty the index
487            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
488                let mut index = self.repo.index()?;
489                index.clear()?;
490                index.write()?;
491            }
492            Err(err) => return Err(err.into()),
493        }
494        Ok(())
495    }
496
497    fn unstage(&self, rel: &Path) -> Result<(), VcsError> {
498        match self.repo.head() {
499            Ok(head) => {
500                let target = head.peel(git2::ObjectType::Commit)?;
501                self.repo.reset_default(Some(&target), [rel])?;
502            }
503            // unborn branch: there is no HEAD entry to restore, drop from index
504            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
505                let mut index = self.repo.index()?;
506                index.remove_path(rel)?;
507                index.write()?;
508            }
509            Err(err) => return Err(err.into()),
510        }
511        Ok(())
512    }
513
514    fn unstage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError> {
515        let head_tree = self.head_tree()?;
516        let mut opts = git2::DiffOptions::new();
517        opts.context_lines(self.context_lines);
518        let diff = self
519            .repo
520            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
521        let patch = synthesize_patch(&diff, rel, hunk, true)?;
522        let diff = git2::Diff::from_buffer(&patch)?;
523        self.repo.apply(&diff, git2::ApplyLocation::Index, None)?;
524        Ok(())
525    }
526
527    fn discard(&self, rel: &Path) -> Result<(), VcsError> {
528        let head_tree = self.head_tree()?;
529        let mut opts = git2::DiffOptions::new();
530        opts.pathspec(rel).disable_pathspec_match(true);
531        let staged = self
532            .repo
533            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
534        if staged.deltas().len() > 0 {
535            return Err(VcsError::Rejected(
536                "file has staged changes; unstage first".into(),
537            ));
538        }
539        let status = self.repo.status_file(rel)?;
540        if status.contains(git2::Status::WT_NEW) {
541            fs::remove_file(self.workdir_path()?.join(rel))?;
542            return Ok(());
543        }
544        // refresh the index stat cache to match the file we just wrote. with
545        // autocrlf the checkout smudges LF->CRLF, growing the file; leaving the
546        // cached stat stale makes git report a phantom modification (size
547        // mismatch defeats the racy-clean check) even though the content is
548        // identical to HEAD. the file has no staged changes here, so the index
549        // blob already equals HEAD and updating it only corrects the metadata.
550        let mut checkout = git2::build::CheckoutBuilder::new();
551        checkout.path(rel).force().update_index(true);
552        self.repo.checkout_head(Some(&mut checkout))?;
553        Ok(())
554    }
555
556    fn commit(&self, message: &str) -> Result<String, VcsError> {
557        if message.trim().is_empty() {
558            return Err(VcsError::Rejected("empty commit message".into()));
559        }
560        let mut index = self.repo.index()?;
561        let tree_id = index.write_tree()?;
562        let tree = self.repo.find_tree(tree_id)?;
563        let signature = self.repo.signature()?;
564        let parent = match self.repo.head() {
565            Ok(head) => Some(head.peel_to_commit()?),
566            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => None,
567            Err(err) => return Err(err.into()),
568        };
569        let parents: Vec<&git2::Commit<'_>> = parent.iter().collect();
570        let oid = self.repo.commit(
571            Some("HEAD"),
572            &signature,
573            &signature,
574            message,
575            &tree,
576            &parents,
577        )?;
578        Ok(oid.to_string())
579    }
580
581    fn head_message(&self) -> Result<String, VcsError> {
582        let commit = self.repo.head()?.peel_to_commit()?;
583        Ok(commit.message().unwrap_or_default().to_owned())
584    }
585
586    fn amend(&self, message: Option<&str>, use_index: bool) -> Result<String, VcsError> {
587        if let Some(message) = message
588            && message.trim().is_empty()
589        {
590            return Err(VcsError::Rejected("empty commit message".into()));
591        }
592        let head = self.repo.head()?.peel_to_commit()?;
593        // extend/amend fold the staged index into the new tree; a pure reword
594        // keeps HEAD's tree so only the message changes
595        let tree = if use_index {
596            let mut index = self.repo.index()?;
597            let tree_id = index.write_tree()?;
598            self.repo.find_tree(tree_id)?
599        } else {
600            head.tree()?
601        };
602        let oid = head.amend(Some("HEAD"), None, None, None, message, Some(&tree))?;
603        Ok(oid.to_string())
604    }
605
606    fn create_branch(&self, name: &str, checkout: bool) -> Result<(), VcsError> {
607        let head = self.repo.head()?.peel_to_commit()?;
608        self.repo.branch(name, &head, false)?;
609        if checkout {
610            self.checkout(name)?;
611        }
612        Ok(())
613    }
614
615    fn delete_branch(&self, name: &str) -> Result<(), VcsError> {
616        let mut branch = self.repo.find_branch(name, git2::BranchType::Local)?;
617        if branch.is_head() {
618            return Err(VcsError::Rejected(
619                "cannot delete the checked-out branch".into(),
620            ));
621        }
622        branch.delete()?;
623        Ok(())
624    }
625
626    fn checkout(&self, name: &str) -> Result<(), VcsError> {
627        let branch = self.repo.find_branch(name, git2::BranchType::Local)?;
628        let target = branch.get().peel(git2::ObjectType::Commit)?;
629        // safe (non-force) checkout: refuses to clobber local modifications
630        self.repo.checkout_tree(&target, None)?;
631        self.repo.set_head(&format!("refs/heads/{name}"))?;
632        Ok(())
633    }
634
635    fn stash_push(&self, message: Option<&str>) -> Result<(), VcsError> {
636        if !self.has_tracked_changes()? {
637            return Err(VcsError::Rejected("nothing to stash".into()));
638        }
639        // git2 stash mutates the repo, but the trait is &self; a fresh handle on
640        // the same workdir gives the &mut without threading mutability everywhere
641        let mut repo = git2::Repository::open(self.workdir_path()?)?;
642        let signature = repo.signature()?;
643        repo.stash_save2(&signature, message, None)?;
644        Ok(())
645    }
646
647    fn stash_pop(&self) -> Result<(), VcsError> {
648        let mut repo = git2::Repository::open(self.workdir_path()?)?;
649        match repo.stash_pop(0, None) {
650            Ok(()) => Ok(()),
651            Err(err) if err.code() == git2::ErrorCode::NotFound => {
652                Err(VcsError::Rejected("no stash to pop".into()))
653            }
654            // a conflicting pop leaves the merge in the worktree and keeps the
655            // stash entry; say so rather than surfacing a bare libgit2 error
656            Err(err) if err.code() == git2::ErrorCode::Conflict => Err(VcsError::Rejected(
657                "stash applied with conflicts; resolve them (the stash was kept)".into(),
658            )),
659            Err(err) => Err(err.into()),
660        }
661    }
662
663    fn network_argv(&self, op: NetworkOp) -> Vec<String> {
664        // shelling to `git` (not git2) so the user's credential helper, SSH
665        // agent, and config drive auth
666        let args: &[&str] = match op {
667            NetworkOp::Fetch => &["fetch"],
668            NetworkOp::FetchAll => &["fetch", "--all"],
669        };
670        std::iter::once("git")
671            .chain(args.iter().copied())
672            .map(str::to_owned)
673            .collect()
674    }
675
676    fn workdir(&self) -> Result<PathBuf, VcsError> {
677        Ok(self.workdir_path()?.to_path_buf())
678    }
679
680    fn remote_url(&self, name: &str) -> Result<Option<String>, VcsError> {
681        match self.repo.find_remote(name) {
682            // url() errs only on a non-UTF-8 remote URL; treat that as no URL
683            Ok(remote) => Ok(remote.url().ok().map(str::to_owned)),
684            Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
685            Err(err) => Err(err.into()),
686        }
687    }
688
689    fn remotes(&self) -> Result<Vec<String>, VcsError> {
690        let array = self.repo.remotes()?;
691        let mut names = Vec::new();
692        for i in 0..array.len() {
693            if let Ok(Some(name)) = array.get(i) {
694                names.push(name.to_owned());
695            }
696        }
697        Ok(names)
698    }
699}
700
701/// Render one hunk of `rel` as a unified patch libgit2 can apply to the
702/// index. `reverse` flips the patch so applying it undoes a staged hunk.
703/// Built from the raw git2 patch lines (not the display model) so original
704/// line endings and missing-trailing-newline markers survive intact.
705fn synthesize_patch(
706    diff: &git2::Diff<'_>,
707    rel: &Path,
708    target: &HunkId,
709    reverse: bool,
710) -> Result<Vec<u8>, VcsError> {
711    let rel = rel.to_string_lossy();
712    for idx in 0..diff.deltas().len() {
713        let Some(patch) = git2::Patch::from_diff(diff, idx)? else {
714            continue;
715        };
716        let delta = patch.delta();
717        if delta.flags().is_binary() || delta_new_path(&delta) != rel {
718            continue;
719        }
720        for h in 0..patch.num_hunks() {
721            if hunk_id(&rel, &hunk_model_lines(&patch, h)?) == *target {
722                return render_hunk_patch(&patch, h, &rel, delta.status(), reverse);
723            }
724        }
725    }
726    Err(VcsError::Rejected("hunk not found (diff changed?)".into()))
727}
728
729fn render_hunk_patch(
730    patch: &git2::Patch<'_>,
731    h: usize,
732    rel: &str,
733    status: git2::Delta,
734    reverse: bool,
735) -> Result<Vec<u8>, VcsError> {
736    let added = matches!(status, git2::Delta::Added | git2::Delta::Untracked);
737    let deleted = status == git2::Delta::Deleted;
738    let mut out = Vec::new();
739    out.extend_from_slice(format!("diff --git a/{rel} b/{rel}\n").as_bytes());
740    // whole-file adds and deletes must keep that identity (with the sides
741    // swapped under reverse) so applying creates or drops the index entry
742    // instead of leaving an empty blob behind
743    if (added && !reverse) || (deleted && reverse) {
744        out.extend_from_slice(
745            format!("new file mode 100644\n--- /dev/null\n+++ b/{rel}\n").as_bytes(),
746        );
747    } else if (deleted && !reverse) || (added && reverse) {
748        out.extend_from_slice(
749            format!("deleted file mode 100644\n--- a/{rel}\n+++ /dev/null\n").as_bytes(),
750        );
751    } else {
752        out.extend_from_slice(format!("--- a/{rel}\n+++ b/{rel}\n").as_bytes());
753    }
754    let (hunk, line_count) = patch.hunk(h)?;
755    let (old, new) = (
756        (hunk.old_start(), hunk.old_lines()),
757        (hunk.new_start(), hunk.new_lines()),
758    );
759    let ((minus_start, minus_lines), (plus_start, plus_lines)) =
760        if reverse { (new, old) } else { (old, new) };
761    out.extend_from_slice(
762        format!("@@ -{minus_start},{minus_lines} +{plus_start},{plus_lines} @@\n").as_bytes(),
763    );
764    for l in 0..line_count {
765        let line = patch.line_in_hunk(h, l)?;
766        let origin = match (line.origin(), reverse) {
767            (' ', _) => Some(b' '),
768            ('+', false) | ('-', true) => Some(b'+'),
769            ('-', false) | ('+', true) => Some(b'-'),
770            // EOF-newline markers already carry the full "\ No newline at
771            // end of file" text, including the newline that terminates the
772            // preceding unterminated line, so they pass through unprefixed
773            ('=' | '>' | '<', _) => None,
774            _ => continue,
775        };
776        if let Some(origin) = origin {
777            out.push(origin);
778        }
779        out.extend_from_slice(line.content());
780    }
781    Ok(out)
782}
783
784fn workdir_diff_options(context_lines: u32) -> git2::DiffOptions {
785    let mut opts = git2::DiffOptions::new();
786    opts.include_untracked(true)
787        .recurse_untracked_dirs(true)
788        .show_untracked_content(true)
789        .context_lines(context_lines);
790    opts
791}
792
793fn short7(oid: &str) -> String {
794    oid.get(..7).unwrap_or(oid).to_owned()
795}
796
797fn diff_to_model(
798    repo: &git2::Repository,
799    diff: &mut git2::Diff<'_>,
800) -> Result<DiffModel, VcsError> {
801    let mut files = Vec::new();
802    for idx in 0..diff.deltas().len() {
803        if let Some(file) = build_file(repo, diff, idx)? {
804            files.push(file);
805        }
806    }
807    // intra-line emphasis is a render-time concern: the TUI enriches the
808    // file it is about to draw (see crate::pairing::enrich_file), so the
809    // backend leaves `.emphasis` empty.
810    Ok(DiffModel { files })
811}
812
813fn build_file(
814    repo: &git2::Repository,
815    diff: &mut git2::Diff<'_>,
816    idx: usize,
817) -> Result<Option<FileDiff>, VcsError> {
818    let Some(patch) = git2::Patch::from_diff(diff, idx)? else {
819        // binary or unreadable: fall back to delta metadata only
820        return Ok(build_binary_file(diff, idx));
821    };
822    let delta = patch.delta();
823    if delta.flags().is_binary() {
824        return Ok(build_binary_file(diff, idx));
825    }
826    let file_path = delta_new_path(&delta);
827    let status = map_status(delta.status());
828    let old_path = if status == FileStatus::Renamed {
829        delta
830            .old_file()
831            .path()
832            .map(|p| p.to_string_lossy().into_owned())
833    } else {
834        None
835    };
836
837    let old_text = blob_text(repo, delta.old_file().id());
838    let new_text = new_side_text(repo, &delta, &file_path);
839
840    let hunks = patch_hunks(&patch, &file_path)?;
841
842    Ok(Some(FileDiff {
843        path: file_path,
844        old_path,
845        status,
846        binary: false,
847        old_text,
848        new_text,
849        hunks,
850        hashes: crate::model::HashCache::default(),
851    }))
852}
853
854/// Re-diff a file's own old/new text at `context` lines of surrounding context
855/// (`u32::MAX` for the whole file), yielding the hunks the diff pane would show
856/// at that context. `None` for binary files or when a side's text is absent, so
857/// the caller keeps its current hunks.
858pub fn rehunk_file(file: &FileDiff, context: u32) -> Option<Vec<Hunk>> {
859    if file.binary {
860        return None;
861    }
862    let (old, new) = (file.old_text.as_deref()?, file.new_text.as_deref()?);
863    let as_path = Path::new(&file.path);
864    // libgit2's context math overflows on a huge value (the whole-file
865    // sentinel u32::MAX), yielding zero context on some platforms; the line
866    // count is enough to show the whole file and stays in range everywhere
867    let cap = u32::try_from(old.lines().count().max(new.lines().count())).unwrap_or(u32::MAX);
868    let mut opts = git2::DiffOptions::new();
869    opts.context_lines(context.min(cap));
870    let patch = git2::Patch::from_buffers(
871        old.as_bytes(),
872        Some(as_path),
873        new.as_bytes(),
874        Some(as_path),
875        Some(&mut opts),
876    )
877    .ok()?;
878    patch_hunks(&patch, &file.path).ok()
879}
880
881/// Assemble model hunks from a git2 patch. Shared by the initial diff and the
882/// context re-diff so line numbers, ids, and section headings can't drift.
883fn patch_hunks(patch: &git2::Patch<'_>, file_path: &str) -> Result<Vec<Hunk>, VcsError> {
884    let mut hunks = Vec::with_capacity(patch.num_hunks());
885    for h in 0..patch.num_hunks() {
886        let (hunk, _) = patch.hunk(h)?;
887        let lines = hunk_model_lines(patch, h)?;
888        let id = hunk_id(file_path, &lines);
889        hunks.push(Hunk {
890            id,
891            old_start: hunk.old_start(),
892            old_lines: hunk.old_lines(),
893            new_start: hunk.new_start(),
894            new_lines: hunk.new_lines(),
895            context: hunk_context(&hunk),
896            lines,
897        });
898    }
899    Ok(hunks)
900}
901
902/// git's section heading for a hunk: the text git appends after the second
903/// `@@` of the header (`@@ -a,b +c,d @@ <context>`), typically the enclosing
904/// function or section. Empty when git emits none (e.g. a top-of-file hunk).
905fn hunk_context(hunk: &git2::DiffHunk<'_>) -> String {
906    let header = String::from_utf8_lossy(hunk.header());
907    match header.split_once(" @@") {
908        Some((_, rest)) => rest.trim_matches(['\n', '\r', ' ']).to_owned(),
909        None => String::new(),
910    }
911}
912
913/// Content lines of one hunk as model lines (headers and EOF-newline markers
914/// excluded). Shared by model building and hunk lookup so the hunk ids
915/// computed in both places agree.
916fn hunk_model_lines(patch: &git2::Patch<'_>, h: usize) -> Result<Vec<DiffLine>, VcsError> {
917    let (_, line_count) = patch.hunk(h)?;
918    let mut lines = Vec::with_capacity(line_count);
919    for l in 0..line_count {
920        let line = patch.line_in_hunk(h, l)?;
921        let kind = match line.origin() {
922            '-' => LineKind::Deleted,
923            '+' => LineKind::Added,
924            ' ' => LineKind::Context,
925            // headers, EOF-newline markers etc. are not content lines
926            _ => continue,
927        };
928        let text = String::from_utf8_lossy(line.content())
929            .trim_end_matches(['\n', '\r'])
930            .to_owned();
931        lines.push(DiffLine::new(
932            kind,
933            line.old_lineno(),
934            line.new_lineno(),
935            text,
936        ));
937    }
938    Ok(lines)
939}
940
941fn build_binary_file(diff: &git2::Diff<'_>, idx: usize) -> Option<FileDiff> {
942    let delta = diff.get_delta(idx)?;
943    Some(FileDiff {
944        path: delta_new_path(&delta),
945        old_path: None,
946        status: map_status(delta.status()),
947        binary: true,
948        old_text: None,
949        new_text: None,
950        hunks: Vec::new(),
951        hashes: crate::model::HashCache::default(),
952    })
953}
954
955fn delta_new_path(delta: &git2::DiffDelta<'_>) -> String {
956    delta
957        .new_file()
958        .path()
959        .or_else(|| delta.old_file().path())
960        .map(|p| p.to_string_lossy().into_owned())
961        .unwrap_or_default()
962}
963
964fn map_status(status: git2::Delta) -> FileStatus {
965    match status {
966        git2::Delta::Added => FileStatus::Added,
967        git2::Delta::Deleted => FileStatus::Deleted,
968        git2::Delta::Renamed => FileStatus::Renamed,
969        git2::Delta::Untracked => FileStatus::Untracked,
970        _ => FileStatus::Modified,
971    }
972}
973
974fn blob_text(repo: &git2::Repository, oid: git2::Oid) -> Option<String> {
975    if oid.is_zero() {
976        return None;
977    }
978    let blob = repo.find_blob(oid).ok()?;
979    if blob.is_binary() {
980        return None;
981    }
982    String::from_utf8(blob.content().to_vec()).ok()
983}
984
985/// New-side content: the recorded blob when the diff target is a tree or the
986/// index (where the workdir may differ), the workdir file otherwise.
987fn new_side_text(
988    repo: &git2::Repository,
989    delta: &git2::DiffDelta<'_>,
990    rel: &str,
991) -> Option<String> {
992    if delta.status() == git2::Delta::Deleted {
993        return None;
994    }
995    if let Some(text) = blob_text(repo, delta.new_file().id()) {
996        return Some(text);
997    }
998    let root = repo.workdir()?;
999    fs::read_to_string(root.join(rel)).ok()
1000}