verctl-git 0.9.6

Git repository access and history queries for verctl
Documentation
use std::env;
use std::fs::{self, File, Metadata};
use std::io::Read;
use std::path::{self, Component, Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};
use gix::actor::Signature;
use gix::date::Time;
use gix::filter::Pipeline;
use gix::index::State;
use gix::objs::Commit;
use gix::objs::tree::EntryKind;
use gix::refs::transaction::PreviousValue;
use verctl_core::process;
use verctl_core::repo::Repo;

use crate::discover;

/// What [`commit_branch_and_push`] did: `Empty` when the tree was unchanged.
///
/// Not `#[non_exhaustive]`: `verctl-release` matches both outcomes
/// exhaustively.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum PushOutcome {
    /// No version files changed.
    Empty,
    /// Branch was updated and pushed.
    Pushed,
}

/// Commits `paths` onto `branch` without moving HEAD, then force-pushes
/// `branch` to `github` over HTTPS with `token`.
///
/// When `paths` leave the tree unchanged, nothing is pushed and the result is
/// [`PushOutcome::Empty`].
///
/// # Errors
///
/// Returns an error when:
///
/// - `root` is not inside a git repository;
/// - the repository has no workdir, or HEAD names no commit;
/// - a path lies outside the workdir, is not UTF-8, or cannot be read or
///   filtered;
/// - the commit or branch ref cannot be written;
/// - `git push` fails or runs past five minutes.
pub fn commit_branch_and_push(
    root: &Path,
    branch: &str,
    message: &str,
    token: &str,
    github: &Repo,
    paths: &[PathBuf],
) -> Result<PushOutcome> {
    let repo = discover(root).context("open git repository")?;
    let workdir = absolute_workdir(&repo)?;
    let parent = repo.head_commit().context("HEAD commit")?;
    let Some(_) = write_commit_on_branch(&repo, &workdir, &parent, branch, message, paths)? else {
        return Ok(PushOutcome::Empty);
    };
    let url = format!("https://github.com/{}/{}.git", github.owner, github.name);
    push(repo.git_dir(), &url, branch, token)?;
    Ok(PushOutcome::Pushed)
}

/// The working tree as an absolute path. gix reports it as it was discovered,
/// so a repository found from `.` has `.` for a workdir, and no path would
/// strip that prefix.
pub(crate) fn absolute_workdir(repo: &gix::Repository) -> Result<PathBuf> {
    let workdir = repo.workdir().context("repository has no workdir")?;
    path::absolute(workdir).with_context(|| format!("resolve the workdir {}", workdir.display()))
}

/// The token reaches `git push` through this variable, which only the push's
/// own process sees.
const PUSH_TOKEN: &str = "VERCTL_GIT_TOKEN";

/// The credential helper `git push` runs. For `get` it supplies
/// `x-access-token` and the token from [`PUSH_TOKEN`]. It ignores `store` and
/// `erase`, so the token is never in argv, a URL, or a credential store.
const PUSH_CREDENTIAL_HELPER: &str = r#"!f() { test "$1" = get || return 0; echo username=x-access-token; echo "password=$VERCTL_GIT_TOKEN"; }; f"#;

/// How long a push may run before it is killed.
const PUSH_TIMEOUT: Duration = Duration::from_mins(5);

/// Force-pushes `branch` to `url` with the `git` binary, because gix cannot
/// push yet.
///
/// `credential.helper=` first clears every helper the user configured, so no
/// keychain supplies a credential or stores one in its place.
/// `GIT_TERMINAL_PROMPT=0` makes a rejected token fail instead of waiting for
/// input.
///
/// The repository's own hooks do not run (`--no-verify`): the branch is
/// generated, and libgit2, which pushed it before, never ran hooks either.
///
/// `--git-dir` names the repository outright, so a `GIT_DIR` a hook exported
/// cannot redirect the push. The error, which carries git's stderr, can contain
/// the URL but not the token, since git only ever saw the variable's name.
pub(crate) fn push(git_dir: &Path, url: &str, branch: &str, token: &str) -> Result<()> {
    let git_dir = git_dir
        .canonicalize()
        .with_context(|| format!("git directory {}", git_dir.display()))?;
    let git_dir = format!(
        "--git-dir={}",
        git_dir.to_str().context("git directory is not UTF-8")?
    );
    let helper = format!("credential.helper={PUSH_CREDENTIAL_HELPER}");
    let refspec = format!("+refs/heads/{branch}:refs/heads/{branch}");
    let argv = process::argv(&[
        "git",
        &git_dir,
        "-c",
        "credential.helper=",
        "-c",
        &helper,
        "push",
        "--no-verify",
        "--quiet",
        url,
        &refspec,
    ]);
    process::run_limited(
        &argv,
        &[(PUSH_TOKEN, token), ("GIT_TERMINAL_PROMPT", "0")],
        PUSH_TIMEOUT,
    )
    .context("git push")?;
    Ok(())
}

