verctl-git 0.9.7

Git repository access and history queries for verctl
Documentation
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};

/// What a missing or unreachable merge-base means for a version comparison.
const NEED_FULL_FETCH: &str =
    "cannot compare versions against the default branch (need a full fetch, not a shallow clone)";

/// File contents at the merge-base of HEAD and the default branch.
///
/// Paths are relative to `root` (the directory containing `.ctl/`) and are
/// mapped onto the git workdir so `-c crates/foo/.ctl/ver.yaml` still hits the
/// right blob. One repository open for the whole list.
///
/// Every entry is `None` when there is no repository, or when the repository
/// has no `origin` remote and none of the candidate refs exists. A path
/// missing from the merge-base tree is `None` for that entry only.
///
/// # Errors
///
/// Returns an error when:
///
/// - `origin` exists but resolving its default branch ref fails;
/// - HEAD names no commit;
/// - there is no merge-base (a shallow clone, for one);
/// - the merge-base commit or its tree cannot be read.
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())
}

/// `rel` as a path inside the repository. A relative path joins the
/// canonical root without being canonicalized itself. A file deleted from the
/// working tree still resolves to its committed copy this way. The version
/// guard has to see a manifest that a pull request removed. An absolute path
/// to a file that is gone resolves through its canonical directory, so a
/// fragment a commit deleted still names its committed copy.
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)
}

/// The tree at the merge-base of HEAD and the pull request's base, and the
/// paths the working tree changes against it. The content check for a Version
/// PR replays the version step on this tree.
#[derive(Debug)]
pub struct MergeBase {
    repo: gix::Repository,
    workdir: PathBuf,
    files: BTreeMap<String, (gix::ObjectId, EntryKind)>,
    changed: BTreeSet<String>,
}

impl MergeBase {
    /// Read the merge-base tree and list each tracked path that differs from
    /// it: committed on the branch, modified, or deleted. A symlink or a
    /// submodule differs when its entry on HEAD does. Untracked files are left
    /// out.
    ///
    /// `None` when there is no repository, or no `origin` and none of the
    /// candidate refs, as for [`files_on_merge_base`].
    ///
    /// # Errors
    ///
    /// Returns an error under the conditions of [`files_on_merge_base`], or
    /// when a tree, a blob, a working tree file, or `git status` cannot be
    /// read.
    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))
    }

    /// Whether `rel` differs from the merge-base. A regular file compares by
    /// its bytes in the working tree, and a symlink by its target there, so an
    /// uncommitted edit counts. A submodule compares by its commit on HEAD:
    /// an uncommitted submodule move is out of scope, since CI checks out a
    /// commit.
    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))?)
    }

    /// The working tree's root, canonical.
    #[must_use]
    pub fn workdir(&self) -> &Path {
        &self.workdir
    }

    /// Each path, relative to the working tree's root, that differs from the
    /// merge-base. A file differs by its bytes, a symlink by its target, and a
    /// submodule by its commit.
    #[must_use]
    pub fn changed(&self) -> &BTreeSet<String> {
        &self.changed
    }

    /// A file's bytes at the merge-base, or `None` when it has no file there.
    ///
    /// # Errors
    ///
    /// Returns an error when the blob cannot be read.
    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()))
    }

    /// A file's bytes in the working tree, or `None` when it is missing.
    ///
    /// # Errors
    ///
    /// Returns an error when the file exists but cannot be read.
    pub fn worktree_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
        read_optional(&self.workdir.join(rel))
    }

    /// Write every regular file of the merge-base tree under `dir`. Each file
    /// keeps its executable bit.
    ///
    /// The whole tree is written because the replay's readers are not a fixed
    /// list. `cargo metadata` expands member globs and needs each member's
    /// target files. A pin or a served file can name any path. Symlinks
    /// are not recreated, so no write through one leaves `dir`.
    ///
    /// # Errors
    ///
    /// Returns an error when a blob cannot be read or a file cannot be
    /// written.
    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(())
    }
}

/// What the working tree contains at a path, as the merge-base tree records it:
/// a symlink's target, or a file's bytes.
#[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))
    }
}

/// A file's bytes, or `None` when it does not exist.
///
/// # Errors
///
/// Returns an error when the file exists but cannot be read.
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()),
    }
}

/// Every entry in `tree` other than a directory, by path, with its object and
/// kind. A symlink or a submodule contains no bytes the version step writes, so
/// the content check never replays one. It still lists one that changed.
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())
}

/// The text of `path` at commit `sha`, or `None` when that commit contains no
/// such file.
///
/// # Errors
///
/// Returns an error when `root` is in no repository, when `path` is outside
/// it, or when `sha` names no commit in it.
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())
}

/// Every blob named `file_name` under `dir` at commit `sha`, as
/// `(path relative to dir, UTF-8 text)` pairs.
///
/// # Errors
///
/// Returns an error when `root` is in no repository, when `dir` is outside it,
/// when `sha` names no commit in it, or when reading the tree or a blob fails.
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)
}