nibkeep_node/library/trees/
paths.rs1use std::path::{Component, Path};
10
11use unicode_normalization::{UnicodeNormalization, is_nfc};
12
13const MAX_PATH: usize = 4_096;
15
16#[must_use]
22pub fn is_safe_tree_path(path: &str) -> bool {
23 !path.is_empty() && path.len() <= MAX_PATH && is_nfc(path) && path.split('/').all(is_safe_name)
24}
25
26pub(crate) fn is_safe_name(name: &str) -> bool {
29 !name.is_empty()
30 && name != "."
31 && name != ".."
32 && !name.contains(['/', '\\', '\0'])
33 && !is_reserved(name)
34}
35
36pub(crate) fn is_reserved(name: &str) -> bool {
42 let before_stream = name.split(':').next().unwrap_or_default();
43 let seen: String = before_stream
44 .chars()
45 .filter(|character| !is_ignored_by_macos(*character))
46 .collect();
47 let seen = seen.trim_end_matches(['.', ' ']).to_uppercase();
48 if seen == ".GIT" || seen == ".NIB" {
49 return true;
50 }
51 ["GIT~", "NIB~"].iter().any(|start| {
53 seen.strip_prefix(start)
54 .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|byte| byte.is_ascii_digit()))
55 })
56}
57
58fn is_ignored_by_macos(character: char) -> bool {
61 matches!(
62 character,
63 '\u{200c}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{206a}'..='\u{206f}' | '\u{feff}'
64 )
65}
66
67pub(crate) fn fits_this_system(name: &str) -> bool {
71 if cfg!(windows) {
72 let device = name
73 .split('.')
74 .next()
75 .unwrap_or_default()
76 .trim_end()
77 .to_ascii_uppercase();
78 let numbered = |start: &str| {
79 device.strip_prefix(start).is_some_and(|rest| {
80 matches!(
81 rest,
82 "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
83 )
84 })
85 };
86 !name.contains(['<', '>', ':', '"', '|', '?', '*'])
87 && !name.chars().any(char::is_control)
88 && !name.ends_with(['.', ' '])
89 && !matches!(
90 device.as_str(),
91 "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
92 )
93 && !numbered("COM")
94 && !numbered("LPT")
95 } else {
96 true
97 }
98}
99
100pub(crate) fn tree_path_of(relative: &Path) -> Result<String, &'static str> {
103 let mut names = Vec::new();
104 for component in relative.components() {
105 let Component::Normal(name) = component else {
106 return Err("it is not in the tree's folder");
107 };
108 let name = name.to_str().ok_or("its name is not Unicode")?;
109 names.push(name.nfc().collect::<String>());
110 }
111 let path = names.join("/");
112 if path.is_empty() {
113 return Err("it is the tree's folder");
114 }
115 if path.split('/').any(|name| name.contains('\\')) {
116 return Err("its name holds a backslash, which Windows reads as between folders");
117 }
118 if !is_safe_tree_path(&path) {
119 return Err("its path cannot be in a tree");
120 }
121 Ok(path)
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 #[test]
129 fn names_of_git_and_the_library_are_reserved_however_spelled() {
130 for reserved in [
131 ".git",
132 ".GIT",
133 ".gIt",
134 ".git.",
135 ".git...",
136 ".git ",
137 ".git. .",
138 ".git:stream",
139 ".git::$INDEX_ALLOCATION",
140 "\u{200c}.git",
141 ".g\u{200d}it",
142 ".git\u{feff}",
143 "git~1",
144 "GIT~12",
145 ".g\u{131}t",
146 ".nib",
147 ".NIB",
148 "nib~1",
149 ] {
150 assert!(is_reserved(reserved), "{reserved:?}");
151 }
152 for allowed in [
153 ".gitignore",
154 ".github",
155 ".gitmodules",
156 "git",
157 ".git-crypt",
158 "git~",
159 "git~a",
160 ".nibignore",
161 "nib",
162 "a.git",
163 ] {
164 assert!(!is_reserved(allowed), "{allowed:?}");
165 }
166 }
167
168 #[test]
169 fn a_path_on_disk_becomes_a_tree_path_in_composed_form() {
170 assert_eq!(
171 tree_path_of(Path::new("docs/cafe\u{301}.md")),
172 Ok("docs/caf\u{e9}.md".to_owned())
173 );
174 assert!(tree_path_of(Path::new("../a")).is_err());
175 assert!(tree_path_of(Path::new("")).is_err());
176 assert!(tree_path_of(Path::new("x/.git/config")).is_err());
177 #[cfg(unix)]
178 {
179 use std::os::unix::ffi::OsStrExt;
180 let not_unicode = std::ffi::OsStr::from_bytes(b"a\xff.txt");
181 assert_eq!(
182 tree_path_of(Path::new(not_unicode)),
183 Err("its name is not Unicode")
184 );
185 assert!(tree_path_of(Path::new("a\\b.txt")).is_err());
186 }
187 }
188
189 #[test]
190 fn windows_takes_only_names_it_can_write() {
191 let names = [
192 "CON", "nul.txt", "com1", "LPT9.log", "a:b", "a?", "end.", "end ",
193 ];
194 for name in names {
195 assert_eq!(fits_this_system(name), !cfg!(windows), "{name}");
196 }
197 for name in ["CONSOLE", "com0", "notes.md", "lpt"] {
198 assert!(fits_this_system(name), "{name}");
199 }
200 }
201}