gitpoulpi-cli-backend 1.4.0

GitBackend implementation that shells out to the system `git` binary, parsing only machine-readable output (porcelain v2, NUL-delimited logs).
Documentation
//! Folders a working-tree update could not remove.
//!
//! When an update deletes every file of a folder, git removes the folder too.
//! If the system will not let go of it (on Windows another program holds it:
//! an IDE, a terminal's current directory, the file manager), git carries on
//! and leaves the folder in place, empty. Such a folder is reported to the
//! caller as [`OpWarning::FolderLeftInPlace`] (through
//! `gitpoulpi_core::warnings`), and the operation still succeeds.
//!
//! Git's own warning is not relied on (`process::note_warnings` reads it
//! when there is one): some platforms stay silent, so the result is also
//! derived from what the update deleted and what is still on disk, the same
//! way on every platform.

use std::future::Future;
use std::path::Path;

use gitpoulpi_core::warnings::{self, OpWarning};
use gitpoulpi_core::Result;

use crate::process::run_lenient;

/// `HEAD`'s commit, `None` when it cannot be read (an unborn branch). Read
/// from the repository's directory without a process (a loose ref, else
/// `packed-refs`); anything else (a reftable repository) asks the system git.
fn head_of(root: &Path) -> Option<String> {
    if let Some(found) = head_from_files(root) {
        return Some(found);
    }
    let (ok, out) = run_lenient(root, &["rev-parse", "--verify", "-q", "HEAD"]).ok()?;
    let out = out.trim().to_string();
    (ok && !out.is_empty()).then_some(out)
}

fn head_from_files(root: &Path) -> Option<String> {
    use crate::conflicts::read_trimmed;
    let dir = gitpoulpi_core::paths::git_dir(root)?;
    let head = read_trimmed(&dir.join("HEAD"))?;
    let Some(name) = head.strip_prefix("ref: ") else {
        return Some(head);
    };
    let common = read_trimmed(&dir.join("commondir")).map_or_else(|| dir.clone(), |c| dir.join(c));
    let is_sha = |s: &str| matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit());
    for base in [&dir, &common] {
        if let Some(sha) = read_trimmed(&base.join(name)).filter(|s| is_sha(s)) {
            return Some(sha);
        }
    }
    let packed = std::fs::read_to_string(common.join("packed-refs")).ok()?;
    packed.lines().find_map(|line| {
        let (sha, refname) = line.split_once(' ')?;
        (refname == name && is_sha(sha)).then(|| sha.to_string())
    })
}

/// Every folder above a file that went from tree `old` to tree `new` as a
/// deletion, outermost first, `/`-separated and relative to the root.
fn folders_emptied(root: &Path, old: &str, new: &str) -> Vec<String> {
    let Ok((true, out)) = run_lenient(
        root,
        &[
            "diff",
            "--name-only",
            "--diff-filter=D",
            "--no-renames",
            "-z",
            old,
            new,
        ],
    ) else {
        return Vec::new();
    };
    let mut folders: Vec<String> = Vec::new();
    for path in out.split('\0').filter(|p| !p.is_empty()) {
        let mut at = 0;
        while let Some(slash) = path[at..].find('/') {
            at += slash;
            let folder = &path[..at];
            if !folders.iter().any(|f| f == folder) {
                folders.push(folder.to_string());
            }
            at += 1;
        }
    }
    folders
}

/// Records every folder of `folders` that is still on disk, empty: the update
/// would have removed it had it been able to.
fn note_left(root: &Path, folders: &[String]) {
    for folder in folders {
        let dir = root.join(folder);
        let empty = std::fs::read_dir(&dir).is_ok_and(|mut entries| entries.next().is_none());
        if empty {
            warnings::record(
                root,
                OpWarning::FolderLeftInPlace {
                    path: folder.clone(),
                },
            );
        }
    }
}

/// Runs `update`, which moves `HEAD` and the working tree, and reports the
/// folders it left in place.
pub(crate) fn watch<T>(root: &Path, update: impl FnOnce() -> Result<T>) -> Result<T> {
    let before = head_of(root);
    let result = update();
    note_moved(root, before);
    result
}

/// [`watch`] for an `async` update.
pub(crate) async fn watch_async<T, F>(root: &Path, update: F) -> Result<T>
where
    F: Future<Output = Result<T>>,
{
    let before = head_of(root);
    let result = update.await;
    note_moved(root, before);
    result
}

fn note_moved(root: &Path, before: Option<String>) {
    let Some(before) = before else { return };
    let Some(after) = head_of(root) else { return };
    if before != after {
        note_left(root, &folders_emptied(root, &before, &after));
    }
}

/// Runs `apply`, which writes the changes of the stash commit `stash` into
/// the working tree (`HEAD` does not move), and reports the folders it left in
/// place.
pub(crate) fn watch_stash<T>(
    root: &Path,
    stash: &str,
    apply: impl FnOnce() -> Result<T>,
) -> Result<T> {
    // The stash is gone after a pop: read what it deletes first.
    let folders = folders_emptied(root, &format!("{stash}^1"), stash);
    let result = apply();
    note_left(root, &folders);
    result
}