use crate::error::AppError;
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
fs,
io::Write,
path::{Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
};
pub const CONFIG_TEMPLATE: &str = include_str!("../config.toml");
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
#[serde(deny_unknown_fields)]
pub struct Config {
#[serde(default)]
pub scan: ScanConfig,
#[serde(default)]
pub cleanup: CleanupConfig,
}
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
#[serde(deny_unknown_fields)]
pub struct CleanupConfig {
#[serde(default)]
pub allowed_output_roots: Vec<PathBuf>,
#[serde(default)]
pub policy: CleanupPolicyConfig,
}
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
#[serde(deny_unknown_fields)]
pub struct CleanupPolicyConfig {
#[serde(default)]
pub min_reclaimable_bytes: u64,
pub min_inactive_seconds: Option<u64>,
#[serde(default)]
pub include: Vec<String>,
#[serde(default)]
pub exclude: Vec<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ScanConfig {
#[serde(default = "default_recency")]
pub recency_seconds: u64,
pub root: Option<PathBuf>,
#[serde(default)]
pub ignore: Vec<String>,
#[serde(default)]
pub unignore: Vec<PathBuf>,
#[serde(default = "default_retention")]
pub learned_root_retention_days: u32,
}
impl Default for ScanConfig {
fn default() -> Self {
Self {
recency_seconds: 300,
root: None,
ignore: vec![],
unignore: vec![],
learned_root_retention_days: 30,
}
}
}
fn default_recency() -> u64 {
300
}
fn default_retention() -> u32 {
30
}
#[derive(Clone, Debug)]
pub struct ConfigPathResolver {
override_path: Option<PathBuf>,
}
impl ConfigPathResolver {
pub fn new(path: Option<PathBuf>) -> Self {
Self {
override_path: path,
}
}
pub fn path(&self) -> Result<PathBuf, AppError> {
if let Some(p) = &self.override_path {
return Ok(p.clone());
}
let d = ProjectDirs::from("", "", "cargo-cleanme").ok_or_else(|| {
AppError::Config("platform config directory is unavailable; use --config".into())
})?;
Ok(d.config_dir().join("config.toml"))
}
}
pub fn load(path: &Path) -> Result<Config, AppError> {
let mut c = if path.exists() {
let s = fs::read_to_string(path)
.map_err(|e| AppError::Config(format!("cannot read {}: {e}", path.display())))?;
toml::from_str(&s)
.map_err(|e| AppError::Config(format!("cannot parse {}: {e}", path.display())))?
} else {
Config::default()
};
if c.scan.recency_seconds == 0 {
return Err(AppError::Config(
"scan.recency_seconds must be greater than 0; 0 would disable the inactivity guard that keeps recently used artifacts out of cleanup".into(),
));
}
if c.scan.recency_seconds > u64::MAX / 1_000_000_000 {
return Err(AppError::Config("scan.recency_seconds is too large".into()));
}
if c.scan.learned_root_retention_days > 3650 {
return Err(AppError::Config(
"scan.learned_root_retention_days must be between 0 and 3650".into(),
));
}
if let Some(p) = &c.scan.root {
require_absolute(p, "scan.root")?;
}
for p in &c.scan.ignore {
if !Path::new(p).is_absolute() {
return Err(AppError::Config(format!(
"ignore pattern must be absolute: {p}"
)));
}
}
for p in &c.scan.unignore {
require_absolute(p, "unignore")?;
}
for p in &c.cleanup.allowed_output_roots {
require_absolute(p, "cleanup.allowed_output_roots")?;
}
if let Some(seconds) = c.cleanup.policy.min_inactive_seconds
&& seconds > u64::MAX / 1_000_000_000
{
return Err(AppError::Config(
"cleanup.policy.min_inactive_seconds is too large".into(),
));
}
for pattern in c
.cleanup
.policy
.include
.iter()
.chain(&c.cleanup.policy.exclude)
{
globset::Glob::new(pattern).map_err(|e| {
AppError::Config(format!("invalid cleanup policy glob {pattern:?}: {e}"))
})?;
}
for pattern in &c.scan.ignore {
globset::Glob::new(pattern)
.map_err(|e| AppError::Config(format!("invalid scan.ignore glob {pattern:?}: {e}")))?;
}
c.scan.ignore = c
.scan
.ignore
.iter()
.map(|p| canonical_pattern_prefix(p, PatternKind::Glob))
.collect();
c.scan.unignore = c
.scan
.unignore
.iter()
.map(|p| {
PathBuf::from(canonical_pattern_prefix(
&p.to_string_lossy(),
PatternKind::Literal,
))
})
.collect();
c.cleanup.policy.include = canonical_policy_patterns(&c.cleanup.policy.include);
c.cleanup.policy.exclude = canonical_policy_patterns(&c.cleanup.policy.exclude);
for pattern in &c.scan.ignore {
globset::Glob::new(pattern)
.map_err(|e| AppError::Config(format!("invalid scan.ignore glob {pattern:?}: {e}")))?;
}
for pattern in c
.cleanup
.policy
.include
.iter()
.chain(&c.cleanup.policy.exclude)
{
globset::Glob::new(pattern).map_err(|e| {
AppError::Config(format!("invalid cleanup policy glob {pattern:?}: {e}"))
})?;
}
Ok(c)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PatternKind {
Glob,
Literal,
}
fn glob_spelling(path: &Path) -> String {
glob_spelling_with(&path.to_string_lossy(), std::path::MAIN_SEPARATOR)
}
fn glob_spelling_with(canonical: &str, separator: char) -> String {
let canonical = if separator == '\\' {
dereference(canonical)
} else {
Cow::Borrowed(canonical)
};
canonical.replace(separator, "/")
}
fn dereference(canonical: &str) -> Cow<'_, str> {
if let Some(unc) = canonical.strip_prefix(r"\\?\UNC\") {
return Cow::Owned(format!(r"\\{unc}"));
}
match canonical.strip_prefix(r"\\?\") {
Some(rest) => Cow::Borrowed(rest),
None => Cow::Borrowed(canonical),
}
}
fn escape_glob_literal(path: &str) -> Option<String> {
let mut out = String::with_capacity(path.len());
for c in path.chars() {
match c {
'*' | '?' | '[' | ']' => {
out.push('[');
out.push(c);
out.push(']');
}
'{' | '}' => return None,
'\\' => out.push_str(r"\\"),
_ => out.push(c),
}
}
Some(out)
}
fn dangling_trailing_escape(prefix: &str, backslash_escapes: bool) -> bool {
backslash_escapes && prefix.ends_with('\\')
}
fn is_windows_drive_root(bare: &str) -> bool {
bare.len() == 2 && bare.as_bytes()[1] == b':' && bare.as_bytes()[0].is_ascii_alphabetic()
}
pub fn canonical_policy_patterns(patterns: &[String]) -> Vec<String> {
patterns
.iter()
.map(|p| canonical_pattern_prefix(p, PatternKind::Glob))
.collect()
}
fn canonical_pattern_prefix(pattern: &str, kind: PatternKind) -> String {
let cut = pattern.find(['*', '?', '[', '{']).unwrap_or(pattern.len());
let (prefix, tail) = pattern.split_at(cut);
if dangling_trailing_escape(prefix, !std::path::is_separator('\\')) {
return pattern.to_owned();
}
let bare = prefix.trim_end_matches(['/', '\\']);
if bare.is_empty() || (!Path::new(bare).is_absolute() && !is_windows_drive_root(bare)) {
return pattern.to_owned();
}
if is_windows_drive_root(bare) {
return pattern.to_owned();
}
let separators = &prefix[bare.len()..];
match fs::canonicalize(bare) {
Ok(canonical) => {
let native = canonical.to_string_lossy();
if native == bare {
pattern.to_owned()
} else {
match kind {
PatternKind::Literal => format!("{native}{separators}{tail}"),
PatternKind::Glob => match escape_glob_literal(&glob_spelling(&canonical)) {
Some(literal) => format!("{literal}{separators}{tail}"),
None => pattern.to_owned(),
},
}
}
}
Err(_) => pattern.to_owned(),
}
}
pub fn load_or_create(path: &Path) -> Result<Config, AppError> {
if !path.exists() {
create_initial(path)?;
if !path.exists() {
return Err(AppError::Config(format!(
"config file {} vanished after creation; refusing to use defaults",
path.display()
)));
}
}
load(path)
}
pub fn ensure_exists(path: &Path) -> Result<(), AppError> {
if !path.exists() {
create_initial(path)?;
}
Ok(())
}
fn require_absolute(p: &Path, field: &str) -> Result<(), AppError> {
if !p.is_absolute() {
Err(AppError::Config(format!(
"{field} must be absolute: {}",
p.display()
)))
} else {
Ok(())
}
}
static STAGING_NONCE: AtomicU64 = AtomicU64::new(0);
fn step_error(step: &str, e: std::io::Error) -> std::io::Error {
std::io::Error::new(e.kind(), format!("{step} failed: {e}"))
}
fn create_initial(path: &Path) -> Result<(), AppError> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent).map_err(|e| step_error("creating the config directory", e))?;
}
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."));
if !parent.exists() {
return Err(AppError::Config(format!(
"config directory is unavailable: {}",
parent.display()
)));
}
let file_name = path
.file_name()
.map(|s| s.to_os_string())
.unwrap_or_else(|| std::ffi::OsString::from("config.toml"));
for attempt in 0..100 {
let nonce = STAGING_NONCE.fetch_add(1, Ordering::Relaxed);
let mut temp_name = file_name.clone();
temp_name.push(format!(".tmp.{}.{}.{}", std::process::id(), nonce, attempt));
let temp = parent.join(temp_name);
let created = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp);
let mut f = match created {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(AppError::Io(step_error("creating a staging file", e))),
};
let write_result: std::io::Result<()> = (|| {
f.write_all(CONFIG_TEMPLATE.as_bytes())
.map_err(|e| step_error("writing the staging file", e))?;
f.sync_all()
.map_err(|e| step_error("flushing the staging file", e))?;
drop(f);
match fs::hard_link(&temp, path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::Unsupported => {
let mut published = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|e| step_error("publishing the config", e))?;
let written = published
.write_all(CONFIG_TEMPLATE.as_bytes())
.and_then(|()| published.sync_all());
if let Err(e) = written {
drop(published);
let _ = fs::remove_file(path);
return Err(step_error("writing the config", e));
}
}
Err(e) => return Err(step_error("publishing the config", e)),
}
if let Err(e) = fs::remove_file(&temp) {
eprintln!(
"cargo-cleanme: could not remove staging file {}: {e}",
temp.display()
);
}
Ok(())
})();
if let Err(e) = write_result {
let _ = fs::remove_file(&temp);
if path.is_file() {
return Ok(());
}
if path.exists() {
return Err(AppError::Config(format!(
"refusing to replace non-file config {}: {e}",
path.display()
)));
}
return Err(AppError::Io(e));
}
return Ok(());
}
Err(AppError::Config(format!(
"could not create a temporary config beside {}",
path.display()
)))
}
pub fn show(config: &Config) -> Result<String, AppError> {
toml::to_string_pretty(config).map_err(|e| AppError::Config(e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
fn toml_string(value: &str) -> String {
toml::Value::String(value.to_owned()).to_string()
}
#[cfg(unix)]
#[test]
fn patterns_are_canonicalized_so_exclusions_actually_apply() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let real = d.path().join("real");
fs::create_dir_all(real.join("workspace")).unwrap();
let link_parent = d.path().join("link");
fs::create_dir_all(&link_parent).unwrap();
let link = link_parent.join("real");
symlink(&real, &link).unwrap();
assert_ne!(
link.display().to_string(),
real.display().to_string(),
"the fixture needs a non-canonical spelling"
);
let config = d.path().join("config.toml");
let shell_spelled = format!("{}/*", link.display());
fs::write(
&config,
format!(
"[scan]\nignore = [{}]\n[cleanup.policy]\nexclude = [{}]\n",
toml_string(&shell_spelled),
toml_string(&shell_spelled)
),
)
.unwrap();
let loaded = load(&config).unwrap();
let canonical_prefix = fs::canonicalize(&real).unwrap();
assert_eq!(
loaded.scan.ignore,
vec![format!("{}/*", canonical_prefix.display())]
);
assert_eq!(
loaded.cleanup.policy.exclude,
vec![format!("{}/*", canonical_prefix.display())]
);
fs::write(
&config,
format!(
"[cleanup.policy]\nexclude = [{}]\n",
toml_string(&link.display().to_string())
),
)
.unwrap();
assert_eq!(
load(&config).unwrap().cleanup.policy.exclude,
vec![canonical_prefix.display().to_string()]
);
fs::write(
&config,
format!(
"[cleanup.policy]\nexclude = [{}]\n",
toml_string(&format!("{}/does/not/exist/*", link.display()))
),
)
.unwrap();
assert_eq!(
load(&config).unwrap().cleanup.policy.exclude,
vec![format!("{}/does/not/exist/*", link.display())]
);
assert_eq!(
canonical_pattern_prefix("relative/*", PatternKind::Glob),
"relative/*",
"relative patterns keep their spelling"
);
}
#[cfg(unix)]
#[test]
fn a_canonical_spelling_cannot_inject_glob_characters() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let base = fs::canonicalize(d.path()).unwrap();
let real = base.join("real[abc]");
fs::create_dir_all(&real).unwrap();
for sibling in ["reala", "realb"] {
fs::create_dir_all(base.join(sibling)).unwrap();
}
let link = base.join("link");
symlink(&real, &link).unwrap();
assert_ne!(
link.display().to_string(),
real.display().to_string(),
"premise: the fixture needs a spelling that is not the canonical one, \
or the rewrite never has a bracketed name to splice"
);
let config = base.join("config.toml");
fs::write(
&config,
format!(
"[scan]\nignore = [{}]\n",
toml_string(&format!("{}/*", link.display()))
),
)
.unwrap();
let ignore = load(&config).unwrap().scan.ignore;
assert_eq!(ignore.len(), 1);
let matcher = globset::Glob::new(&ignore[0]).unwrap().compile_matcher();
assert!(
matcher.is_match(format!("{}/proj", real.display())),
"the named tree must still match: {}",
ignore[0]
);
for sibling in ["reala", "realb"] {
assert!(
!matcher.is_match(format!("{}/{}/proj", base.display(), sibling)),
"{} must not be pruned by {}",
sibling,
ignore[0]
);
}
let literal =
canonical_pattern_prefix(&format!("{}/*", link.display()), PatternKind::Literal);
assert_eq!(literal, format!("{}/*", real.display()));
let braces = base.join("a{b}c");
fs::create_dir_all(&braces).unwrap();
let brace_link = base.join("bracelink");
symlink(&braces, &brace_link).unwrap();
let written = format!("{}/*", brace_link.display());
assert_eq!(
canonical_pattern_prefix(&written, PatternKind::Glob),
written,
"a `{{` in the canonical spelling cannot be escaped, so the pattern is untouched"
);
}
#[cfg(unix)]
#[test]
fn a_command_line_policy_pattern_is_canonicalized_like_a_configured_one() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let base = fs::canonicalize(d.path()).unwrap();
let real = base.join("real/proj");
fs::create_dir_all(&real).unwrap();
let link = base.join("link");
symlink(base.join("real"), &link).unwrap();
assert_ne!(
link.display().to_string(),
real.display().to_string(),
"premise: the fixture needs a spelling that is not the canonical one, \
or the rewrite never runs"
);
let written = vec![format!("{}/*", link.display())];
let canonical = canonical_policy_patterns(&written);
assert_eq!(
canonical,
vec![format!("{}/*", base.join("real").display())]
);
let matcher = globset::Glob::new(&canonical[0]).unwrap().compile_matcher();
assert!(
matcher.is_match(format!("{}/proj", base.join("real").display())),
"the rewritten pattern must match the canonical root: {}",
canonical[0]
);
let spelled = globset::Glob::new(&written[0]).unwrap().compile_matcher();
assert!(
!spelled.is_match(format!("{}/proj", base.join("real").display())),
"premise: the un-canonicalized spelling must not match"
);
}
#[test]
fn a_spliced_canonical_spelling_matches_the_directory_it_names() {
let d = tempfile::tempdir().unwrap();
let base = PathBuf::from(glob_spelling(&fs::canonicalize(d.path()).unwrap()));
let real = base.join("real[abc]");
fs::create_dir_all(&real).unwrap();
for sibling in ["reala", "realb"] {
fs::create_dir_all(base.join(sibling)).unwrap();
}
let spelling = glob_spelling(&real);
assert!(
!spelling.contains('\\'),
"the spliced spelling must be /-spelled on every platform: {spelling}"
);
assert_eq!(
spelling,
format!("{}/real[abc]", glob_spelling(&base)),
"a canonical path spells its own brackets, which is what has to be escaped"
);
let spliced = escape_glob_literal(&spelling)
.expect("a bracketed name is escapable; only `{{` and `}}` are not");
assert_eq!(spliced, format!("{}/real[[]abc[]]", glob_spelling(&base)));
let matcher = globset::Glob::new(&format!("{spliced}/*"))
.unwrap()
.compile_matcher();
assert!(
matcher.is_match(format!("{}/proj", glob_spelling(&real))),
"the named tree must match the spliced spelling {spliced}"
);
for sibling in ["reala", "realb"] {
assert!(
!matcher.is_match(format!("{}/{sibling}/proj", glob_spelling(&base))),
"{sibling} must not match the spliced spelling {spliced}"
);
}
let unescaped = format!("{}/real[abc]/*", glob_spelling(&base));
let unescaped = globset::Glob::new(&unescaped).unwrap().compile_matcher();
assert!(
!unescaped.is_match(format!("{}/proj", glob_spelling(&real))),
"premise: the unescaped reading must NOT match the directory it names"
);
assert!(
unescaped.is_match(format!("{}/reala/proj", glob_spelling(&base))),
"premise: the unescaped reading must match a sibling, which is the defect"
);
let windows_spliced =
escape_glob_literal(&glob_spelling_with(r"C:\Users\runneradmin\real[abc]", '\\'))
.unwrap();
assert_eq!(
windows_spliced, "C:/Users/runneradmin/real[[]abc[]]",
"a Windows canonical spelling is `/`-spelled and its brackets escaped"
);
let windows = globset::Glob::new(&format!("{windows_spliced}/*"))
.unwrap()
.compile_matcher();
assert!(
windows.is_match("C:/Users/runneradmin/real[abc]/proj"),
"the spliced Windows spelling must match the tree it names"
);
assert!(
!windows.is_match("C:/Users/runneradmin/reala/proj"),
"the spliced Windows spelling must not match a sibling"
);
for (verbatim, expected) in [
(
r"\\?\C:\Users\runneradmin\real[abc]",
"C:/Users/runneradmin/real[abc]",
),
(
r"\\?\UNC\server\share\real[abc]",
"//server/share/real[abc]",
),
] {
let spelling = glob_spelling_with(verbatim, '\\');
assert_eq!(
spelling, expected,
"a verbatim prefix is a Win32 artefact, not part of the path"
);
let spliced = escape_glob_literal(&spelling).unwrap();
let matcher = globset::Glob::new(&format!("{spliced}/*"))
.unwrap()
.compile_matcher();
assert!(
matcher.is_match(format!("{expected}/proj")),
"the de-verbatim spelling must still match the tree it names: {spliced}"
);
}
assert!(
!dangling_trailing_escape(r"C:\Users\runneradmin\proj\", false),
"a trailing separator is not a dangling escape where `\\` is a separator"
);
assert!(
dangling_trailing_escape("/home/you/proj\\", true),
"a trailing `\\` is a dangling escape where it escapes"
);
assert!(!dangling_trailing_escape("/home/you/proj/", true));
}
#[cfg(unix)]
#[test]
fn a_backslash_in_a_canonical_directory_name_is_spliced_as_a_escape() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let base = fs::canonicalize(d.path()).unwrap();
let real = base.join("back\\slash");
fs::create_dir_all(&real).unwrap();
let link = base.join("bslink");
symlink(&real, &link).unwrap();
let written = format!("{}/*", link.display());
let rewritten = canonical_pattern_prefix(&written, PatternKind::Glob);
assert_eq!(
rewritten,
format!("{}/back\\\\slash/*", base.display()),
"a literal backslash in the canonical name is spliced as an escaped backslash"
);
let matcher = globset::Glob::new(&rewritten).unwrap().compile_matcher();
assert!(
matcher.is_match(format!("{}/proj", real.display())),
"the named tree must match {rewritten}"
);
assert!(
!matcher.is_match(format!("{}/backslash/proj", base.display())),
"an unescaped reading would have matched `backslash`: {rewritten}"
);
}
#[cfg(windows)]
#[test]
fn a_bracketed_canonical_spelling_is_matched_literally_on_windows() {
let d = tempfile::tempdir().unwrap();
let base = PathBuf::from(glob_spelling(&fs::canonicalize(d.path()).unwrap()));
assert!(
!base.display().to_string().contains('?'),
"premise: the fixture root must be spelled the way a user spells it"
);
let real = base.join("real[abc]");
fs::create_dir_all(&real).unwrap();
for sibling in ["reala", "realb"] {
fs::create_dir_all(base.join(sibling)).unwrap();
}
let link = base.join("link");
let link_arg = link.display().to_string().replace('/', "\\");
let real_arg = real.display().to_string().replace('/', "\\");
let made = std::process::Command::new("cmd")
.args(["/c", "mklink", "/J"])
.arg(&link_arg)
.arg(&real_arg)
.output()
.unwrap();
assert!(
made.status.success(),
"fixture-scope: a directory junction is the Windows alias a canonical \
rewrite needs, and it needs no elevation: {}",
String::from_utf8_lossy(&made.stderr)
);
assert_ne!(
link.display().to_string(),
real.display().to_string(),
"premise: the fixture needs a spelling that is not the canonical one"
);
let written = format!("{link_arg}\\*");
let config = base.join("config.toml");
fs::write(
&config,
format!("[cleanup.policy]\nexclude = [{}]\n", toml_string(&written)),
)
.unwrap();
let exclude = load(&config).unwrap().cleanup.policy.exclude;
assert_eq!(exclude.len(), 1);
assert_eq!(
exclude[0],
format!("{}/real[[]abc[]]\\*", glob_spelling(&base)),
"the rewritten pattern is the canonical name, escaped, with the \
user's own separators and tail untouched"
);
let matcher = globset::Glob::new(&exclude[0]).unwrap().compile_matcher();
assert!(
matcher.is_match(format!("{}/proj", glob_spelling(&real))),
"the named tree must match the spliced spelling {}",
exclude[0]
);
for sibling in ["reala", "realb"] {
assert!(
!matcher.is_match(format!("{}/{sibling}/proj", glob_spelling(&base))),
"{sibling} must not match the spliced spelling {}",
exclude[0]
);
}
let unescaped = format!("{}/real[abc]/*", glob_spelling(&base));
let unescaped = globset::Glob::new(&unescaped).unwrap().compile_matcher();
assert!(!unescaped.is_match(format!("{}/proj", glob_spelling(&real))));
assert!(unescaped.is_match(format!("{}/reala/proj", glob_spelling(&base))));
}
#[test]
fn windows_drive_roots_are_recognised_as_absolute_prefixes() {
assert!(is_windows_drive_root("C:"));
assert!(is_windows_drive_root("d:"));
assert!(!is_windows_drive_root("C:\\proj"));
assert!(!is_windows_drive_root("CC:"));
assert!(!is_windows_drive_root("C"));
assert!(!is_windows_drive_root(""));
assert!(!is_windows_drive_root("/tmp"));
assert_eq!(
canonical_pattern_prefix("C:\\*", PatternKind::Glob),
"C:\\*"
);
}
#[test]
fn recency_seconds_of_zero_is_rejected() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.toml");
fs::write(&p, "[scan]\nrecency_seconds = 0\n").unwrap();
let err = load(&p).unwrap_err().to_string();
assert!(err.contains("recency_seconds"), "{err}");
assert!(err.contains("inactivity guard"), "{err}");
fs::write(&p, "[scan]\nrecency_seconds = 1\n").unwrap();
assert_eq!(load(&p).unwrap().scan.recency_seconds, 1);
}
#[test]
fn out_of_range_retention_reports_a_range_not_a_parse_error() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.toml");
fs::write(&p, "[scan]\nlearned_root_retention_days = 99999\n").unwrap();
let err = load(&p).unwrap_err().to_string();
assert!(
err.contains("learned_root_retention_days must be between 0 and 3650"),
"{err}"
);
fs::write(&p, "[scan]\nlearned_root_retention_days = 7\n").unwrap();
assert_eq!(load(&p).unwrap().scan.learned_root_retention_days, 7);
}
#[test]
fn invalid_scan_ignore_glob_is_reported_at_load() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.toml");
let absolute_invalid = d.path().join("[unclosed");
let pattern = absolute_invalid.to_string_lossy().replace('\\', "/");
fs::write(&p, format!("[scan]\nignore = [\"{pattern}\"]\n")).unwrap();
let err = load(&p).unwrap_err().to_string();
assert!(err.contains("invalid scan.ignore glob"), "{err}");
}
#[test]
fn default_recency_and_absent_config() {
let d = tempfile::tempdir().unwrap();
let c = load(&d.path().join("missing.toml")).unwrap();
assert_eq!(c.scan.recency_seconds, 300);
}
#[test]
fn malformed_and_relative_paths_fail() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("bad.toml");
fs::write(&p, "[scan]\nrecency_seconds = nope\n").unwrap();
assert!(load(&p).is_err());
fs::write(&p, "[scan]\nroot = \"relative\"\n").unwrap();
assert!(load(&p).is_err());
fs::write(
&p,
"[cleanup]\nallowed_output_roots = [\"relative/root\"]\n",
)
.unwrap();
assert!(load(&p).is_err());
}
#[test]
fn checked_in_template_parses_and_matches_defaults() {
let config: Config =
toml::from_str(CONFIG_TEMPLATE).expect("checked-in template must parse");
assert_eq!(config.scan.recency_seconds, 300);
assert!(config.scan.root.is_none());
assert!(config.scan.ignore.is_empty());
assert!(config.scan.unignore.is_empty());
assert!(config.cleanup.allowed_output_roots.is_empty());
let defaults = Config::default();
assert_eq!(config.scan.recency_seconds, defaults.scan.recency_seconds);
assert_eq!(config.scan.root, defaults.scan.root);
assert_eq!(config.scan.ignore, defaults.scan.ignore);
assert_eq!(config.scan.unignore, defaults.scan.unignore);
assert_eq!(
config.cleanup.allowed_output_roots,
defaults.cleanup.allowed_output_roots
);
}
#[test]
fn config_template_matches_repository_file() {
let on_disk = fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/config.toml"))
.expect("repository config.toml must exist");
assert_eq!(
CONFIG_TEMPLATE, on_disk,
"bootstrap source must equal the checked-in template"
);
}
#[test]
fn legacy_cleanup_config_loads_with_neutral_policy() {
let config: Config = toml::from_str("[cleanup]\nallowed_output_roots = []\n").unwrap();
assert_eq!(config.cleanup.policy.min_reclaimable_bytes, 0);
assert_eq!(config.cleanup.policy.min_inactive_seconds, None);
assert!(config.cleanup.policy.include.is_empty());
assert!(config.cleanup.policy.exclude.is_empty());
}
#[test]
fn cleanup_policy_globs_and_durations_are_validated() {
let d = tempfile::tempdir().unwrap();
let path = d.path().join("config.toml");
fs::write(&path, "[cleanup.policy]\ninclude = [\"[\"]\n").unwrap();
assert!(load(&path).is_err());
fs::write(
&path,
"[cleanup.policy]\nmin_inactive_seconds = 18446744073709551615\n",
)
.unwrap();
assert!(load(&path).is_err());
}
#[test]
fn operational_bootstrap_refuses_overwrite() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.toml");
let initial = load_or_create(&p).unwrap();
assert_eq!(initial.scan.recency_seconds, 300);
fs::write(&p, "[scan]\nrecency_seconds = 61\n").unwrap();
assert_eq!(load_or_create(&p).unwrap().scan.recency_seconds, 61);
}
#[test]
fn bootstrap_bytes_equal_checked_in_template() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.toml");
load_or_create(&p).unwrap();
let written = fs::read_to_string(&p).unwrap();
assert_eq!(written, CONFIG_TEMPLATE);
let loaded = load(&p).unwrap();
assert_eq!(loaded.scan.recency_seconds, 300);
}
#[test]
fn malformed_config_is_not_replaced_automatically() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.toml");
fs::write(&p, "[scan]\nrecency_seconds = nope\n").unwrap();
assert!(load(&p).is_err());
assert!(load_or_create(&p).is_err());
assert_eq!(
fs::read_to_string(&p).unwrap(),
"[scan]\nrecency_seconds = nope\n"
);
}
#[test]
fn concurrent_first_use_creates_one_complete_template() {
const WORKERS: usize = 16;
const ROUNDS: usize = 24;
let d = tempfile::tempdir().unwrap();
for round in 0..ROUNDS {
let p = d.path().join(format!("round{round}/config.toml"));
let workers: Vec<_> = (0..WORKERS)
.map(|_| {
let path = p.clone();
std::thread::spawn(move || load_or_create(&path).unwrap())
})
.collect();
for worker in workers {
assert_eq!(
worker.join().unwrap().scan.recency_seconds,
300,
"round {round}: every racer must succeed"
);
}
assert_eq!(
fs::read(&p).unwrap(),
CONFIG_TEMPLATE.as_bytes(),
"round {round}: one complete template, never a partial one"
);
}
}
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod hard_link_trap {
#[repr(C)]
struct SockFilter {
code: u16,
jt: u8,
jf: u8,
k: u32,
}
#[repr(C)]
struct SockFprog {
len: u16,
filter: *const SockFilter,
}
const LD_W_ABS: u16 = 0x20;
const JEQ_K: u16 = 0x15;
const RET_K: u16 = 0x06;
const AUDIT_ARCH_X86_64: u32 = 0xc000_003e;
const RET_ALLOW: u32 = 0x7fff_0000;
const RET_ERRNO: u32 = 0x0005_0000;
const ENOSYS: u32 = 38;
const SYS_LINK: u32 = 86;
const SYS_LINKAT: u32 = 265;
const PR_SET_NO_NEW_PRIVS: i32 = 38;
const PR_SET_SECCOMP: i32 = 22;
const SECCOMP_MODE_FILTER: i32 = 2;
unsafe extern "C" {
fn prctl(option: i32, ...) -> i32;
}
pub fn install() {
let program = [
SockFilter {
code: LD_W_ABS,
jt: 0,
jf: 0,
k: 4,
},
SockFilter {
code: JEQ_K,
jt: 1,
jf: 0,
k: AUDIT_ARCH_X86_64,
},
SockFilter {
code: RET_K,
jt: 0,
jf: 0,
k: RET_ALLOW,
},
SockFilter {
code: LD_W_ABS,
jt: 0,
jf: 0,
k: 0,
},
SockFilter {
code: JEQ_K,
jt: 2,
jf: 0,
k: SYS_LINKAT,
},
SockFilter {
code: JEQ_K,
jt: 1,
jf: 0,
k: SYS_LINK,
},
SockFilter {
code: RET_K,
jt: 0,
jf: 0,
k: RET_ALLOW,
},
SockFilter {
code: RET_K,
jt: 0,
jf: 0,
k: RET_ERRNO | ENOSYS,
},
];
let prog = SockFprog {
len: program.len() as u16,
filter: program.as_ptr(),
};
unsafe {
assert_eq!(
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0),
0,
"could not set NO_NEW_PRIVS: errno {}",
std::io::Error::last_os_error()
);
assert_eq!(
prctl(
PR_SET_SECCOMP,
SECCOMP_MODE_FILTER,
&prog as *const SockFprog
),
0,
"could not install the link trap: errno {}",
std::io::Error::last_os_error()
);
}
}
}
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[test]
fn the_config_is_published_on_a_filesystem_without_hard_links() {
let d = tempfile::tempdir().unwrap();
let fresh = d.path().join("fresh/config.toml");
let raced = d.path().join("raced/config.toml");
let winner = b"# a concurrent winner\nrecency_seconds = 300\n";
fs::create_dir_all(raced.parent().unwrap()).unwrap();
fs::write(&raced, winner).unwrap();
let probe_src = d.path().join("probe");
let probe_dst = d.path().join("probe.link");
fs::write(&probe_src, b"probe").unwrap();
let (published, raced_result) = std::thread::spawn({
let probe_src = probe_src.clone();
let probe_dst = probe_dst.clone();
let raced = raced.clone();
let fresh = fresh.clone();
move || {
hard_link_trap::install();
let trapped = std::fs::hard_link(&probe_src, &probe_dst).unwrap_err();
assert_eq!(
trapped.kind(),
std::io::ErrorKind::Unsupported,
"premise: link(2) must report the capability as unsupported, got {trapped}"
);
(create_initial(&fresh), create_initial(&raced))
}
})
.join()
.expect("the trapped thread panicked");
published.unwrap_or_else(|e| panic!("publication must survive the fallback: {e}"));
assert_eq!(
fs::read(&fresh).unwrap(),
CONFIG_TEMPLATE.as_bytes(),
"the fallback must write the whole template, not a prefix of it"
);
raced_result.unwrap_or_else(|e| panic!("a lost race is success, not failure: {e}"));
assert_eq!(
fs::read(&raced).unwrap(),
winner,
"the fallback must not overwrite a config another process published"
);
let _ = fs::remove_file(&probe_src);
}
}