beffroi-tools/crates/ascii-names/tests/cleanup.rs

371 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use ascii_names::{Options, ascii_name, clean};
use std::{
fs,
sync::atomic::AtomicBool,
time::{Duration, Instant},
};
fn options() -> Options {
Options {
delay: Duration::ZERO,
dry_run: false,
}
}
// Older FreeBSD jails have no atomic no-replace API. Exercise their documented
// refusal rather than expecting successful renames or accepting other OS errors.
fn rename_test_dir() -> Option<tempfile::TempDir> {
let tmp = tempfile::tempdir().unwrap();
#[cfg(target_os = "freebsd")]
{
// SAFETY: a static C string and the default loaded-library search handle.
let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"renameat2".as_ptr()) };
if symbol.is_null() {
let file = tmp.path().join("été.txt");
let directory = tmp.path().join("été");
fs::write(&file, "unchanged").unwrap();
fs::create_dir(&directory).unwrap();
let mut messages = Vec::new();
let summary = clean(
tmp.path(),
options(),
&AtomicBool::new(false),
|_, message| messages.push(message),
)
.unwrap();
assert_eq!(summary.errors, 2, "{messages:?}");
assert_eq!(summary.renamed, 0);
assert_eq!(fs::read_to_string(file).unwrap(), "unchanged");
assert!(directory.is_dir());
assert!(!tmp.path().join("ete.txt").exists());
assert!(!tmp.path().join("ete").exists());
assert!(
messages
.iter()
.all(|m| m.contains("renameat2 is missing from the jail's libc")),
"{messages:?}"
);
let output = std::process::Command::new(env!("CARGO_BIN_EXE_ascii-names"))
.arg(tmp.path())
.args(["--delay-ms", "0"])
.output()
.unwrap();
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stdout)
.contains("renameat2 is missing from the jail's libc")
);
assert_eq!(
fs::read_to_string(tmp.path().join("été.txt")).unwrap(),
"unchanged"
);
assert!(tmp.path().join("été").is_dir());
// Direct stderr keeps this platform limitation visible in successful CI output.
use std::io::Write;
let _ = writeln!(
std::io::stderr(),
"FreeBSD libc lacks renameat2: verified safe refusal; successful-rename assertions require a supported host."
);
return None;
}
}
Some(tmp)
}
#[test]
fn accents_punctuation_unknowns_and_portable_names() {
for (input, expected) in [
("Été à Noël.mov", "Ete a Noel.mov"),
("Cafe\u{301}.txt", "Cafe.txt"),
(
"œuf Straße Łódź Æsir Øresund",
"oeuf Strasse Lodz AEsir Oresund",
),
("‘Hello’—world…", "'Hello'-world"),
("日本🎬.txt", "___.txt"),
("a\nb:<>\"\\|?*c", "a_b________c"),
("\u{301}", "_"),
("..", "_"),
("foo. ", "foo"),
("CON.txt", "_CON.txt"),
("LPT9", "_LPT9"),
("COM0", "COM0"),
("ordinary file-01.txt", "ordinary file-01.txt"),
] {
assert_eq!(ascii_name(input), expected, "{input:?}");
}
let name = ascii_name(&format!("{}.txt", "ffi".repeat(100)));
assert_eq!(name.len(), 220);
assert!(name.ends_with(".txt"));
assert!(name.is_ascii());
}
#[test]
fn nested_cleanup_preserves_all_contents_and_is_idempotent() {
let Some(tmp) = rename_test_dir() else {
return;
};
let root = tmp.path().join("Sélection");
fs::create_dir_all(root.join("Étage/été")).unwrap();
fs::write(root.join("Étage/été/vidéo.mov"), b"video bytes").unwrap();
fs::write(root.join("resume.txt"), b"original").unwrap();
fs::write(root.join("résumé.txt"), b"accented").unwrap();
fs::write(root.join("résume.txt"), b"another").unwrap();
let cancel = AtomicBool::new(false);
let summary = clean(&root, options(), &cancel, |_, message| {
eprintln!("{message}")
})
.unwrap();
assert_eq!(summary.errors, 0);
assert_eq!(summary.renamed, 5);
assert_eq!(
fs::read(root.join("Etage/ete/video.mov")).unwrap(),
b"video bytes"
);
assert_eq!(fs::read(root.join("resume.txt")).unwrap(), b"original");
let mut contents = [
fs::read(root.join("resume_1.txt")).unwrap(),
fs::read(root.join("resume_2.txt")).unwrap(),
];
contents.sort();
assert_eq!(contents, [b"accented".to_vec(), b"another".to_vec()]);
assert_eq!(
clean(&root, options(), &cancel, |_, message| eprintln!(
"{message}"
))
.unwrap()
.renamed,
0
);
}
#[test]
fn preview_reserves_targets_and_changes_nothing() {
let tmp = tempfile::tempdir().unwrap();
fs::write(tmp.path().join("é.txt"), "a").unwrap();
fs::write(tmp.path().join("è.txt"), "b").unwrap();
let mut logs = vec![];
let summary = clean(
tmp.path(),
Options {
dry_run: true,
..options()
},
&AtomicBool::new(false),
|_, msg| logs.push(msg),
)
.unwrap();
assert_eq!(summary.renamed, 2);
assert!(logs[0].ends_with("e.txt"));
assert!(logs[1].ends_with("e_1.txt"));
assert!(tmp.path().join("é.txt").exists());
assert!(tmp.path().join("è.txt").exists());
assert!(!tmp.path().join("e.txt").exists());
}
#[test]
fn directory_and_file_collisions_never_merge() {
let Some(tmp) = rename_test_dir() else {
return;
};
fs::create_dir(tmp.path().join("Ete")).unwrap();
fs::create_dir(tmp.path().join("Été")).unwrap();
fs::write(tmp.path().join("Ete/original"), "keep").unwrap();
fs::write(tmp.path().join("Été/new"), "new").unwrap();
fs::write(tmp.path().join("été"), "file").unwrap();
let result = clean(
tmp.path(),
options(),
&AtomicBool::new(false),
|_, message| eprintln!("{message}"),
)
.unwrap();
assert_eq!(result.errors, 0);
assert_eq!(
fs::read_to_string(tmp.path().join("Ete/original")).unwrap(),
"keep"
);
assert!(tmp.path().join("Ete_1/new").is_file());
}
#[test]
fn cancellation_stops_between_renames_and_delay_is_applied() {
let Some(tmp) = rename_test_dir() else {
return;
};
fs::write(tmp.path().join("é"), "a").unwrap();
fs::write(tmp.path().join("à"), "b").unwrap();
let cancel = AtomicBool::new(false);
let start = Instant::now();
let result = clean(
tmp.path(),
Options {
delay: Duration::from_millis(30),
dry_run: false,
},
&cancel,
|_, message| {
eprintln!("{message}");
cancel.store(true, std::sync::atomic::Ordering::Relaxed);
},
)
.unwrap();
assert!(result.cancelled);
assert_eq!(result.renamed, 1);
assert!(start.elapsed() >= Duration::from_millis(30));
assert!(
clean(tmp.path(), options(), &cancel, |_, message| eprintln!(
"{message}"
))
.unwrap()
.cancelled
);
}
#[test]
fn missing_root_and_file_root_are_errors() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("file");
let cancel = AtomicBool::new(false);
assert!(
clean(&file, options(), &cancel, |_, message| eprintln!(
"{message}"
))
.is_err()
);
fs::write(&file, "x").unwrap();
assert!(
clean(&file, options(), &cancel, |_, message| eprintln!(
"{message}"
))
.is_err()
);
}
#[cfg(unix)]
#[test]
fn links_are_not_followed_and_invalid_utf8_is_cleaned() {
use std::{
ffi::OsString,
os::unix::{ffi::OsStringExt, fs::symlink},
};
let Some(tmp) = rename_test_dir() else {
return;
};
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("é.txt"), "outside").unwrap();
symlink(outside.path(), tmp.path().join("lïnk")).unwrap();
symlink("missing", tmp.path().join("e.txt")).unwrap();
fs::write(tmp.path().join("é.txt"), "inside").unwrap();
fs::write(
tmp.path().join(OsString::from_vec(b"bad\xff.txt".to_vec())),
"bytes",
)
.unwrap();
let result = clean(
tmp.path(),
options(),
&AtomicBool::new(false),
|_, message| eprintln!("{message}"),
)
.unwrap();
assert_eq!(result.skipped, 2);
assert_eq!(result.errors, 0);
assert!(outside.path().join("é.txt").exists());
assert_eq!(
fs::read_to_string(tmp.path().join("bad_.txt")).unwrap(),
"bytes"
);
assert_eq!(
fs::read_to_string(tmp.path().join("e_1.txt")).unwrap(),
"inside"
);
assert!(
clean(
&tmp.path().join("lïnk"),
options(),
&AtomicBool::new(false),
|_, message| eprintln!("{message}")
)
.is_err()
);
}
#[test]
fn cli_preview_and_apply() {
let Some(tmp) = rename_test_dir() else {
return;
};
fs::write(tmp.path().join("été.txt"), "content").unwrap();
let bin = env!("CARGO_BIN_EXE_ascii-names");
let output = std::process::Command::new(bin)
.arg(tmp.path())
.arg("--dry-run")
.output()
.unwrap();
assert!(
output.status.success(),
"status: {}; stdout: {}; stderr: {}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(tmp.path().join("été.txt").exists());
let output = std::process::Command::new(bin)
.arg(tmp.path())
.args(["--delay-ms", "0"])
.output()
.unwrap();
assert!(
output.status.success(),
"status: {}; stdout: {}; stderr: {}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
fs::read_to_string(tmp.path().join("ete.txt")).unwrap(),
"content"
);
assert!(
!std::process::Command::new(bin)
.arg(tmp.path().join("missing"))
.output()
.unwrap()
.status
.success()
);
}
#[test]
fn many_names_with_same_fallback_keep_every_file() {
let Some(tmp) = rename_test_dir() else {
return;
};
for (index, character) in (0x4e00..0x4e80).filter_map(char::from_u32).enumerate() {
fs::write(
tmp.path().join(format!("{character}.txt")),
index.to_string(),
)
.unwrap();
}
let summary = clean(
tmp.path(),
options(),
&AtomicBool::new(false),
|_, message| eprintln!("{message}"),
)
.unwrap();
assert_eq!(summary.renamed, 128);
assert_eq!(summary.errors, 0);
let values: std::collections::HashSet<_> = fs::read_dir(tmp.path())
.unwrap()
.map(|entry| {
let path = entry.unwrap().path();
assert!(path.file_name().unwrap().to_str().unwrap().is_ascii());
fs::read_to_string(path).unwrap()
})
.collect();
assert_eq!(values.len(), 128);
}