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::{BranchInfo, HeadInfo, LogEntry, NetworkOp, StatusModel, Vcs, VcsError};
10
11/// git's own default amount of context around hunks.
12pub const DEFAULT_CONTEXT_LINES: u32 = 3;
13
14pub struct GitVcs {
15    repo: git2::Repository,
16    context_lines: u32,
17}
18
19impl GitVcs {
20    pub fn open(root: &Path) -> Result<Self, VcsError> {
21        Self::open_with_context(root, DEFAULT_CONTEXT_LINES)
22    }
23
24    /// Open with a custom number of context lines around diff hunks.
25    pub fn open_with_context(root: &Path, context_lines: u32) -> Result<Self, VcsError> {
26        let repo = git2::Repository::open(root)?;
27        if repo.workdir().is_none() {
28            return Err(VcsError::NoWorkdir);
29        }
30        Ok(Self {
31            repo,
32            context_lines,
33        })
34    }
35
36    /// HEAD tree, or `None` on an unborn branch (fresh repo).
37    fn head_tree(&self) -> Result<Option<git2::Tree<'_>>, VcsError> {
38        match self.repo.head() {
39            Ok(head) => Ok(Some(head.peel_to_tree()?)),
40            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => Ok(None),
41            Err(err) => Err(err.into()),
42        }
43    }
44
45    fn workdir_path(&self) -> Result<&Path, VcsError> {
46        self.repo.workdir().ok_or(VcsError::NoWorkdir)
47    }
48
49    /// Whether any tracked file differs from HEAD or the index — i.e. there is
50    /// something `git stash` would save. Untracked files don't count, matching
51    /// stash's default.
52    fn has_tracked_changes(&self) -> Result<bool, VcsError> {
53        let mut opts = git2::StatusOptions::new();
54        opts.include_untracked(false).include_ignored(false);
55        let statuses = self.repo.statuses(Some(&mut opts))?;
56        Ok(statuses.iter().next().is_some())
57    }
58}
59
60impl Vcs for GitVcs {
61    fn git_dir(&self) -> Result<PathBuf, VcsError> {
62        // libgit2 resolves gitlink files, so linked worktrees come back as
63        // their external gitdir under the main repo's .git/worktrees/
64        Ok(self.repo.path().to_path_buf())
65    }
66
67    fn head(&self) -> Result<HeadInfo, VcsError> {
68        match self.repo.head() {
69            Ok(head) => {
70                let branch = if head.is_branch() {
71                    Some(head.shorthand()?.to_owned())
72                } else {
73                    None
74                };
75                let commit = head.peel_to_commit()?;
76                let upstream = branch.as_deref().and_then(|name| {
77                    let local = self.repo.find_branch(name, git2::BranchType::Local).ok()?;
78                    let upstream = local.upstream().ok()?;
79                    upstream.name().ok().flatten().map(str::to_owned)
80                });
81                Ok(HeadInfo {
82                    branch,
83                    oid7: short7(&commit.id().to_string()),
84                    subject: commit.summary()?.unwrap_or_default().to_owned(),
85                    upstream,
86                })
87            }
88            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
89                let branch = self
90                    .repo
91                    .find_reference("HEAD")
92                    .ok()
93                    .and_then(|r| r.symbolic_target().ok().flatten().map(str::to_owned))
94                    .and_then(|t| t.strip_prefix("refs/heads/").map(str::to_owned));
95                Ok(HeadInfo {
96                    branch,
97                    oid7: String::new(),
98                    subject: String::new(),
99                    upstream: None,
100                })
101            }
102            Err(err) => Err(err.into()),
103        }
104    }
105
106    fn status(&self) -> Result<StatusModel, VcsError> {
107        // index vs workdir classifies "untracked" against the index, so a
108        // staged new file lands in staged only, not here
109        let mut workdir = self
110            .repo
111            .diff_index_to_workdir(None, Some(&mut workdir_diff_options(self.context_lines)))?;
112        let workdir_model = diff_to_model(&self.repo, &mut workdir)?;
113        let (untracked, unstaged): (Vec<_>, Vec<_>) = workdir_model
114            .files
115            .into_iter()
116            .partition(|f| f.status == FileStatus::Untracked);
117
118        let head_tree = self.head_tree()?;
119        let mut opts = git2::DiffOptions::new();
120        opts.context_lines(self.context_lines);
121        let mut staged = self
122            .repo
123            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
124        let staged = diff_to_model(&self.repo, &mut staged)?;
125
126        Ok(StatusModel {
127            untracked: DiffModel { files: untracked },
128            unstaged: DiffModel { files: unstaged },
129            staged,
130        })
131    }
132
133    fn working_tree_diff(&self) -> Result<DiffModel, VcsError> {
134        let head_tree = self.head_tree()?;
135        let mut diff = self.repo.diff_tree_to_workdir_with_index(
136            head_tree.as_ref(),
137            Some(&mut workdir_diff_options(self.context_lines)),
138        )?;
139        let mut find = git2::DiffFindOptions::new();
140        find.renames(true);
141        diff.find_similar(Some(&mut find))?;
142        diff_to_model(&self.repo, &mut diff)
143    }
144
145    fn commit_diff(&self, oid: &str) -> Result<DiffModel, VcsError> {
146        let oid = git2::Oid::from_str(oid)?;
147        let commit = self.repo.find_commit(oid)?;
148        let tree = commit.tree()?;
149        // root commit: first-parent tree is the empty tree
150        let parent_tree = commit.parent(0).ok().map(|p| p.tree()).transpose()?;
151        let mut opts = git2::DiffOptions::new();
152        opts.context_lines(self.context_lines);
153        let mut diff =
154            self.repo
155                .diff_tree_to_tree(parent_tree.as_ref(), Some(&tree), Some(&mut opts))?;
156        diff_to_model(&self.repo, &mut diff)
157    }
158
159    fn range_diff(&self, oldest_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError> {
160        let oldest = self.repo.find_commit(git2::Oid::from_str(oldest_oid)?)?;
161        let newest = self.repo.find_commit(git2::Oid::from_str(newest_oid)?)?;
162        let newest_tree = newest.tree()?;
163        // the range starts before the oldest commit, so its base is that
164        // commit's first parent; a root commit has none and diffs against the
165        // empty tree, matching commit_diff
166        let base_tree = oldest.parent(0).ok().map(|p| p.tree()).transpose()?;
167        let mut opts = git2::DiffOptions::new();
168        opts.context_lines(self.context_lines);
169        let mut diff =
170            self.repo
171                .diff_tree_to_tree(base_tree.as_ref(), Some(&newest_tree), Some(&mut opts))?;
172        diff_to_model(&self.repo, &mut diff)
173    }
174
175    fn log(&self, limit: usize) -> Result<Vec<LogEntry>, VcsError> {
176        if self.head_tree()?.is_none() {
177            return Ok(Vec::new());
178        }
179        let mut refs_by_oid: HashMap<git2::Oid, Vec<String>> = HashMap::new();
180        for reference in self.repo.references()?.flatten() {
181            let Ok(name) = reference.shorthand().map(str::to_owned) else {
182                continue;
183            };
184            // peel through symbolic refs and annotated tags to the commit
185            let Some(target) = reference.peel_to_commit().ok().map(|c| c.id()) else {
186                continue;
187            };
188            refs_by_oid.entry(target).or_default().push(name);
189        }
190
191        let mut walk = self.repo.revwalk()?;
192        walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
193        walk.push_head()?;
194        let mut entries = Vec::new();
195        for oid in walk.take(limit) {
196            let oid = oid?;
197            let commit = self.repo.find_commit(oid)?;
198            let full = oid.to_string();
199            entries.push(LogEntry {
200                oid7: short7(&full),
201                oid: full,
202                refs: refs_by_oid.get(&oid).cloned().unwrap_or_default(),
203                subject: commit.summary()?.unwrap_or_default().to_owned(),
204                author: commit.author().name().unwrap_or_default().to_owned(),
205                time_unix: commit.time().seconds(),
206            });
207        }
208        Ok(entries)
209    }
210
211    fn branches(&self) -> Result<Vec<BranchInfo>, VcsError> {
212        let mut out = Vec::new();
213        for entry in self.repo.branches(Some(git2::BranchType::Local))? {
214            let (branch, _) = entry?;
215            let Some(name) = branch.name()?.map(str::to_owned) else {
216                continue;
217            };
218            out.push(BranchInfo {
219                name,
220                is_head: branch.is_head(),
221            });
222        }
223        Ok(out)
224    }
225
226    fn stage(&self, rel: &Path) -> Result<(), VcsError> {
227        let root = self.workdir_path()?;
228        let mut index = self.repo.index()?;
229        if root.join(rel).exists() {
230            index.add_path(rel)?;
231        } else {
232            index.remove_path(rel)?;
233        }
234        index.write()?;
235        Ok(())
236    }
237
238    fn stage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError> {
239        let diff = self
240            .repo
241            .diff_index_to_workdir(None, Some(&mut workdir_diff_options(self.context_lines)))?;
242        let patch = synthesize_patch(&diff, rel, hunk, false)?;
243        let diff = git2::Diff::from_buffer(&patch)?;
244        self.repo.apply(&diff, git2::ApplyLocation::Index, None)?;
245        Ok(())
246    }
247
248    fn unstage(&self, rel: &Path) -> Result<(), VcsError> {
249        match self.repo.head() {
250            Ok(head) => {
251                let target = head.peel(git2::ObjectType::Commit)?;
252                self.repo.reset_default(Some(&target), [rel])?;
253            }
254            // unborn branch: there is no HEAD entry to restore, drop from index
255            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
256                let mut index = self.repo.index()?;
257                index.remove_path(rel)?;
258                index.write()?;
259            }
260            Err(err) => return Err(err.into()),
261        }
262        Ok(())
263    }
264
265    fn unstage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError> {
266        let head_tree = self.head_tree()?;
267        let mut opts = git2::DiffOptions::new();
268        opts.context_lines(self.context_lines);
269        let diff = self
270            .repo
271            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
272        let patch = synthesize_patch(&diff, rel, hunk, true)?;
273        let diff = git2::Diff::from_buffer(&patch)?;
274        self.repo.apply(&diff, git2::ApplyLocation::Index, None)?;
275        Ok(())
276    }
277
278    fn discard(&self, rel: &Path) -> Result<(), VcsError> {
279        let head_tree = self.head_tree()?;
280        let mut opts = git2::DiffOptions::new();
281        opts.pathspec(rel).disable_pathspec_match(true);
282        let staged = self
283            .repo
284            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
285        if staged.deltas().len() > 0 {
286            return Err(VcsError::Rejected(
287                "file has staged changes; unstage first".into(),
288            ));
289        }
290        let status = self.repo.status_file(rel)?;
291        if status.contains(git2::Status::WT_NEW) {
292            fs::remove_file(self.workdir_path()?.join(rel))?;
293            return Ok(());
294        }
295        // refresh the index stat cache to match the file we just wrote. with
296        // autocrlf the checkout smudges LF->CRLF, growing the file; leaving the
297        // cached stat stale makes git report a phantom modification (size
298        // mismatch defeats the racy-clean check) even though the content is
299        // identical to HEAD. the file has no staged changes here, so the index
300        // blob already equals HEAD and updating it only corrects the metadata.
301        let mut checkout = git2::build::CheckoutBuilder::new();
302        checkout.path(rel).force().update_index(true);
303        self.repo.checkout_head(Some(&mut checkout))?;
304        Ok(())
305    }
306
307    fn commit(&self, message: &str) -> Result<String, VcsError> {
308        if message.trim().is_empty() {
309            return Err(VcsError::Rejected("empty commit message".into()));
310        }
311        let mut index = self.repo.index()?;
312        let tree_id = index.write_tree()?;
313        let tree = self.repo.find_tree(tree_id)?;
314        let signature = self.repo.signature()?;
315        let parent = match self.repo.head() {
316            Ok(head) => Some(head.peel_to_commit()?),
317            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => None,
318            Err(err) => return Err(err.into()),
319        };
320        let parents: Vec<&git2::Commit<'_>> = parent.iter().collect();
321        let oid = self.repo.commit(
322            Some("HEAD"),
323            &signature,
324            &signature,
325            message,
326            &tree,
327            &parents,
328        )?;
329        Ok(oid.to_string())
330    }
331
332    fn head_message(&self) -> Result<String, VcsError> {
333        let commit = self.repo.head()?.peel_to_commit()?;
334        Ok(commit.message().unwrap_or_default().to_owned())
335    }
336
337    fn amend(&self, message: Option<&str>, use_index: bool) -> Result<String, VcsError> {
338        if let Some(message) = message
339            && message.trim().is_empty()
340        {
341            return Err(VcsError::Rejected("empty commit message".into()));
342        }
343        let head = self.repo.head()?.peel_to_commit()?;
344        // extend/amend fold the staged index into the new tree; a pure reword
345        // keeps HEAD's tree so only the message changes
346        let tree = if use_index {
347            let mut index = self.repo.index()?;
348            let tree_id = index.write_tree()?;
349            self.repo.find_tree(tree_id)?
350        } else {
351            head.tree()?
352        };
353        let oid = head.amend(Some("HEAD"), None, None, None, message, Some(&tree))?;
354        Ok(oid.to_string())
355    }
356
357    fn create_branch(&self, name: &str, checkout: bool) -> Result<(), VcsError> {
358        let head = self.repo.head()?.peel_to_commit()?;
359        self.repo.branch(name, &head, false)?;
360        if checkout {
361            self.checkout(name)?;
362        }
363        Ok(())
364    }
365
366    fn delete_branch(&self, name: &str) -> Result<(), VcsError> {
367        let mut branch = self.repo.find_branch(name, git2::BranchType::Local)?;
368        if branch.is_head() {
369            return Err(VcsError::Rejected(
370                "cannot delete the checked-out branch".into(),
371            ));
372        }
373        branch.delete()?;
374        Ok(())
375    }
376
377    fn checkout(&self, name: &str) -> Result<(), VcsError> {
378        let branch = self.repo.find_branch(name, git2::BranchType::Local)?;
379        let target = branch.get().peel(git2::ObjectType::Commit)?;
380        // safe (non-force) checkout: refuses to clobber local modifications
381        self.repo.checkout_tree(&target, None)?;
382        self.repo.set_head(&format!("refs/heads/{name}"))?;
383        Ok(())
384    }
385
386    fn stash_push(&self, message: Option<&str>) -> Result<(), VcsError> {
387        if !self.has_tracked_changes()? {
388            return Err(VcsError::Rejected("nothing to stash".into()));
389        }
390        // git2 stash mutates the repo, but the trait is &self; a fresh handle on
391        // the same workdir gives the &mut without threading mutability everywhere
392        let mut repo = git2::Repository::open(self.workdir_path()?)?;
393        let signature = repo.signature()?;
394        repo.stash_save2(&signature, message, None)?;
395        Ok(())
396    }
397
398    fn stash_pop(&self) -> Result<(), VcsError> {
399        let mut repo = git2::Repository::open(self.workdir_path()?)?;
400        match repo.stash_pop(0, None) {
401            Ok(()) => Ok(()),
402            Err(err) if err.code() == git2::ErrorCode::NotFound => {
403                Err(VcsError::Rejected("no stash to pop".into()))
404            }
405            // a conflicting pop leaves the merge in the worktree and keeps the
406            // stash entry; say so rather than surfacing a bare libgit2 error
407            Err(err) if err.code() == git2::ErrorCode::Conflict => Err(VcsError::Rejected(
408                "stash applied with conflicts; resolve them — the stash was kept".into(),
409            )),
410            Err(err) => Err(err.into()),
411        }
412    }
413
414    fn network_argv(&self, op: NetworkOp) -> Vec<String> {
415        // shelling to `git` (not git2) so the user's credential helper, SSH
416        // agent, and config drive auth; PushSetUpstream targets HEAD so the
417        // current branch publishes to its same-named remote ref
418        let args: &[&str] = match op {
419            NetworkOp::Push => &["push"],
420            NetworkOp::PushSetUpstream => &["push", "-u", "origin", "HEAD"],
421            NetworkOp::Pull => &["pull"],
422            NetworkOp::Fetch => &["fetch"],
423            NetworkOp::FetchAll => &["fetch", "--all"],
424        };
425        std::iter::once("git")
426            .chain(args.iter().copied())
427            .map(str::to_owned)
428            .collect()
429    }
430
431    fn workdir(&self) -> Result<PathBuf, VcsError> {
432        Ok(self.workdir_path()?.to_path_buf())
433    }
434
435    fn remote_url(&self, name: &str) -> Result<Option<String>, VcsError> {
436        match self.repo.find_remote(name) {
437            // url() errs only on a non-UTF-8 remote URL; treat that as no URL
438            Ok(remote) => Ok(remote.url().ok().map(str::to_owned)),
439            Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
440            Err(err) => Err(err.into()),
441        }
442    }
443}
444
445/// Render one hunk of `rel` as a unified patch libgit2 can apply to the
446/// index. `reverse` flips the patch so applying it undoes a staged hunk.
447/// Built from the raw git2 patch lines (not the display model) so original
448/// line endings and missing-trailing-newline markers survive intact.
449fn synthesize_patch(
450    diff: &git2::Diff<'_>,
451    rel: &Path,
452    target: &HunkId,
453    reverse: bool,
454) -> Result<Vec<u8>, VcsError> {
455    let rel = rel.to_string_lossy();
456    for idx in 0..diff.deltas().len() {
457        let Some(patch) = git2::Patch::from_diff(diff, idx)? else {
458            continue;
459        };
460        let delta = patch.delta();
461        if delta.flags().is_binary() || delta_new_path(&delta) != rel {
462            continue;
463        }
464        for h in 0..patch.num_hunks() {
465            if hunk_id(&rel, &hunk_model_lines(&patch, h)?)? == *target {
466                return render_hunk_patch(&patch, h, &rel, delta.status(), reverse);
467            }
468        }
469    }
470    Err(VcsError::Rejected("hunk not found (diff changed?)".into()))
471}
472
473fn render_hunk_patch(
474    patch: &git2::Patch<'_>,
475    h: usize,
476    rel: &str,
477    status: git2::Delta,
478    reverse: bool,
479) -> Result<Vec<u8>, VcsError> {
480    let added = matches!(status, git2::Delta::Added | git2::Delta::Untracked);
481    let deleted = status == git2::Delta::Deleted;
482    let mut out = Vec::new();
483    out.extend_from_slice(format!("diff --git a/{rel} b/{rel}\n").as_bytes());
484    // whole-file adds and deletes must keep that identity (with the sides
485    // swapped under reverse) so applying creates or drops the index entry
486    // instead of leaving an empty blob behind
487    if (added && !reverse) || (deleted && reverse) {
488        out.extend_from_slice(
489            format!("new file mode 100644\n--- /dev/null\n+++ b/{rel}\n").as_bytes(),
490        );
491    } else if (deleted && !reverse) || (added && reverse) {
492        out.extend_from_slice(
493            format!("deleted file mode 100644\n--- a/{rel}\n+++ /dev/null\n").as_bytes(),
494        );
495    } else {
496        out.extend_from_slice(format!("--- a/{rel}\n+++ b/{rel}\n").as_bytes());
497    }
498    let (hunk, line_count) = patch.hunk(h)?;
499    let (old, new) = (
500        (hunk.old_start(), hunk.old_lines()),
501        (hunk.new_start(), hunk.new_lines()),
502    );
503    let ((minus_start, minus_lines), (plus_start, plus_lines)) =
504        if reverse { (new, old) } else { (old, new) };
505    out.extend_from_slice(
506        format!("@@ -{minus_start},{minus_lines} +{plus_start},{plus_lines} @@\n").as_bytes(),
507    );
508    for l in 0..line_count {
509        let line = patch.line_in_hunk(h, l)?;
510        let origin = match (line.origin(), reverse) {
511            (' ', _) => Some(b' '),
512            ('+', false) | ('-', true) => Some(b'+'),
513            ('-', false) | ('+', true) => Some(b'-'),
514            // EOF-newline markers already carry the full "\ No newline at
515            // end of file" text, including the newline that terminates the
516            // preceding unterminated line, so they pass through unprefixed
517            ('=' | '>' | '<', _) => None,
518            _ => continue,
519        };
520        if let Some(origin) = origin {
521            out.push(origin);
522        }
523        out.extend_from_slice(line.content());
524    }
525    Ok(out)
526}
527
528fn workdir_diff_options(context_lines: u32) -> git2::DiffOptions {
529    let mut opts = git2::DiffOptions::new();
530    opts.include_untracked(true)
531        .recurse_untracked_dirs(true)
532        .show_untracked_content(true)
533        .context_lines(context_lines);
534    opts
535}
536
537fn short7(oid: &str) -> String {
538    oid.get(..7).unwrap_or(oid).to_owned()
539}
540
541fn diff_to_model(
542    repo: &git2::Repository,
543    diff: &mut git2::Diff<'_>,
544) -> Result<DiffModel, VcsError> {
545    let mut files = Vec::new();
546    for idx in 0..diff.deltas().len() {
547        if let Some(file) = build_file(repo, diff, idx)? {
548            files.push(file);
549        }
550    }
551    // intra-line emphasis is a render-time concern: the TUI enriches the
552    // file it is about to draw (see crate::pairing::enrich_file), so the
553    // backend leaves `.emphasis` empty.
554    Ok(DiffModel { files })
555}
556
557fn build_file(
558    repo: &git2::Repository,
559    diff: &mut git2::Diff<'_>,
560    idx: usize,
561) -> Result<Option<FileDiff>, VcsError> {
562    let Some(patch) = git2::Patch::from_diff(diff, idx)? else {
563        // binary or unreadable: fall back to delta metadata only
564        return Ok(build_binary_file(diff, idx));
565    };
566    let delta = patch.delta();
567    if delta.flags().is_binary() {
568        return Ok(build_binary_file(diff, idx));
569    }
570    let file_path = delta_new_path(&delta);
571    let status = map_status(delta.status());
572    let old_path = if status == FileStatus::Renamed {
573        delta
574            .old_file()
575            .path()
576            .map(|p| p.to_string_lossy().into_owned())
577    } else {
578        None
579    };
580
581    let old_text = blob_text(repo, delta.old_file().id());
582    let new_text = new_side_text(repo, &delta, &file_path);
583
584    let mut hunks = Vec::new();
585    for h in 0..patch.num_hunks() {
586        let (hunk, _) = patch.hunk(h)?;
587        let lines = hunk_model_lines(&patch, h)?;
588        let id = hunk_id(&file_path, &lines)?;
589        hunks.push(Hunk {
590            id,
591            old_start: hunk.old_start(),
592            old_lines: hunk.old_lines(),
593            new_start: hunk.new_start(),
594            new_lines: hunk.new_lines(),
595            context: hunk_context(&hunk),
596            lines,
597        });
598    }
599
600    Ok(Some(FileDiff {
601        path: file_path,
602        old_path,
603        status,
604        binary: false,
605        old_text,
606        new_text,
607        hunks,
608    }))
609}
610
611/// git's section heading for a hunk: the text git appends after the second
612/// `@@` of the header (`@@ -a,b +c,d @@ <context>`), typically the enclosing
613/// function or section. Empty when git emits none (e.g. a top-of-file hunk).
614fn hunk_context(hunk: &git2::DiffHunk<'_>) -> String {
615    let header = String::from_utf8_lossy(hunk.header());
616    match header.split_once(" @@") {
617        Some((_, rest)) => rest.trim_matches(['\n', '\r', ' ']).to_owned(),
618        None => String::new(),
619    }
620}
621
622/// Content lines of one hunk as model lines (headers and EOF-newline markers
623/// excluded). Shared by model building and hunk lookup so the hunk ids
624/// computed in both places agree.
625fn hunk_model_lines(patch: &git2::Patch<'_>, h: usize) -> Result<Vec<DiffLine>, VcsError> {
626    let (_, line_count) = patch.hunk(h)?;
627    let mut lines = Vec::with_capacity(line_count);
628    for l in 0..line_count {
629        let line = patch.line_in_hunk(h, l)?;
630        let kind = match line.origin() {
631            '-' => LineKind::Deleted,
632            '+' => LineKind::Added,
633            ' ' => LineKind::Context,
634            // headers, EOF-newline markers etc. are not content lines
635            _ => continue,
636        };
637        let text = String::from_utf8_lossy(line.content())
638            .trim_end_matches(['\n', '\r'])
639            .to_owned();
640        lines.push(DiffLine::new(
641            kind,
642            line.old_lineno(),
643            line.new_lineno(),
644            text,
645        ));
646    }
647    Ok(lines)
648}
649
650fn build_binary_file(diff: &git2::Diff<'_>, idx: usize) -> Option<FileDiff> {
651    let delta = diff.get_delta(idx)?;
652    Some(FileDiff {
653        path: delta_new_path(&delta),
654        old_path: None,
655        status: map_status(delta.status()),
656        binary: true,
657        old_text: None,
658        new_text: None,
659        hunks: Vec::new(),
660    })
661}
662
663fn delta_new_path(delta: &git2::DiffDelta<'_>) -> String {
664    delta
665        .new_file()
666        .path()
667        .or_else(|| delta.old_file().path())
668        .map(|p| p.to_string_lossy().into_owned())
669        .unwrap_or_default()
670}
671
672fn map_status(status: git2::Delta) -> FileStatus {
673    match status {
674        git2::Delta::Added => FileStatus::Added,
675        git2::Delta::Deleted => FileStatus::Deleted,
676        git2::Delta::Renamed => FileStatus::Renamed,
677        git2::Delta::Untracked => FileStatus::Untracked,
678        _ => FileStatus::Modified,
679    }
680}
681
682fn blob_text(repo: &git2::Repository, oid: git2::Oid) -> Option<String> {
683    if oid.is_zero() {
684        return None;
685    }
686    let blob = repo.find_blob(oid).ok()?;
687    if blob.is_binary() {
688        return None;
689    }
690    String::from_utf8(blob.content().to_vec()).ok()
691}
692
693/// New-side content: the recorded blob when the diff target is a tree or the
694/// index (where the workdir may differ), the workdir file otherwise.
695fn new_side_text(
696    repo: &git2::Repository,
697    delta: &git2::DiffDelta<'_>,
698    rel: &str,
699) -> Option<String> {
700    if delta.status() == git2::Delta::Deleted {
701        return None;
702    }
703    if let Some(text) = blob_text(repo, delta.new_file().id()) {
704        return Some(text);
705    }
706    let root = repo.workdir()?;
707    fs::read_to_string(root.join(rel)).ok()
708}