use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum OpWarning {
FolderLeftInPlace { path: String },
}
impl std::fmt::Display for OpWarning {
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)
}
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);
}
}
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()
}
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());
}
}