Replace libgit2 with gitoxide

This commit is contained in:
blinxen committed 2026-06-26 20:27:49 +02:00
1 parent 04576fd5a5
commit c5e6f6aae3
5 files changed
+1707 -576

No files matched your search

+1
View File
@@ -53,6 +53,7 @@
- Allow home and end keys to be used with builtin pager, see #3651 (@keith-hall) - Allow home and end keys to be used with builtin pager, see #3651 (@keith-hall)
- Builtin syntax mapping: cleanup matcher glob parsing logic #3652 (@cyqsimon) - Builtin syntax mapping: cleanup matcher glob parsing logic #3652 (@cyqsimon)
- Statically link the CRT for MSVC builds via Cargo config to avoid runtime DLL dependencies. Closes #3634, see #3692 (@barry3406) - Statically link the CRT for MSVC builds via Cargo config to avoid runtime DLL dependencies. Closes #3634, see #3692 (@barry3406)
- Replace `libgit2` with a pure Rust implementation of git called `gitoxide`, see PR #XXXX (@blinxen)
## Syntaxes ## Syntaxes
Generated
+1598 -482
View File
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -31,8 +31,7 @@ minimal-application = [
"regex-onig", "regex-onig",
"wild", "wild",
] ]
git = ["git2"] # Support indicating git modifications git = ["gix"] # Support indicating git modifications
vendored-libgit2 = ["git2/vendored-libgit2"]
paging = [ "shell-words", "grep-cli", "minus"] # Support applying a pager on the output paging = [ "shell-words", "grep-cli", "minus"] # Support applying a pager on the output
lessopen = ["execute"] # Support $LESSOPEN preprocessor lessopen = ["execute"] # Support $LESSOPEN preprocessor
build-assets = ["syntect/yaml-load", "syntect/plist-load", "regex", "walkdir"] build-assets = ["syntect/yaml-load", "syntect/plist-load", "regex", "walkdir"]
@@ -76,10 +75,11 @@ terminal-colorsaurus = "1.0"
unicode-segmentation = "1.13.2" unicode-segmentation = "1.13.2"
itertools = "0.14.0" itertools = "0.14.0"
[dependencies.git2] [dependencies.gix]
version = "0.20" version = "0.82"
optional = true optional = true
default-features = false default-features = false
features = ["sha1", "blob-diff"]
[dependencies.syntect] [dependencies.syntect]
version = "5.3.0" version = "5.3.0"
+67 -62
View File
@@ -1,11 +1,14 @@
#![cfg(feature = "git")] #![cfg(feature = "git")]
use gix::diff::blob::pipeline::{Mode, WorktreeRoots};
use gix::diff::blob::{Algorithm, HunkIter, ResourceKind};
use gix::index::hash::Kind;
use gix::object::tree::EntryKind;
use gix::{self, ObjectId};
use path_abs::PathInfo;
use std::collections::HashMap; use std::collections::HashMap;
use std::fs;
use std::path::Path; use std::path::Path;
use git2::{DiffOptions, IntoCString, Repository};
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub enum LineChange { pub enum LineChange {
Added, Added,
@@ -16,68 +19,70 @@ pub enum LineChange {
pub type LineChanges = HashMap<u32, LineChange>; pub type LineChanges = HashMap<u32, LineChange>;
fn collect_changes_from_hunks(hunks: HunkIter) -> Option<LineChanges> {
let mut changes: LineChanges = HashMap::new();
for hunk in hunks {
if hunk.before.is_empty() && !hunk.after.is_empty() {
for line in hunk.after {
changes.insert(line + 1, LineChange::Added);
}
} else if hunk.after.is_empty() && !hunk.before.is_empty() {
if hunk.after.start == 0 {
changes.insert(1, LineChange::RemovedAbove);
} else {
changes.insert(hunk.after.start, LineChange::RemovedBelow);
}
} else {
for line in hunk.after {
changes.insert(line + 1, LineChange::Modified);
}
}
}
Some(changes)
}
pub fn get_git_diff(filename: &Path) -> Option<LineChanges> { pub fn get_git_diff(filename: &Path) -> Option<LineChanges> {
let repo = Repository::discover(filename).ok()?; let filepath_absolute = filename.canonicalize().ok()?;
let repository = gix::discover(filepath_absolute.parent().ok()?).unwrap();
let repo_path_absolute = fs::canonicalize(repo.workdir()?).ok()?; let repo_path_absolute = repository.workdir()?.canonicalize().ok()?;
let filepath_absolute = fs::canonicalize(filename).ok()?;
let filepath_relative_to_repo = filepath_absolute.strip_prefix(&repo_path_absolute).ok()?; let filepath_relative_to_repo = filepath_absolute.strip_prefix(&repo_path_absolute).ok()?;
let mut cache = repository
let mut diff_options = DiffOptions::new(); .diff_resource_cache(
let pathspec = filepath_relative_to_repo.into_c_string().ok()?; Mode::ToGit,
diff_options.pathspec(pathspec); WorktreeRoots {
diff_options.context_lines(0); old_root: None,
new_root: repository.workdir().map(Path::to_path_buf),
let diff = repo },
.diff_index_to_workdir(None, Some(&mut diff_options)) )
.ok()?; .ok()?;
cache
let mut line_changes: LineChanges = HashMap::new(); .set_resource(
repository
let mark_section = .head_tree()
|line_changes: &mut LineChanges, start: u32, end: i32, change: LineChange| { .ok()?
for line in start..=end as u32 { .lookup_entry_by_path(filepath_relative_to_repo.to_str()?)
line_changes.insert(line, change); .ok()??
} .object_id(),
}; EntryKind::Blob,
filepath_relative_to_repo.to_str()?.into(),
let _ = diff.foreach( ResourceKind::OldOrSource,
&mut |_, _| true, &repository,
None, )
Some(&mut |delta, hunk| { .ok()?;
let path = delta.new_file().path().unwrap_or_else(|| Path::new("")); cache
.set_resource(
if filepath_relative_to_repo != path { ObjectId::null(Kind::Sha1),
return false; EntryKind::Blob,
} filepath_relative_to_repo.to_str()?.into(),
ResourceKind::NewOrDestination,
let old_lines = hunk.old_lines(); &repository,
let new_start = hunk.new_start(); )
let new_lines = hunk.new_lines(); .ok()?;
let new_end = (new_start + new_lines) as i32 - 1; let diff = gix::diff::blob::diff_with_slider_heuristics(
Algorithm::Myers,
if old_lines == 0 && new_lines > 0 { &cache.prepare_diff().ok()?.interned_input(),
mark_section(&mut line_changes, new_start, new_end, LineChange::Added);
} else if new_lines == 0 && old_lines > 0 {
if new_start == 0 {
mark_section(&mut line_changes, 1, 1, LineChange::RemovedAbove);
} else {
mark_section(
&mut line_changes,
new_start,
new_start as i32,
LineChange::RemovedBelow,
);
}
} else {
mark_section(&mut line_changes, new_start, new_end, LineChange::Modified);
}
true
}),
None,
); );
Some(line_changes) collect_changes_from_hunks(diff.hunks())
} }
+37 -28
View File
@@ -1,15 +1,17 @@
use gix::actor::SignatureRef;
use gix::bstr::BString;
use gix::bstr::ByteSlice;
use gix::date::time::Format;
use gix::date::Time;
use gix::objs::tree;
use std::env; use std::env;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::Read; use std::io::Read;
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use tempfile::TempDir; use tempfile::TempDir;
use git2::build::CheckoutBuilder;
use git2::Repository;
use git2::Signature;
pub struct BatTester { pub struct BatTester {
/// Temporary working directory /// Temporary working directory
temp_dir: TempDir, temp_dir: TempDir,
@@ -59,35 +61,42 @@ impl Default for BatTester {
} }
} }
fn create_sample_directory() -> Result<TempDir, git2::Error> { fn create_sample_directory() -> Result<TempDir, Box<dyn std::error::Error>> {
// Create temp directory and initialize repository // Create temp directory and initialize repository
let temp_dir = TempDir::new().expect("Temp directory"); let temp_dir = TempDir::new().expect("Temp directory");
let repo = Repository::init(&temp_dir)?; let repo = gix::init(&temp_dir)?;
let mut tree = gix::objs::Tree::empty();
// Copy over `sample.rs` // Create sample.rs from snapshot file
let sample_path = temp_dir.path().join("sample.rs"); let blob_id = repo.write_blob_stream(File::open("tests/snapshots/sample.rs")?)?;
println!("{sample_path:?}"); let entry = tree::Entry {
fs::copy("tests/snapshots/sample.rs", &sample_path).expect("successful copy"); mode: tree::EntryMode::from(tree::EntryKind::Blob),
oid: blob_id.object()?.id,
filename: BString::from("sample.rs"),
};
tree.entries.push(entry);
let tree_id = repo.write_object(tree)?;
// Commit let author = SignatureRef {
let mut index = repo.index()?; name: "test".as_bytes().as_bstr(),
index.add_path(Path::new("sample.rs"))?; email: "test@test.test".as_bytes().as_bstr(),
time: &Time::now_local_or_utc().format_or_unix(Format::Raw),
let oid = index.write_tree()?; };
let signature = Signature::now("bat test runner", "bat@test.runner")?; let commit_id = repo.commit_as(
let tree = repo.find_tree(oid)?; author,
let _ = repo.commit( author,
Some("HEAD"), // point HEAD to our new commit "HEAD",
&signature, // author
&signature, // committer
"initial commit", "initial commit",
&tree, tree_id,
&[], gix::commit::NO_PARENT_IDS,
); )?;
let mut opts = CheckoutBuilder::new(); assert_eq!(commit_id, repo.head_id()?);
repo.checkout_head(Some(opts.force()))?;
fs::copy("tests/snapshots/sample.modified.rs", &sample_path).expect("successful copy"); fs::copy(
"tests/snapshots/sample.modified.rs",
temp_dir.path().join("sample.rs"),
)
.expect("successful copy");
Ok(temp_dir) Ok(temp_dir)
} }