1use std::path::{Component, Path, PathBuf};
9
10pub fn normalize_lexically(p: &Path) -> PathBuf {
14 let mut out = PathBuf::new();
15 for c in p.components() {
16 match c {
17 Component::ParentDir => {
18 out.pop();
19 }
20 Component::CurDir => {}
21 other => out.push(other),
22 }
23 }
24 out
25}
26
27pub const MAX_LINK_HOPS: u32 = 40;
30
31pub fn resolve_physically(path: &Path) -> PathBuf {
37 let mut wanted = path.to_path_buf();
38 for _ in 0..=MAX_LINK_HOPS {
39 let parts: Vec<Component> = wanted.components().collect();
40 let Some((split, out)) = (1..=parts.len()).rev().find_map(|split| {
41 let prefix: PathBuf = parts[..split].iter().collect();
42 Some((split, std::fs::canonicalize(prefix).ok()?))
43 }) else {
44 return normalize_lexically(&wanted);
45 };
46 let rest = &parts[split..];
47 match first_below(&out, rest)
48 .and_then(|(link, after)| Some(out.join(std::fs::read_link(link).ok()?).join(after)))
49 {
50 Some(next) => wanted = next,
51 None => return put_back(out, rest),
52 }
53 }
54 wanted
55}
56
57pub fn first_below(out: &Path, rest: &[Component]) -> Option<(PathBuf, PathBuf)> {
60 let (Component::Normal(name), after) = rest.split_first()? else {
61 return None;
62 };
63 Some((out.join(name), after.iter().collect()))
64}
65
66pub fn put_back(mut out: PathBuf, rest: &[Component]) -> PathBuf {
68 for part in rest {
69 match part {
70 Component::ParentDir => {
71 out.pop();
72 }
73 Component::CurDir => {}
74 other => out.push(other),
75 }
76 }
77 out
78}
79
80const DJB2_INIT: u64 = 5381;
82
83fn djb2_hash(s: &str) -> u64 {
85 let mut hash = DJB2_INIT;
86 for byte in s.bytes() {
87 hash = hash.wrapping_mul(33).wrapping_add(byte as u64);
88 }
89 hash
90}
91
92fn radix36_encode(mut value: u64) -> String {
96 const CHARS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
97 if value == 0 {
98 return "0".to_string();
99 }
100 let mut digits = Vec::new();
101 while value > 0 {
102 digits.push(CHARS[(value % 36) as usize]);
103 value /= 36;
104 }
105 digits.iter().rev().map(|&d| d as char).collect()
106}
107
108const SANITIZE_MAX_LEN: usize = 200;
110pub const MAX_SANITIZED_LENGTH: usize = SANITIZE_MAX_LEN;
113
114pub fn sanitize_for_fs(name: &str) -> String {
122 let sanitized: String = name
123 .chars()
124 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
125 .collect();
126
127 if sanitized.len() <= SANITIZE_MAX_LEN {
128 return sanitized;
129 }
130
131 let hash = djb2_hash(name);
132 let suffix = radix36_encode(hash);
133 let prefix_len = SANITIZE_MAX_LEN.saturating_sub(suffix.len() + 1);
134 let prefix: String = sanitized.chars().take(prefix_len).collect();
135 format!("{prefix}-{suffix}")
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 #[test]
143 fn lexical_normalization_drops_dots_and_pops_parents() {
144 assert_eq!(
145 normalize_lexically(Path::new("/a/./b/../c")),
146 PathBuf::from("/a/c")
147 );
148 }
149
150 #[test]
151 fn physical_resolution_pops_a_parent_after_a_missing_component() {
152 let dir = tempfile::tempdir().unwrap();
153 let real = std::fs::canonicalize(dir.path()).unwrap();
154 let got = resolve_physically(&dir.path().join("missing/../x"));
155 assert_eq!(got, real.join("x"));
156 }
157
158 #[cfg(unix)]
159 #[test]
160 fn physical_resolution_follows_a_symlink_before_a_parent_step() {
161 let dir = tempfile::tempdir().unwrap();
162 let real = std::fs::canonicalize(dir.path()).unwrap();
163 std::fs::create_dir_all(real.join("target/inner")).unwrap();
164 std::os::unix::fs::symlink(real.join("target/inner"), real.join("link")).unwrap();
165 let got = resolve_physically(&real.join("link/../x"));
166 assert_eq!(got, real.join("target/x"));
167 }
168
169 #[cfg(unix)]
170 #[test]
171 fn physical_resolution_follows_a_dangling_symlink_and_a_chain_of_them() {
172 let dir = tempfile::tempdir().unwrap();
173 let real = std::fs::canonicalize(dir.path()).unwrap();
174 std::fs::create_dir_all(real.join("forge")).unwrap();
175 std::os::unix::fs::symlink("../.git/hooks/pre-commit", real.join("forge/h")).unwrap();
176 assert_eq!(
177 resolve_physically(&real.join("forge/h")),
178 real.join(".git/hooks/pre-commit")
179 );
180 std::os::unix::fs::symlink(real.join("forge/h"), real.join("chained")).unwrap();
181 assert_eq!(
182 resolve_physically(&real.join("chained")),
183 real.join(".git/hooks/pre-commit")
184 );
185 std::os::unix::fs::symlink(real.join("absent"), real.join("dir-link")).unwrap();
186 assert_eq!(
187 resolve_physically(&real.join("dir-link/new.txt")),
188 real.join("absent/new.txt")
189 );
190 }
191
192 #[cfg(unix)]
193 #[test]
194 fn physical_resolution_of_a_symlink_loop_ends() {
195 let dir = tempfile::tempdir().unwrap();
196 let real = std::fs::canonicalize(dir.path()).unwrap();
197 std::os::unix::fs::symlink(real.join("b"), real.join("a")).unwrap();
198 std::os::unix::fs::symlink(real.join("a"), real.join("b")).unwrap();
199 let got = resolve_physically(&real.join("a"));
200 assert!(got == real.join("a") || got == real.join("b"), "{got:?}");
201 }
202
203 #[test]
204 fn test_basic_string() {
205 let result = sanitize_for_fs("hello");
206 assert_eq!(result, "hello");
207 }
208
209 #[test]
210 fn test_special_chars_replaced() {
211 let result = sanitize_for_fs("/Users/foo/my-project");
212 assert_eq!(result, "-Users-foo-my-project");
213 }
214
215 #[test]
216 fn test_spaces_replaced() {
217 let result = sanitize_for_fs("hello world");
218 assert_eq!(result, "hello-world");
219 }
220
221 #[test]
222 fn test_djb2_hash_consistency() {
223 let h1 = djb2_hash("test");
224 let h2 = djb2_hash("test");
225 assert_eq!(h1, h2);
226 }
227
228 #[test]
229 fn test_djb2_hash_different_inputs() {
230 let h1 = djb2_hash("abc");
231 let h2 = djb2_hash("xyz");
232 assert_ne!(h1, h2);
233 }
234
235 #[test]
236 fn test_radix36_zero() {
237 assert_eq!(radix36_encode(0), "0");
238 }
239
240 #[test]
241 fn test_radix36_encoding() {
242 let encoded = radix36_encode(10);
243 assert_eq!(encoded, "a");
244 }
245
246 #[test]
247 fn test_sanitize_produces_different_outputs_for_different_inputs() {
248 let r1 = sanitize_for_fs("project alpha");
249 let r2 = sanitize_for_fs("project beta");
250 assert_ne!(r1, r2);
251 }
252
253 #[test]
254 fn test_sanitize_truncates_long_inputs() {
255 let long = "a".repeat(300);
256 let result = sanitize_for_fs(&long);
257 assert!(result.len() < 300);
259 assert!(!result.is_empty());
260 }
261
262 #[test]
263 fn test_sanitize_allows_alphanumeric() {
264 let result = sanitize_for_fs("MyProject_v2.0");
265 assert_eq!(result, "MyProject-v2-0");
266 }
267}