use std::path::{Component, Path};
use unicode_normalization::{UnicodeNormalization, is_nfc};
const MAX_PATH: usize = 4_096;
#[must_use]
pub fn is_safe_tree_path(path: &str) -> bool {
!path.is_empty() && path.len() <= MAX_PATH && is_nfc(path) && path.split('/').all(is_safe_name)
}
pub(crate) fn is_safe_name(name: &str) -> bool {
!name.is_empty()
&& name != "."
&& name != ".."
&& !name.contains(['/', '\\', '\0'])
&& !is_reserved(name)
}
pub(crate) fn is_reserved(name: &str) -> bool {
let before_stream = name.split(':').next().unwrap_or_default();
let seen: String = before_stream
.chars()
.filter(|character| !is_ignored_by_macos(*character))
.collect();
let seen = seen.trim_end_matches(['.', ' ']).to_uppercase();
if seen == ".GIT" || seen == ".NIB" {
return true;
}
["GIT~", "NIB~"].iter().any(|start| {
seen.strip_prefix(start)
.is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|byte| byte.is_ascii_digit()))
})
}
fn is_ignored_by_macos(character: char) -> bool {
matches!(
character,
'\u{200c}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{206a}'..='\u{206f}' | '\u{feff}'
)
}
pub(crate) fn fits_this_system(name: &str) -> bool {
if cfg!(windows) {
let device = name
.split('.')
.next()
.unwrap_or_default()
.trim_end()
.to_ascii_uppercase();
let numbered = |start: &str| {
device.strip_prefix(start).is_some_and(|rest| {
matches!(
rest,
"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
)
})
};
!name.contains(['<', '>', ':', '"', '|', '?', '*'])
&& !name.chars().any(char::is_control)
&& !name.ends_with(['.', ' '])
&& !matches!(
device.as_str(),
"CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
)
&& !numbered("COM")
&& !numbered("LPT")
} else {
true
}
}
pub(crate) fn tree_path_of(relative: &Path) -> Result<String, &'static str> {
let mut names = Vec::new();
for component in relative.components() {
let Component::Normal(name) = component else {
return Err("it is not in the tree's folder");
};
let name = name.to_str().ok_or("its name is not Unicode")?;
names.push(name.nfc().collect::<String>());
}
let path = names.join("/");
if path.is_empty() {
return Err("it is the tree's folder");
}
if path.split('/').any(|name| name.contains('\\')) {
return Err("its name holds a backslash, which Windows reads as between folders");
}
if !is_safe_tree_path(&path) {
return Err("its path cannot be in a tree");
}
Ok(path)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_of_git_and_the_library_are_reserved_however_spelled() {
for reserved in [
".git",
".GIT",
".gIt",
".git.",
".git...",
".git ",
".git. .",
".git:stream",
".git::$INDEX_ALLOCATION",
"\u{200c}.git",
".g\u{200d}it",
".git\u{feff}",
"git~1",
"GIT~12",
".g\u{131}t",
".nib",
".NIB",
"nib~1",
] {
assert!(is_reserved(reserved), "{reserved:?}");
}
for allowed in [
".gitignore",
".github",
".gitmodules",
"git",
".git-crypt",
"git~",
"git~a",
".nibignore",
"nib",
"a.git",
] {
assert!(!is_reserved(allowed), "{allowed:?}");
}
}
#[test]
fn a_path_on_disk_becomes_a_tree_path_in_composed_form() {
assert_eq!(
tree_path_of(Path::new("docs/cafe\u{301}.md")),
Ok("docs/caf\u{e9}.md".to_owned())
);
assert!(tree_path_of(Path::new("../a")).is_err());
assert!(tree_path_of(Path::new("")).is_err());
assert!(tree_path_of(Path::new("x/.git/config")).is_err());
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
let not_unicode = std::ffi::OsStr::from_bytes(b"a\xff.txt");
assert_eq!(
tree_path_of(Path::new(not_unicode)),
Err("its name is not Unicode")
);
assert!(tree_path_of(Path::new("a\\b.txt")).is_err());
}
}
#[test]
fn windows_takes_only_names_it_can_write() {
let names = [
"CON", "nul.txt", "com1", "LPT9.log", "a:b", "a?", "end.", "end ",
];
for name in names {
assert_eq!(fits_this_system(name), !cfg!(windows), "{name}");
}
for name in ["CONSOLE", "com0", "notes.md", "lpt"] {
assert!(fits_this_system(name), "{name}");
}
}
}