use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, Permissions};
use std::io::ErrorKind;
use std::path::{Component, Path, PathBuf};
use anyhow::{Context, Result};
use gix::bstr::ByteSlice;
use gix::objs::tree::EntryKind;
use crate::branches::default_upstream_commit;
use crate::status::{IgnoredFiles, status_paths};
use crate::{discover, repo_covering};
const NEED_FULL_FETCH: &str =
"cannot compare versions against the default branch (need a full fetch, not a shallow clone)";
pub fn files_on_merge_base(
root: &Path,
rels: &[&Path],
candidates: &[String],
) -> Result<Vec<Option<String>>> {
let Some(repo) = repo_covering(root) else {
return Ok(vec![None; rels.len()]);
};
let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
return Ok(vec![None; rels.len()]);
};
let head = repo
.head_commit()
.context("cannot compare versions (need HEAD)")?;
let base = repo
.merge_base(head.id(), upstream)
.context(NEED_FULL_FETCH)?
.context(NEED_FULL_FETCH)?;
let tree = repo.find_commit(base)?.tree()?;
let workdir = repo.workdir().map(Path::to_path_buf);
Ok(rels
.iter()
.map(|rel| git_path(root, rel, workdir.as_deref()).and_then(|path| blob_at(&tree, &path)))
.collect())
}
pub(crate) fn git_path(root: &Path, rel: &Path, workdir: Option<&Path>) -> Option<PathBuf> {
let abs = if rel.is_absolute() {
rel.canonicalize().ok().or_else(|| {
rel.parent()?
.canonicalize()
.ok()
.map(|dir| dir.join(rel.file_name().unwrap_or_default()))
})?
} else {
let inside: PathBuf = rel
.components()
.filter(|part| !matches!(part, Component::CurDir))
.collect();
root.canonicalize().ok()?.join(inside)
};
let workdir = workdir?.canonicalize().ok()?;
abs.strip_prefix(workdir).ok().map(Path::to_path_buf)
}
#[derive(Debug)]
pub struct MergeBase {
repo: gix::Repository,
workdir: PathBuf,
files: BTreeMap<String, (gix::ObjectId, EntryKind)>,
changed: BTreeSet<String>,
}
impl MergeBase {
pub fn read(root: &Path, candidates: &[String]) -> Result<Option<Self>> {
let Some(repo) = repo_covering(root) else {
return Ok(None);
};
let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
return Ok(None);
};
let (files, head_files) = {
let head = repo
.head_commit()
.context("cannot compare the Version PR (need HEAD)")?;
let base = repo
.merge_base(head.id(), upstream)
.context(NEED_FULL_FETCH)?
.context(NEED_FULL_FETCH)?;
(
files_of(&repo.find_commit(base)?.tree()?)?,
files_of(&head.tree()?)?,
)
};
let workdir = repo
.workdir()
.context("the Version PR check needs a working tree")?
.canonicalize()
.context("the working tree")?;
let mut candidates: BTreeSet<String> = files
.keys()
.chain(head_files.keys())
.filter(|path| files.get(*path) != head_files.get(*path))
.cloned()
.collect();
candidates.extend(
status_paths(&repo, Vec::new(), IgnoredFiles::Skip)
.context("git status")?
.into_iter()
.filter(|path| files.contains_key(path) || head_files.contains_key(path)),
);
let mut merge_base = Self {
repo,
workdir,
files,
changed: BTreeSet::new(),
};
for path in candidates {
if merge_base.differs(&path, head_files.get(&path))? {
merge_base.changed.insert(path);
}
}
Ok(Some(merge_base))
}
fn differs(&self, rel: &str, head: Option<&(gix::ObjectId, EntryKind)>) -> Result<bool> {
let base = self.files.get(rel);
let gitlink = |entry: Option<&(gix::ObjectId, EntryKind)>| {
entry.is_some_and(|(_, kind)| *kind == EntryKind::Commit)
};
if gitlink(base) || gitlink(head) {
return Ok(base != head);
}
let expected = match base {
None => Worktree::Missing,
Some((_, EntryKind::Link)) => Worktree::Link(self.base_bytes(rel)?.unwrap_or_default()),
Some(_) => Worktree::File(self.base_bytes(rel)?.unwrap_or_default()),
};
Ok(expected != Worktree::read(&self.workdir.join(rel))?)
}
#[must_use]
pub fn workdir(&self) -> &Path {
&self.workdir
}
#[must_use]
pub fn changed(&self) -> &BTreeSet<String> {
&self.changed
}
pub fn base_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
let Some((oid, _)) = self.files.get(rel) else {
return Ok(None);
};
let blob = self
.repo
.find_blob(*oid)
.with_context(|| format!("{rel} at the merge-base"))?;
Ok(Some(blob.data.clone()))
}
pub fn worktree_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
read_optional(&self.workdir.join(rel))
}
pub fn write_to(&self, dir: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt as _;
for (rel, (_, kind)) in &self.files {
let mode = match kind {
EntryKind::Blob => 0o644,
EntryKind::BlobExecutable => 0o755,
EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
};
let path = dir.join(rel);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("create {}", parent.display()))?;
}
let bytes = self.base_bytes(rel)?.unwrap_or_default();
fs::write(&path, bytes).with_context(|| format!("write {}", path.display()))?;
fs::set_permissions(&path, Permissions::from_mode(mode))
.with_context(|| format!("chmod {}", path.display()))?;
}
Ok(())
}
}
#[derive(Debug, PartialEq, Eq)]
enum Worktree {
Missing,
Link(Vec<u8>),
File(Vec<u8>),
}
impl Worktree {
fn read(path: &Path) -> Result<Self> {
use std::os::unix::ffi::OsStrExt as _;
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Self::Missing),
Err(error) => return Err(error).with_context(|| path.display().to_string()),
};
if metadata.file_type().is_symlink() {
let target = fs::read_link(path).with_context(|| path.display().to_string())?;
return Ok(Self::Link(target.as_os_str().as_bytes().to_vec()));
}
let bytes = fs::read(path).with_context(|| path.display().to_string())?;
Ok(Self::File(bytes))
}
}
pub fn read_optional(path: &Path) -> Result<Option<Vec<u8>>> {
match fs::read(path) {
Ok(bytes) => Ok(Some(bytes)),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(error).with_context(|| path.display().to_string()),
}
}
pub(crate) fn files_of(
tree: &gix::Tree<'_>,
) -> Result<BTreeMap<String, (gix::ObjectId, EntryKind)>> {
Ok(tree
.traverse()
.breadthfirst
.files()?
.into_iter()
.filter(|entry| !entry.mode.is_tree())
.map(|entry| {
(
entry.filepath.to_str_lossy().into_owned(),
(entry.oid, entry.mode.kind()),
)
})
.collect())
}
pub fn file_at(root: &Path, sha: &str, path: &Path) -> Result<Option<String>> {
let repo = discover(root).context("reading a file at a commit needs a git repository")?;
let rel = git_path(root, path, repo.workdir())
.with_context(|| format!("{} is not in the repository", path.display()))?;
let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
let commit = repo
.find_commit(id)
.with_context(|| format!("commit {sha} is not in the repository"))?;
Ok(blob_at(&commit.tree()?, &rel))
}
pub(crate) fn blob_at(tree: &gix::Tree<'_>, rel: &Path) -> Option<String> {
let entry = tree.lookup_entry_by_path(rel).ok()??;
let blob = entry.object().ok()?.try_into_blob().ok()?;
Some(String::from_utf8_lossy(&blob.data).into_owned())
}
pub fn files_named_at(
root: &Path,
sha: &str,
dir: &Path,
file_name: &str,
) -> Result<Vec<(String, String)>> {
let repo = discover(root).context("reading files at a commit needs a git repository")?;
let dir = dir
.canonicalize()
.with_context(|| format!("resolve {}", dir.display()))?;
let dir_rel = git_path(root, &dir, repo.workdir())
.with_context(|| format!("{} is not in the repository", dir.display()))?;
let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
let commit = repo
.find_commit(id)
.with_context(|| format!("commit {sha} is not in the repository"))?;
let mut found = Vec::new();
for (rel, (oid, kind)) in files_of(&commit.tree()?)? {
if !matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
continue;
}
let path = Path::new(&rel);
if path.file_name().and_then(|name| name.to_str()) != Some(file_name) {
continue;
}
let under_dir = if dir_rel.as_os_str().is_empty() {
path
} else if let Ok(stripped) = path.strip_prefix(&dir_rel) {
stripped
} else {
continue;
};
let blob = repo
.find_object(oid)
.with_context(|| format!("read {rel} at commit {sha}"))?
.try_into_blob()
.with_context(|| format!("{rel} at commit {sha} is not a blob"))?;
found.push((
under_dir.to_string_lossy().into_owned(),
String::from_utf8_lossy(&blob.data).into_owned(),
));
}
Ok(found)
}