gitpoulpi-core 1.4.0

GitPoulpi domain model, GitBackend and trait. No I/O-framework dependencies.
Documentation
//! Non-fatal things an operation reports besides its result.
//!
//! A backend that completes an operation but could not do part of it records
//! a warning here, keyed by the repository root; the daemon takes them after
//! the request and returns them with the response, so every frontend can show
//! them (status line, Activity Log, CLI/MCP output). The recorder is a
//! process-wide map and not a return value because the same note comes out of
//! many operations (every one that updates the working tree) and out of
//! `async` ones that change threads.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

use serde::{Deserialize, Serialize};

/// One warning of a completed operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum OpWarning {
    /// The update removed every file of a folder, but the folder itself could
    /// not be removed (another program holds it open, as an IDE, a terminal's
    /// current directory or the file manager does): like system git, the
    /// operation went on and the folder is left in place, empty. `path` is
    /// relative to the repository root, with `/` separators.
    FolderLeftInPlace { path: String },
}

impl std::fmt::Display for OpWarning {
    /// The English text (CLI, MCP and log output); the TUI has its own
    /// localized wording per kind.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OpWarning::FolderLeftInPlace { path } => {
                write!(f, "Folder {path} left in place: in use by another program")
            }
        }
    }
}

type Pending = Mutex<HashMap<PathBuf, Vec<OpWarning>>>;

fn pending() -> &'static Pending {
    static PENDING: OnceLock<Pending> = OnceLock::new();
    PENDING.get_or_init(Default::default)
}

/// Records `warning` for an operation running in the repository at `root`.
pub fn record(root: &Path, warning: OpWarning) {
    let mut map = pending().lock().unwrap_or_else(|e| e.into_inner());
    let list = map.entry(root.to_path_buf()).or_default();
    if !list.contains(&warning) {
        list.push(warning);
    }
}

/// Takes (and forgets) the warnings recorded for `root` since the last take.
pub fn take(root: &Path) -> Vec<OpWarning> {
    let mut map = pending().lock().unwrap_or_else(|e| e.into_inner());
    map.remove(root).unwrap_or_default()
}

/// The folders git's `warning: unable to rmdir '<path>': <reason>` lines of
/// `stderr` name (git's messages must be in English: see the callers).
pub fn parse_rmdir_warnings(stderr: &str) -> Vec<OpWarning> {
    const MARK: &str = "unable to rmdir '";
    stderr
        .lines()
        .filter_map(|line| {
            let rest = &line[line.find(MARK)? + MARK.len()..];
            let path = &rest[..rest.rfind('\'')?];
            let path = path.replace('\\', "/");
            let path = path.trim_end_matches('/');
            (!path.is_empty()).then(|| OpWarning::FolderLeftInPlace { path: path.into() })
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_git_rmdir_warnings() {
        let err = "warning: unable to rmdir 'legacy': Permission denied\nHEAD is now at abc\n";
        assert_eq!(
            parse_rmdir_warnings(err),
            vec![OpWarning::FolderLeftInPlace {
                path: "legacy".into()
            }]
        );
        assert!(parse_rmdir_warnings("nothing here").is_empty());
    }

    #[test]
    fn record_then_take_is_per_repository_and_deduplicated() {
        let a = Path::new("/warnings-test/a");
        let w = OpWarning::FolderLeftInPlace { path: "x".into() };
        record(a, w.clone());
        record(a, w.clone());
        assert!(take(Path::new("/warnings-test/b")).is_empty());
        assert_eq!(take(a), vec![w]);
        assert!(take(a).is_empty());
    }
}