use std::io;
use std::path::Path;
fn missing_directory(path: &Path) -> Option<&'static str> {
match std::fs::metadata(path) {
Ok(meta) if meta.is_dir() => None,
Ok(_) => Some("exists but is not a directory"),
Err(err) if err.kind() == io::ErrorKind::NotFound => Some("does not exist yet"),
Err(_) => None,
}
}
#[must_use]
pub(crate) fn cwd_advisory(cwd: &Path) -> Option<String> {
#[cfg(windows)]
{
if let Some(reason) = windows_name_advisory(cwd) {
return Some(format!("{} {reason}", cwd.display()));
}
}
let reason = missing_directory(cwd)?;
Some(format!("{} {reason}", cwd.display()))
}
#[must_use]
pub(crate) fn log_path_advisory(path: &Path) -> Option<String> {
#[cfg(windows)]
{
if let Some(reason) = windows_name_advisory(path) {
return Some(format!("{} {reason}", path.display()));
}
}
if matches!(std::fs::metadata(path), Ok(meta) if meta.is_dir()) {
return Some(format!("{} is a directory, not a log file", path.display()));
}
let parent = path.parent().filter(|p| !p.as_os_str().is_empty())?;
let reason = missing_directory(parent)?;
Some(format!("{} {reason}", parent.display()))
}
#[cfg(windows)]
#[must_use]
fn windows_name_advisory(path: &Path) -> Option<String> {
use std::os::windows::ffi::OsStrExt as _;
const ILLEGAL: &[char] = &['<', '>', ':', '"', '|', '?', '*'];
const RESERVED: &[&str] = &[
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
"COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];
const MAX_PATH: usize = 260;
let length = path.as_os_str().encode_wide().count();
if length >= MAX_PATH {
return Some(format!(
"is {length} characters, at or over Windows' {MAX_PATH}-character default limit"
));
}
for component in path.components() {
let std::path::Component::Normal(part) = component else {
continue;
};
let Some(name) = part.to_str() else {
continue;
};
if let Some(bad) = name.chars().find(|c| ILLEGAL.contains(c)) {
return Some(format!("contains `{bad}`, which Windows refuses in a path"));
}
if let Some(control) = name.chars().find(|&c| (c as u32) < 0x20) {
return Some(format!(
"contains U+{:04X}, a control character Windows refuses in a path",
control as u32
));
}
let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem);
if RESERVED
.iter()
.any(|reserved| reserved.eq_ignore_ascii_case(stem))
{
return Some(format!("names `{name}`, a reserved Windows device name"));
}
}
None
}
#[cfg(test)]
mod path_advisory_tests {
use super::*;
#[test]
fn a_cwd_that_exists_gets_no_warning() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(cwd_advisory(dir.path()), None);
}
#[test]
fn a_cwd_that_does_not_exist_yet_is_named() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("not-created-yet");
let warning = cwd_advisory(&missing).expect("a missing cwd warns");
assert!(warning.contains("does not exist"), "{warning}");
assert!(
warning.contains(&missing.display().to_string()),
"names the path: {warning}"
);
}
#[test]
fn a_cwd_that_is_a_file_is_named() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("not-a-dir");
std::fs::write(&file, b"").unwrap();
let warning = cwd_advisory(&file).expect("a file where a directory is meant warns");
assert!(warning.contains("is not a directory"), "{warning}");
}
#[test]
fn a_log_path_whose_parent_exists_gets_no_warning() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("web-out.log");
assert_eq!(
log_path_advisory(&log),
None,
"the file itself need not exist yet; `open_log_path` creates it"
);
}
#[test]
fn a_log_path_whose_parent_does_not_exist_yet_is_named() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("not-created-yet").join("web-out.log");
let warning = log_path_advisory(&log).expect("a missing parent warns");
assert!(warning.contains("does not exist"), "{warning}");
}
#[test]
fn a_log_path_whose_parent_is_a_file_is_named() {
let dir = tempfile::tempdir().unwrap();
let parent = dir.path().join("not-a-directory");
std::fs::write(&parent, b"").unwrap();
let warning =
log_path_advisory(&parent.join("web-out.log")).expect("a parent that is a file warns");
assert!(
warning.contains("exists but is not a directory"),
"{warning}"
);
}
#[test]
fn a_log_path_that_is_already_a_directory_is_named() {
let dir = tempfile::tempdir().unwrap();
let warning =
log_path_advisory(dir.path()).expect("a directory where a file is meant warns");
assert!(
warning.contains("is a directory, not a log file"),
"{warning}"
);
}
}
#[cfg(all(test, windows))]
mod windows_advisory_tests {
use super::*;
#[test]
fn a_reserved_device_name_is_named_regardless_of_extension() {
let warning = windows_name_advisory(Path::new(r"C:\logs\CON.log"))
.expect("CON is reserved regardless of extension");
assert!(
warning.contains("reserved Windows device name"),
"{warning}"
);
}
#[test]
fn a_second_dot_takes_a_name_back_out_of_the_reserved_set() {
assert_eq!(
windows_name_advisory(Path::new(r"C:\logs\CON.my.txt")),
None,
"CON.my is not a device name"
);
assert_eq!(
windows_name_advisory(Path::new(r"C:\logs\NUL.my.log")),
None,
"NUL.my is not a device name"
);
assert!(
windows_name_advisory(Path::new(r"C:\logs\CON.txt")).is_some(),
"one dot still leaves CON reserved"
);
}
#[test]
fn the_path_limit_counts_utf16_units_not_bytes() {
let under = format!(r"C:\logs\{}.log", "\u{1f411}".repeat(120));
assert_eq!(
windows_name_advisory(Path::new(&under)),
None,
"252 units is under the limit, though the same path is 492 bytes"
);
let over = format!(r"C:\logs\{}.log", "\u{1f411}".repeat(130));
let warning = windows_name_advisory(Path::new(&over)).expect("260 units is at the limit");
assert!(warning.contains("260-character"), "{warning}");
}
#[test]
fn a_control_character_is_named_by_code_point_and_c1_is_not() {
let warning = windows_name_advisory(Path::new("C:\\logs\\web\tout.log"))
.expect("a tab is refused anywhere in a Windows path");
assert!(warning.contains("U+0009"), "{warning}");
assert!(!warning.contains('\t'), "{warning}");
assert_eq!(
windows_name_advisory(Path::new("C:\\logs\\web\u{85}out.log")),
None,
"U+0085 is a C1 control that Windows accepts in a file name"
);
}
#[test]
fn an_ordinary_path_gets_no_warning() {
assert_eq!(
windows_name_advisory(Path::new(r"C:\logs\web-out.log")),
None
);
}
#[test]
fn an_illegal_character_is_named() {
let warning = windows_name_advisory(Path::new(r"C:\logs\web?out.log"))
.expect("`?` is refused anywhere in a Windows path");
assert!(warning.contains('?'), "{warning}");
}
#[test]
fn an_over_length_path_is_named() {
let long = format!(r"C:\{}", "a".repeat(300));
let warning =
windows_name_advisory(Path::new(&long)).expect("300 characters is over MAX_PATH");
assert!(warning.contains("260-character"), "{warning}");
}
}