Skip to main content

nibkeep_node/library/trees/
paths.rs

1//! The paths of a tree's files: relative to the tree's folder, with `/` between folders, in
2//! Unicode's composed form (NFC); never leaving the folder, and never naming the library's
3//! own folder or Git's, by any spelling that Windows or macOS read as one of them
4//! ([technical design: trees]). Git's own checks came to the same after folder names were used
5//! against it.
6//!
7//! [technical design: trees]: ../../../../../docs/Technical-design.md#15-trees
8
9use std::path::{Component, Path};
10
11use unicode_normalization::{UnicodeNormalization, is_nfc};
12
13/// How long a path in a tree may be, in bytes: longer than any system's limit.
14const MAX_PATH: usize = 4_096;
15
16/// Whether a path is one that a tree may hold, and so one that writing a tree may write:
17/// relative, with `/` between its folders, in composed form, at most 4,096 bytes, with no
18/// empty name, no `.` or `..`, no backslash, which Windows reads as a separator, no zero
19/// byte, and no name that any system reads as `.git` or `.nib`, the folders of Git and of
20/// the library.
21#[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
26/// Whether a name of a file or a folder may be in a tree's path, as [`is_safe_tree_path`]
27/// says.
28pub(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
36/// Whether a name is one that some system reads as `.git` or `.nib`: compared without regard
37/// to case, as Windows' and macOS's file systems compare names, with what Windows drops from
38/// a name's end, dots and spaces, dropped, with what macOS ignores in names dropped, with
39/// what follows a colon dropped, which on Windows names a stream of the file, and with
40/// Windows' short names of them, as `GIT~1`.
41pub(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	// A short name, as Windows makes for names that do not fit 8.3: GIT~1, NIB~2.
52	["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
58/// Whether macOS's file systems ignore a character in names, as HFS+ did: the joiners and
59/// the marks of direction, which Git ignores too when it looks for `.git`.
60fn 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
67/// Whether a name can be written on this system: on Windows, without the characters it
68/// forbids, such as a colon, without a dot or a space at its end, and not a device's name,
69/// such as `CON` or `NUL.txt`; elsewhere, any name a tree may hold.
70pub(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
100/// The path in a tree of what is at `relative` in its folder, if its names are Unicode: in
101/// composed form, with `/` between folders. `Err` says why it cannot be.
102pub(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}