/// Writes a commit that starts from `parent`'s tree and takes `paths` from the
/// working tree, then points `branch` at it. HEAD, the index, and the working
/// tree are left alone, because the tree is edited in memory. `None` when the
/// tree is unchanged.
///
/// A path missing from the working tree is removed from the tree. Each file
/// passes through the `.gitattributes` clean filters first, as `git add` runs
/// them. So `text` normalization and Large File Storage (LFS) pointers match
/// what git would store.
pub(crate) fn write_commit_on_branch(
    repo: &gix::Repository,
    workdir: &Path,
    parent: &gix::Commit<'_>,
    branch: &str,
    message: &str,
    paths: &[PathBuf],
) -> Result<Option<gix::ObjectId>> {
    let parent_tree = parent.tree_id().context("HEAD tree")?.detach();
    let mut editor = repo.edit_tree(parent_tree).context("edit HEAD tree")?;
    let (mut filters, index) = repo
        .filter_pipeline(None)
        .context("load the .gitattributes filters")?;
    for path in paths {
        let rel = workdir_rel(workdir, path)?;
        let name = rel
            .to_str()
            .with_context(|| format!("path is not UTF-8: {}", rel.display()))?
            .to_owned();
        let abs = workdir.join(&rel);
        if abs.exists() {
            let (kind, data) = worktree_entry(&mut filters, &index, &abs, &rel)?;
            let blob = repo
                .write_blob(data)
                .with_context(|| format!("git add {name}"))?;
            editor
                .upsert(&name, kind, blob)
                .with_context(|| format!("git add {name}"))?;
        } else {
            editor
                .remove(&name)
                .with_context(|| format!("git rm {name}"))?;
        }
    }
    let tree = editor.write().context("write tree")?.detach();
    if tree == parent_tree {
        return Ok(None);
    }
    let signature = signature(repo);
    let commit = Commit {
        tree,
        parents: [parent.id().detach()].into_iter().collect(),
        author: signature.clone(),
        committer: signature,
        encoding: None,
        message: message.into(),
        extra_headers: Vec::new(),
    };
    let id = repo.write_object(&commit).context("git commit")?.detach();
    repo.reference(
        format!("refs/heads/{branch}"),
        id,
        PreviousValue::Any,
        "verctl: version packages",
    )
    .context("git commit")?;
    Ok(Some(id))
}

/// The tree entry kind and content for the file at `abs`, which sits at `rel`
/// in the working tree. A symbolic link stores its target. A file stores what
/// the clean `filters` make of it and keeps its executable bit.
fn worktree_entry(
    filters: &mut Pipeline<'_>,
    index: &State,
    abs: &Path,
    rel: &Path,
) -> Result<(EntryKind, Vec<u8>)> {
    let meta = fs::symlink_metadata(abs).with_context(|| abs.display().to_string())?;
    if meta.file_type().is_symlink() {
        let target = fs::read_link(abs).with_context(|| abs.display().to_string())?;
        let target = target
            .to_str()
            .with_context(|| format!("link target is not UTF-8: {}", abs.display()))?;
        return Ok((EntryKind::Link, target.as_bytes().to_vec()));
    }
    let file = File::open(abs).with_context(|| abs.display().to_string())?;
    let mut clean = filters
        .convert_to_git(file, rel, index)
        .with_context(|| format!("filter {}", rel.display()))?;
    let mut data = Vec::new();
    Read::read_to_end(&mut clean, &mut data)
        .with_context(|| format!("filter {}", rel.display()))?;
    Ok((blob_entry_mode(&meta), data))
}

#[cfg(unix)]
fn blob_entry_mode(meta: &Metadata) -> EntryKind {
    use std::os::unix::fs::PermissionsExt;
    if meta.permissions().mode() & 0o111 == 0 {
        EntryKind::Blob
    } else {
        EntryKind::BlobExecutable
    }
}

#[cfg(not(unix))]
fn blob_entry_mode(_meta: &Metadata) -> EntryKind {
    EntryKind::Blob
}

/// `path` relative to the working tree. A relative `path` is taken from the
/// workdir. An absolute one may spell the workdir as given or canonical. The
/// dirty-path check returns canonical paths. The plan keeps the spelling
/// verctl was started with, and a checkout behind a symlink spells them
/// differently.
///
/// Both spellings of the workdir are tried against `path` as given and against
/// `path` with its parent canonicalized. The second try still works for a file
/// that was deleted.
pub(crate) fn workdir_rel(workdir: &Path, path: &Path) -> Result<PathBuf> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        workdir.join(path)
    };
    let normalized: PathBuf = absolute
        .components()
        .filter(|component| !matches!(component, Component::CurDir))
        .collect();
    let workdirs = [Some(workdir.to_path_buf()), workdir.canonicalize().ok()];
    let through_parent = normalized
        .parent()
        .and_then(|parent| parent.canonicalize().ok())
        .zip(normalized.file_name())
        .map(|(parent, name)| parent.join(name));
    let paths = [Some(normalized.clone()), through_parent];
    paths
        .iter()
        .flatten()
        .find_map(|path| {
            workdirs
                .iter()
                .flatten()
                .find_map(|workdir| path.strip_prefix(workdir).ok())
        })
        .map(Path::to_path_buf)
        .with_context(|| format!("path outside workdir: {}", normalized.display()))
}

/// Who the Version PR commit is by: `user.name` and `user.email` when the
/// repository's git config sets both, else the [`fallback_identity`].
fn signature(repo: &gix::Repository) -> Signature {
    let time = Time::now_local_or_utc();
    let config = repo.config_snapshot();
    if let (Some(name), Some(email)) = (config.string("user.name"), config.string("user.email")) {
        return Signature { name, email, time };
    }
    let (name, email) = fallback_identity();
    Signature {
        name: name.into(),
        email: email.into(),
        time,
    }
}

/// Fallback author identity when git config sets none (`GIT_AUTHOR_NAME` or
/// `GITHUB_ACTOR`, else `verctl`, with `GIT_AUTHOR_EMAIL` or GitHub noreply).
pub(crate) fn fallback_identity() -> (String, String) {
    let name = env::var("GIT_AUTHOR_NAME")
        .or_else(|_| env::var("GITHUB_ACTOR"))
        .unwrap_or_else(|_| "verctl".into());
    let email =
        env::var("GIT_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{name}@users.noreply.github.com"));
    (name, email)
}