| 1 |
use anyhow::{bail, Context, Result}; |
| 2 |
use arc_swap::ArcSwap; |
| 3 |
use gix::filter::plumbing::driver::apply::Delay; |
| 4 |
use std::io::Read; |
| 5 |
use std::path::Path; |
| 6 |
use std::sync::Arc; |
| 7 |
|
| 8 |
use gix::bstr::ByteSlice; |
| 9 |
use gix::diff::Rewrites; |
| 10 |
use gix::dir::entry::Status; |
| 11 |
use gix::objs::tree::EntryKind; |
| 12 |
use gix::sec::trust::DefaultForLevel; |
| 13 |
use gix::status::{ |
| 14 |
index_worktree::Item, |
| 15 |
plumbing::index_as_worktree::{Change, EntryStatus}, |
| 16 |
UntrackedFiles, |
| 17 |
}; |
| 18 |
use gix::{Commit, ObjectId, Repository, ThreadSafeRepository}; |
| 19 |
|
| 20 |
use crate::FileChange; |
| 21 |
|
| 22 |
#[cfg(test)] |
| 23 |
mod test; |
| 24 |
|
| 25 |
#[inline] |
| 26 |
fn get_repo_dir(file: &Path) -> Result<&Path> { |
| 27 |
file.parent().context("file has no parent directory") |
| 28 |
} |
| 29 |
|
| 30 |
pub fn get_diff_base(file: &Path, trust_full: bool) -> Result<Vec<u8>> { |
| 31 |
debug_assert!(!file.exists() || file.is_file()); |
| 32 |
debug_assert!(file.is_absolute()); |
| 33 |
let file = gix::path::realpath(file).context("resolve symlinks")?; |
| 34 |
|
| 35 |
// TODO cache repository lookup |
| 36 |
|
| 37 |
let repo_dir = get_repo_dir(&file)?; |
| 38 |
let repo = open_repo(repo_dir, trust_full) |
| 39 |
.context("failed to open git repo")? |
| 40 |
.to_thread_local(); |
| 41 |
let head = repo.head_commit()?; |
| 42 |
let file_oid = find_file_in_commit(&repo, &head, &file)?; |
| 43 |
|
| 44 |
let file_object = repo.find_object(file_oid)?; |
| 45 |
let data = file_object.detach().data; |
| 46 |
// Get the actual data that git would make out of the git object. |
| 47 |
// This will apply the user's git config or attributes like crlf conversions. |
| 48 |
// |
| 49 |
// The whole filter pipeline still runs in untrusted (`Trust::Reduced`) mode so built-in |
| 50 |
// conversions like autocrlf keep working, but gix drops `filter.*.clean` / `filter.*.smudge` |
| 51 |
// drivers defined in untrusted (repository-local) config, so those external programs are not |
| 52 |
// executed unless the workspace was explicitly trusted. This relies on `open_repo` forcing the |
| 53 |
// trust level instead of letting gix re-derive it from `.git` ownership; see the note there. |
| 54 |
if let Some(work_dir) = repo.workdir() { |
| 55 |
let rela_path = file.strip_prefix(work_dir)?; |
| 56 |
let rela_path = gix::path::try_into_bstr(rela_path)?; |
| 57 |
let (mut pipeline, _) = repo.filter_pipeline(None)?; |
| 58 |
let mut worktree_outcome = |
| 59 |
pipeline.convert_to_worktree(&data, rela_path.as_ref(), Delay::Forbid)?; |
| 60 |
let mut buf = Vec::with_capacity(data.len()); |
| 61 |
worktree_outcome.read_to_end(&mut buf)?; |
| 62 |
Ok(buf) |
| 63 |
} else { |
| 64 |
Ok(data) |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
pub fn get_current_head_name(file: &Path, trust_full: bool) -> Result<Arc<ArcSwap<Box<str>>>> { |
| 69 |
debug_assert!(!file.exists() || file.is_file()); |
| 70 |
debug_assert!(file.is_absolute()); |
| 71 |
let file = gix::path::realpath(file).context("resolve symlinks")?; |
| 72 |
|
| 73 |
let repo_dir = get_repo_dir(&file)?; |
| 74 |
let repo = open_repo(repo_dir, trust_full) |
| 75 |
.context("failed to open git repo")? |
| 76 |
.to_thread_local(); |
| 77 |
let head_ref = repo.head_ref()?; |
| 78 |
let head_commit = repo.head_commit()?; |
| 79 |
|
| 80 |
let name = match head_ref { |
| 81 |
Some(reference) => reference.name().shorten().to_string(), |
| 82 |
None => head_commit.id.to_hex_with_len(8).to_string(), |
| 83 |
}; |
| 84 |
|
| 85 |
Ok(Arc::new(ArcSwap::from_pointee(name.into_boxed_str()))) |
| 86 |
} |
| 87 |
|
| 88 |
pub fn for_each_changed_file( |
| 89 |
cwd: &Path, |
| 90 |
trust_full: bool, |
| 91 |
f: impl Fn(Result<FileChange>) -> bool, |
| 92 |
) -> Result<()> { |
| 93 |
status(&open_repo(cwd, trust_full)?.to_thread_local(), f) |
| 94 |
} |
| 95 |
|
| 96 |
fn open_repo(path: &Path, trust_full: bool) -> Result<ThreadSafeRepository> { |
| 97 |
// `trust_full` is the workspace-trust decision made by the caller, and it must be the |
| 98 |
// authority on the gix trust level. gix's own discovery (`discover_*`) ignores a |
| 99 |
// caller-supplied trust level: it always re-derives trust from `.git` ownership, so a malicious |
| 100 |
// `.git/config` in a user-owned directory would be opened as `Trust::Full` regardless of our |
| 101 |
// gate. Worse, the GIT_DIR-environment branch of that discovery panics because it never sets a |
| 102 |
// trust level at all. So we split discovery from opening: find the repository path ourselves, |
| 103 |
// then `open_opts(..).with(trust)`, which forces the trust level and skips gix's ownership |
| 104 |
// check. Under `Trust::Reduced`, gix then refuses to honor untrusted repository-local config |
| 105 |
// such as `filter.*` smudge/clean drivers. |
| 106 |
|
| 107 |
let trust = if trust_full { |
| 108 |
gix::sec::Trust::Full |
| 109 |
} else { |
| 110 |
gix::sec::Trust::Reduced |
| 111 |
}; |
| 112 |
|
| 113 |
// On Windows various configuration options are bundled as part of the git installation. The |
| 114 |
// lookup is expensive; only do it there. |
| 115 |
let config = gix::open::permissions::Config { |
| 116 |
system: true, |
| 117 |
git: true, |
| 118 |
user: true, |
| 119 |
env: true, |
| 120 |
includes: true, |
| 121 |
git_binary: cfg!(windows), |
| 122 |
}; |
| 123 |
|
| 124 |
let permissions = gix::open::Permissions { |
| 125 |
config, |
| 126 |
..gix::open::Permissions::default_for_level(trust) |
| 127 |
}; |
| 128 |
|
| 129 |
let discover_options = gix::discover::upwards::Options { |
| 130 |
dot_git_only: true, |
| 131 |
..Default::default() |
| 132 |
}; |
| 133 |
let (repo_path, _trust_from_ownership) = gix::discover::upwards_opts(path, discover_options) |
| 134 |
.context("failed to discover git repo")?; |
| 135 |
let (git_dir, _work_dir) = repo_path.into_repository_and_work_tree_directories(); |
| 136 |
|
| 137 |
let options = gix::open::Options::default() |
| 138 |
.permissions(permissions) |
| 139 |
// `git_dir` is the discovered `.git` directory (or a linked-worktree git dir), so open it |
| 140 |
// as-is rather than letting gix append `.git` again. |
| 141 |
.open_path_as_is(true) |
| 142 |
.with(trust); |
| 143 |
|
| 144 |
Ok(ThreadSafeRepository::open_opts(git_dir, options)?) |
| 145 |
} |
| 146 |
|
| 147 |
/// Emulates the result of running `git status` from the command line. |
| 148 |
fn status(repo: &Repository, f: impl Fn(Result<FileChange>) -> bool) -> Result<()> { |
| 149 |
let work_dir = repo |
| 150 |
.workdir() |
| 151 |
.ok_or_else(|| anyhow::anyhow!("working tree not found"))? |
| 152 |
.to_path_buf(); |
| 153 |
|
| 154 |
let status_platform = repo |
| 155 |
.status(gix::progress::Discard)? |
| 156 |
// Here we discard the `status.showUntrackedFiles` config, as it makes little sense in |
| 157 |
// our case to not list new (untracked) files. We could have respected this config |
| 158 |
// if the default value weren't `Collapsed` though, as this default value would render |
| 159 |
// the feature unusable to many. |
| 160 |
.untracked_files(UntrackedFiles::Files) |
| 161 |
// Turn on file rename detection, which is off by default. |
| 162 |
.index_worktree_rewrites(Some(Rewrites { |
| 163 |
copies: None, |
| 164 |
percentage: Some(0.5), |
| 165 |
limit: 1000, |
| 166 |
..Default::default() |
| 167 |
})); |
| 168 |
|
| 169 |
// No filtering based on path |
| 170 |
let empty_patterns = vec![]; |
| 171 |
|
| 172 |
let status_iter = status_platform.into_index_worktree_iter(empty_patterns)?; |
| 173 |
|
| 174 |
for item in status_iter { |
| 175 |
let Ok(item) = item.map_err(|err| f(Err(err.into()))) else { |
| 176 |
continue; |
| 177 |
}; |
| 178 |
let change = match item { |
| 179 |
Item::Modification { |
| 180 |
rela_path, status, .. |
| 181 |
} => { |
| 182 |
let path = work_dir.join(rela_path.to_path()?); |
| 183 |
match status { |
| 184 |
EntryStatus::Conflict { .. } => FileChange::Conflict { path }, |
| 185 |
EntryStatus::Change(Change::Removed) => FileChange::Deleted { path }, |
| 186 |
EntryStatus::Change(Change::Modification { .. }) => { |
| 187 |
FileChange::Modified { path } |
| 188 |
} |
| 189 |
// Files marked with `git add --intent-to-add`. Such files |
| 190 |
// still show up as new in `git status`, so it's appropriate |
| 191 |
// to show them the same way as untracked files in the |
| 192 |
// "changed file" picker. One example of this being used |
| 193 |
// is Jujutsu, a Git-compatible VCS. It marks all new files |
| 194 |
// with `--intent-to-add` automatically. |
| 195 |
EntryStatus::IntentToAdd => FileChange::Untracked { path }, |
| 196 |
_ => continue, |
| 197 |
} |
| 198 |
} |
| 199 |
Item::DirectoryContents { entry, .. } if entry.status == Status::Untracked => { |
| 200 |
FileChange::Untracked { |
| 201 |
path: work_dir.join(entry.rela_path.to_path()?), |
| 202 |
} |
| 203 |
} |
| 204 |
Item::Rewrite { |
| 205 |
source, |
| 206 |
dirwalk_entry, |
| 207 |
.. |
| 208 |
} => FileChange::Renamed { |
| 209 |
from_path: work_dir.join(source.rela_path().to_path()?), |
| 210 |
to_path: work_dir.join(dirwalk_entry.rela_path.to_path()?), |
| 211 |
}, |
| 212 |
_ => continue, |
| 213 |
}; |
| 214 |
if !f(Ok(change)) { |
| 215 |
break; |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
Ok(()) |
| 220 |
} |
| 221 |
|
| 222 |
/// Finds the object that contains the contents of a file at a specific commit. |
| 223 |
fn find_file_in_commit(repo: &Repository, commit: &Commit, file: &Path) -> Result<ObjectId> { |
| 224 |
let repo_dir = repo.workdir().context("repo has no worktree")?; |
| 225 |
let rel_path = file.strip_prefix(repo_dir)?; |
| 226 |
let tree = commit.tree()?; |
| 227 |
let tree_entry = tree |
| 228 |
.lookup_entry_by_path(rel_path)? |
| 229 |
.context("file is untracked")?; |
| 230 |
match tree_entry.mode().kind() { |
| 231 |
// not a file, everything is new, do not show diff |
| 232 |
mode @ (EntryKind::Tree | EntryKind::Commit | EntryKind::Link) => { |
| 233 |
bail!("entry at {} is not a file but a {mode:?}", file.display()) |
| 234 |
} |
| 235 |
// found a file |
| 236 |
EntryKind::Blob | EntryKind::BlobExecutable => Ok(tree_entry.object_id()), |
| 237 |
} |
| 238 |
} |