Elffuss BraidHub

utopia-ia/elffuss-braid public

356f55034aff · 5.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! What a workspace's file system considers the same name.
5//!
6//! Many file systems ignore letter case, including the default ones of two
7//! common desktop systems, and some ignore Unicode normalisation too. A tree
8//! that holds `README` and `readme`, or `café` written two ways, is valid,
9//! but on such a file system the two names are one file: writing both would
10//! let the second overwrite the first, or write through a symlink the first
11//! one made. Each workspace finds out once, when it is created, by creating
12//! a file and looking it up under other spellings.
13
14use std::borrow::Cow;
15use std::hash::{BuildHasher, Hasher};
16use std::io;
17use std::time::{SystemTime, UNIX_EPOCH};
18
19use cap_std::fs::{Dir, OpenOptions};
20use unicode_normalization::UnicodeNormalization;
21
22/// Prefix of the names braid gives its scratch files inside a workspace.
23/// Status skips them.
24pub(crate) const SCRATCH_PREFIX: &str = ".braid-";
25
26/// Which differences between names a file system ignores.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub struct FileSystem {
29 /// `README` and `readme` are one file.
30 pub ignores_case: bool,
31 /// `café` precomposed and decomposed are one file.
32 pub ignores_normalization: bool,
33}
34
35impl FileSystem {
36 /// The most forgiving file system: one that ignores both.
37 pub const FORGIVING: FileSystem = FileSystem {
38 ignores_case: true,
39 ignores_normalization: true,
40 };
41
42 /// Finds out by creating a scratch file in `dir` and looking it up under
43 /// another case and another normalisation. If the probe itself fails,
44 /// the answer is the most forgiving file system, which refuses the most.
45 pub fn probe(dir: &Dir) -> FileSystem {
46 probe_names(dir).unwrap_or(FileSystem::FORGIVING)
47 }
48
49 /// The form of `name` under which this file system finds it: lowercased
50 /// if case is ignored, in Unicode NFC if normalisation is. A name that
51 /// is not UTF-8 is lowercased as ASCII.
52 pub fn fold<'a>(&self, name: &'a [u8]) -> Cow<'a, [u8]> {
53 if !self.ignores_case && !self.ignores_normalization {
54 return Cow::Borrowed(name);
55 }
56 match std::str::from_utf8(name) {
57 Ok(text) => {
58 let folded: String = match (self.ignores_case, self.ignores_normalization) {
59 (true, true) => text.nfc().flat_map(char::to_lowercase).nfc().collect(),
60 (true, false) => text.chars().flat_map(char::to_lowercase).collect(),
61 _ => text.nfc().collect(),
62 };
63 Cow::Owned(folded.into_bytes())
64 }
65 Err(_) if self.ignores_case => Cow::Owned(name.to_ascii_lowercase()),
66 Err(_) => Cow::Borrowed(name),
67 }
68 }
69}
70
71fn probe_names(dir: &Dir) -> io::Result<FileSystem> {
72 let stem = format!("{SCRATCH_PREFIX}probe-{}-", random_hex());
73 let created = format!("{stem}X\u{e9}");
74 let other_case = format!("{stem}x\u{e9}");
75 let other_form = format!("{stem}Xe\u{301}");
76 dir.open_with(&created, OpenOptions::new().write(true).create_new(true))?;
77 let found = |name: &str| dir.symlink_metadata(name).is_ok();
78 let probed = FileSystem {
79 ignores_case: found(&other_case),
80 ignores_normalization: found(&other_form),
81 };
82 dir.remove_file(&created)?;
83 Ok(probed)
84}
85
86/// Sixteen hex digits that differ between calls and processes, for scratch
87/// file names. Not for secrets: names are always created exclusively.
88pub(crate) fn random_hex() -> String {
89 let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
90 let nanos = SystemTime::now()
91 .duration_since(UNIX_EPOCH)
92 .map_or(0, |since| since.as_nanos());
93 hasher.write_u128(nanos);
94 hasher.write_u32(std::process::id());
95 format!("{:016x}", hasher.finish())
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 #[test]
103 fn folding() {
104 let exact = FileSystem::default();
105 assert_eq!(exact.fold(b"README"), &b"README"[..]);
106 let case = FileSystem {
107 ignores_case: true,
108 ignores_normalization: false,
109 };
110 assert_eq!(case.fold(b"ReadMe"), &b"readme"[..]);
111 assert_ne!(
112 case.fold("caf\u{e9}".as_bytes()),
113 case.fold("cafe\u{301}".as_bytes())
114 );
115 let both = FileSystem::FORGIVING;
116 assert_eq!(
117 both.fold("CAF\u{c9}".as_bytes()),
118 both.fold("cafe\u{301}".as_bytes())
119 );
120 assert_eq!(both.fold(b"\xffA"), &b"\xffa"[..]);
121 }
122
123 #[test]
124 fn probing_leaves_nothing_behind() {
125 let temp = tempfile::tempdir().unwrap();
126 let dir = Dir::open_ambient_dir(temp.path(), cap_std::ambient_authority()).unwrap();
127 let probed = FileSystem::probe(&dir);
128 assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0);
129 // Whatever the answer, it is the same the second time.
130 assert_eq!(FileSystem::probe(&dir), probed);
131 assert_ne!(random_hex(), random_hex());
132 }
133}