1#![forbid(unsafe_code)]
9
10pub mod dirs;
11pub use dirs::{
12 cache_home, config_home, connection_file_candidates, cortexkit_cache_dir, cortexkit_config_dir,
13 cortexkit_data_dir, cortexkit_run_dir, cortexkit_state_dir, data_home, env_absolute_path, home,
14 state_home, with_env, xdg_data_home, Dirs, EnvSource, PathsError, SystemEnv,
15};
16
17use std::{
18 error::Error,
19 fmt, fs, io,
20 path::{Path, PathBuf},
21};
22
23#[derive(Clone, Debug, PartialEq, Eq, Hash)]
54pub struct ProjectRootId(PathBuf);
55
56impl ProjectRootId {
57 pub fn from_path(path: impl AsRef<Path>) -> Result<Self, IdentityError> {
70 let requested_path = path.as_ref().to_path_buf();
71 match fs::canonicalize(path.as_ref()) {
72 Ok(canonical_path) => Ok(Self(platform_project_root_path(canonical_path))),
73 Err(err) if err.kind() == io::ErrorKind::NotFound => {
74 Err(IdentityError::NonExistentPath {
75 path: requested_path,
76 })
77 }
78 Err(source) => Err(IdentityError::CanonicalizePath {
79 path: requested_path,
80 source,
81 }),
82 }
83 }
84
85 pub fn from_path_allowing_missing(path: impl AsRef<Path>) -> Result<Self, IdentityError> {
109 let resolved = resolve_allowing_missing(path.as_ref(), 0)?;
110 Ok(Self(platform_project_root_path(resolved)))
111 }
112
113 pub fn as_path(&self) -> &Path {
115 &self.0
116 }
117
118 pub fn into_path_buf(self) -> PathBuf {
120 self.0
121 }
122}
123
124impl AsRef<Path> for ProjectRootId {
125 fn as_ref(&self) -> &Path {
126 self.as_path()
127 }
128}
129
130impl fmt::Display for ProjectRootId {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 write!(f, "{}", self.0.display())
133 }
134}
135
136impl From<ProjectRootId> for PathBuf {
137 fn from(value: ProjectRootId) -> Self {
138 value.into_path_buf()
139 }
140}
141
142impl TryFrom<&Path> for ProjectRootId {
143 type Error = IdentityError;
144
145 fn try_from(value: &Path) -> Result<Self, Self::Error> {
146 Self::from_path(value)
147 }
148}
149
150impl TryFrom<PathBuf> for ProjectRootId {
151 type Error = IdentityError;
152
153 fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
154 Self::from_path(value)
155 }
156}
157
158impl TryFrom<&str> for ProjectRootId {
159 type Error = IdentityError;
160
161 fn try_from(value: &str) -> Result<Self, Self::Error> {
162 Self::from_path(Path::new(value))
163 }
164}
165
166impl TryFrom<String> for ProjectRootId {
167 type Error = IdentityError;
168
169 fn try_from(value: String) -> Result<Self, Self::Error> {
170 Self::from_path(PathBuf::from(value))
171 }
172}
173
174#[derive(Debug)]
176pub enum IdentityError {
177 NonExistentPath { path: PathBuf },
180 CanonicalizePath { path: PathBuf, source: io::Error },
182}
183
184impl fmt::Display for IdentityError {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 match self {
187 Self::NonExistentPath { path } => {
188 write!(f, "project root does not exist: {}", path.display())
189 }
190 Self::CanonicalizePath { path, source } => {
191 write!(
192 f,
193 "failed to canonicalize project root {}: {source}",
194 path.display()
195 )
196 }
197 }
198 }
199}
200
201impl Error for IdentityError {
202 fn source(&self) -> Option<&(dyn Error + 'static)> {
203 match self {
204 Self::NonExistentPath { .. } => None,
205 Self::CanonicalizePath { source, .. } => Some(source),
206 }
207 }
208}
209
210#[cfg(not(windows))]
211fn platform_project_root_path(canonical_path: PathBuf) -> PathBuf {
212 canonical_path
213}
214
215const MAX_SYMLINK_HOPS: u32 = 40;
218
219fn resolve_allowing_missing(path: &Path, hops: u32) -> Result<PathBuf, IdentityError> {
224 match fs::canonicalize(path) {
225 Ok(canonical_path) => return Ok(canonical_path),
226 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
227 Err(source) => {
228 return Err(IdentityError::CanonicalizePath {
229 path: path.to_path_buf(),
230 source,
231 });
232 }
233 }
234
235 let (Some(parent), Some(tail)) = (path.parent(), path.file_name()) else {
239 return Err(IdentityError::NonExistentPath {
240 path: path.to_path_buf(),
241 });
242 };
243 let parent = if parent.as_os_str().is_empty() {
246 Path::new(".")
247 } else {
248 parent
249 };
250
251 let resolved_parent = resolve_allowing_missing(parent, hops)?;
252 let candidate = resolved_parent.join(tail);
253
254 match fs::symlink_metadata(&candidate) {
261 Ok(metadata) if metadata.file_type().is_symlink() => {
262 if hops >= MAX_SYMLINK_HOPS {
263 return Err(IdentityError::CanonicalizePath {
264 path: path.to_path_buf(),
265 source: io::Error::new(
266 io::ErrorKind::InvalidData,
267 format!("symbolic link chain exceeded {MAX_SYMLINK_HOPS} hops"),
268 ),
269 });
270 }
271 let target =
272 fs::read_link(&candidate).map_err(|source| IdentityError::CanonicalizePath {
273 path: candidate.clone(),
274 source,
275 })?;
276 let target = if target.is_absolute() {
277 target
278 } else {
279 resolved_parent.join(target)
280 };
281 resolve_allowing_missing(&target, hops.saturating_add(1))
282 }
283 _ => Ok(candidate),
284 }
285}
286
287#[cfg(windows)]
288fn platform_project_root_path(canonical_path: PathBuf) -> PathBuf {
289 windows_non_verbatim_path(canonical_path)
290}
291
292#[cfg(windows)]
293fn windows_non_verbatim_path(path: PathBuf) -> PathBuf {
294 use std::{
295 ffi::OsString,
296 os::windows::ffi::{OsStrExt, OsStringExt},
297 };
298
299 const SEPARATOR: u16 = b'\\' as u16;
300 const DRIVE_SEPARATOR: u16 = b':' as u16;
301 const LOWER_A: u16 = b'a' as u16;
302 const LOWER_Z: u16 = b'z' as u16;
303 const ASCII_CASE_DELTA: u16 = (b'a' - b'A') as u16;
304 const VERBATIM_PREFIX: [u16; 4] = [SEPARATOR, SEPARATOR, b'?' as u16, SEPARATOR];
305 const VERBATIM_UNC_PREFIX: [u16; 8] = [
306 SEPARATOR,
307 SEPARATOR,
308 b'?' as u16,
309 SEPARATOR,
310 b'U' as u16,
311 b'N' as u16,
312 b'C' as u16,
313 SEPARATOR,
314 ];
315
316 let encoded: Vec<u16> = path.as_os_str().encode_wide().collect();
317 let mut normalized = if encoded.starts_with(&VERBATIM_UNC_PREFIX) {
318 let mut non_verbatim = Vec::with_capacity(encoded.len() - VERBATIM_UNC_PREFIX.len() + 2);
319 non_verbatim.extend_from_slice(&[SEPARATOR, SEPARATOR]);
320 non_verbatim.extend_from_slice(&encoded[VERBATIM_UNC_PREFIX.len()..]);
321 non_verbatim
322 } else if encoded.starts_with(&VERBATIM_PREFIX) {
323 encoded[VERBATIM_PREFIX.len()..].to_vec()
324 } else {
325 encoded
326 };
327
328 if normalized.len() >= 2
329 && normalized[1] == DRIVE_SEPARATOR
330 && (LOWER_A..=LOWER_Z).contains(&normalized[0])
331 {
332 normalized[0] -= ASCII_CASE_DELTA;
333 }
334
335 PathBuf::from(OsString::from_wide(&normalized))
336}
337
338#[cfg(test)]
339mod tests {
340 use std::{
341 collections::HashMap,
342 fs,
343 path::PathBuf,
344 sync::atomic::{AtomicUsize, Ordering},
345 time::{SystemTime, UNIX_EPOCH},
346 };
347
348 use super::*;
349
350 static NEXT_TEST_DIR: AtomicUsize = AtomicUsize::new(0);
351
352 #[cfg(unix)]
353 fn symlink_dir(target: &Path, link: &Path) -> io::Result<()> {
354 std::os::unix::fs::symlink(target, link)
355 }
356
357 #[cfg(windows)]
358 fn symlink_dir(target: &Path, link: &Path) -> io::Result<()> {
359 std::os::windows::fs::symlink_dir(target, link)
360 }
361
362 struct TestDir {
363 path: PathBuf,
364 }
365
366 impl TestDir {
367 fn new(label: &str) -> Self {
368 let unique = format!(
369 "cortexkit-paths-project-root-id-{label}-{}-{}-{}",
370 std::process::id(),
371 SystemTime::now()
372 .duration_since(UNIX_EPOCH)
373 .expect("system time should not be before the Unix epoch")
374 .as_nanos(),
375 NEXT_TEST_DIR.fetch_add(1, Ordering::Relaxed)
376 );
377 let path = std::env::temp_dir().join(unique);
378 fs::create_dir(&path).expect("create temporary project-root-id test directory");
379 Self { path }
380 }
381
382 fn child(&self, name: &str) -> PathBuf {
383 self.path.join(name)
384 }
385 }
386
387 impl Drop for TestDir {
388 fn drop(&mut self) {
389 let _ = fs::remove_dir_all(&self.path);
390 }
391 }
392
393 #[test]
402 fn id_survives_the_root_being_deleted() {
403 let temp = TestDir::new("vanished");
404 let root = temp.child("project");
405 fs::create_dir(&root).expect("create project root");
406
407 let while_present = ProjectRootId::from_path(&root).expect("canonicalize live root");
408 fs::remove_dir(&root).expect("remove project root");
409
410 assert!(
411 ProjectRootId::from_path(&root).is_err(),
412 "the strict constructor must still refuse a vanished root, or callers that \
413 use the refusal to DETECT a dead root would silently keep it"
414 );
415 assert_eq!(
416 ProjectRootId::from_path_allowing_missing(&root).expect("resolve vanished root"),
417 while_present,
418 "a root deleted after admission must resolve to the id it was admitted \
419 under, or the caller addresses an empty lineage and is told no such thing \
420 exists rather than being given an error"
421 );
422 }
423
424 #[test]
428 fn missing_tail_resolves_through_a_symlinked_ancestor() {
429 let temp = TestDir::new("symlinked-ancestor");
430 let real = temp.child("real");
431 let link = temp.child("link");
432 fs::create_dir(&real).expect("create real directory");
433 symlink_dir(&real, &link).expect("create ancestor symlink");
434
435 let through_link = ProjectRootId::from_path_allowing_missing(link.join("gone"))
436 .expect("resolve through symlinked ancestor");
437 let through_real = ProjectRootId::from_path_allowing_missing(real.join("gone"))
438 .expect("resolve through real ancestor");
439
440 assert_eq!(
441 through_link, through_real,
442 "a missing tail must resolve through a live symlinked ancestor, or two \
443 spellings of one location mint two different ids"
444 );
445 assert_ne!(
446 through_link.as_path(),
447 link.join("gone"),
448 "non-vacuity: if this equals the input the implementation is normalizing \
449 lexically and the test above would pass for the wrong reason"
450 );
451 }
452
453 #[test]
460 fn dangling_link_resolves_to_its_target_and_survives_the_link_being_repaired() {
461 let temp = TestDir::new("dangling");
462 let target = temp.child("target");
463 let link = temp.child("link");
464 symlink_dir(&target, &link).expect("create dangling symlink");
465
466 let while_dangling = ProjectRootId::from_path_allowing_missing(link.join("session"))
467 .expect("resolve through dangling link");
468
469 fs::create_dir(&target).expect("create link target");
470 fs::create_dir(target.join("session")).expect("create session directory");
471 let after_repair =
472 ProjectRootId::from_path(link.join("session")).expect("canonicalize repaired path");
473
474 assert_eq!(
475 while_dangling, after_repair,
476 "repairing a dangling link must not move the id, or an act of maintenance \
477 silently strands whatever was admitted while it dangled"
478 );
479 }
480
481 #[test]
485 fn symlink_chain_beyond_the_hop_ceiling_is_refused() {
486 let temp = TestDir::new("loop");
487 let first = temp.child("a");
488 let second = temp.child("b");
489 symlink_dir(&second, &first).expect("create first link");
490 symlink_dir(&first, &second).expect("create second link");
491
492 let error = ProjectRootId::from_path_allowing_missing(first.join("gone"))
493 .expect_err("a symlink cycle must be refused");
494 assert!(
495 matches!(error, IdentityError::CanonicalizePath { .. }),
496 "a cycle is an unresolvable path, not a missing one: {error:?}"
497 );
498 }
499
500 #[test]
501 fn path_spellings_to_same_root_have_equal_project_root_ids() {
502 let temp = TestDir::new("spellings");
503 let root = temp.child("project");
504 let nested = root.join("nested");
505 fs::create_dir(&root).expect("create project root");
506 fs::create_dir(&nested).expect("create nested directory");
507
508 let trailing = PathBuf::from(format!("{}{}", root.display(), std::path::MAIN_SEPARATOR));
509 let direct = ProjectRootId::from_path(&root).expect("canonicalize direct root");
510 let with_trailing = ProjectRootId::from_path(trailing).expect("canonicalize trailing root");
511 let with_dot = ProjectRootId::from_path(root.join(".")).expect("canonicalize dot root");
512 let round_trip =
513 ProjectRootId::from_path(nested.join("..")).expect("canonicalize round-trip root");
514
515 assert_eq!(direct, with_trailing);
516 assert_eq!(direct, with_dot);
517 assert_eq!(direct, round_trip);
518 }
519
520 #[cfg(unix)]
521 #[test]
522 fn symlinked_project_root_has_same_id_as_target() {
523 use std::os::unix::fs::symlink;
524
525 let temp = TestDir::new("symlink");
526 let target = temp.child("target");
527 let link = temp.child("link");
528 fs::create_dir(&target).expect("create symlink target");
529 symlink(&target, &link).expect("create symlink to project root");
530
531 let target_id = ProjectRootId::from_path(&target).expect("canonicalize target");
532 let link_id = ProjectRootId::from_path(&link).expect("canonicalize symlink");
533
534 assert_eq!(target_id, link_id);
535 }
536
537 #[test]
538 fn git_worktree_checkout_path_is_distinct_from_main_checkout_path() {
539 let temp = TestDir::new("worktree");
540 let main_checkout = temp.child("main-checkout");
541 let linked_worktree = temp.child("linked-worktree");
542 let main_gitdir = main_checkout.join(".git");
543 let worktree_gitdir = main_gitdir.join("worktrees").join("linked-worktree");
544
545 fs::create_dir(&main_checkout).expect("create main checkout");
546 fs::create_dir(&linked_worktree).expect("create linked worktree checkout");
547 fs::create_dir_all(&worktree_gitdir).expect("create simulated worktree gitdir");
548 fs::write(
549 linked_worktree.join(".git"),
550 format!("gitdir: {}\n", worktree_gitdir.display()),
551 )
552 .expect("write simulated linked-worktree .git file");
553
554 let main_id = ProjectRootId::from_path(&main_checkout).expect("canonicalize main checkout");
555 let worktree_id =
556 ProjectRootId::from_path(&linked_worktree).expect("canonicalize linked worktree");
557
558 assert_ne!(main_id, worktree_id);
559 }
560
561 #[test]
562 fn non_existent_project_root_returns_typed_error() {
563 let temp = TestDir::new("missing");
564 let missing_root = temp.child("missing-project");
565
566 match ProjectRootId::from_path(&missing_root) {
567 Err(IdentityError::NonExistentPath { path }) => assert_eq!(path, missing_root),
568 Err(other) => panic!("expected NonExistentPath error, got {other}"),
569 Ok(id) => panic!("expected missing project root to fail, got {id}"),
570 }
571 }
572
573 #[cfg(target_os = "macos")]
574 #[test]
575 fn macos_var_symlink_resolves_to_private_var() {
576 let id = ProjectRootId::from_path("/var").expect("canonicalize /var");
577
578 assert_eq!(id.as_path(), std::path::Path::new("/private/var"));
579 }
580
581 #[test]
582 fn realpath_preserves_stored_case_on_case_insensitive_filesystems() {
583 let temp = TestDir::new("stored-case");
584 let stored_case = temp.child("SUB");
585 let alternate_case = temp.child("sub");
586 fs::create_dir(&stored_case).expect("create stored-case project root");
587
588 let stored_id =
589 ProjectRootId::from_path(&stored_case).expect("canonicalize stored-case root");
590 match ProjectRootId::from_path(&alternate_case) {
591 Ok(alternate_id) => {
592 assert_eq!(stored_id, alternate_id);
593 assert!(alternate_id.as_path().ends_with("SUB"));
594 }
595 Err(IdentityError::NonExistentPath { path }) if path == alternate_case => {
596 }
598 Err(other) => {
599 panic!("expected alternate case to canonicalize or be absent, got {other}")
600 }
601 }
602 }
603
604 #[test]
605 fn project_root_id_is_hashable_as_hash_map_key() {
606 let temp = TestDir::new("hashmap");
607 let root = temp.child("project");
608 let other_root = temp.child("other-project");
609 fs::create_dir(&root).expect("create project root");
610 fs::create_dir(&other_root).expect("create other project root");
611
612 let id = ProjectRootId::from_path(&root).expect("canonicalize project root");
613 let same_id =
614 ProjectRootId::from_path(root.join(".")).expect("canonicalize equivalent root");
615 let other_id = ProjectRootId::from_path(&other_root).expect("canonicalize different root");
616
617 let mut entries = HashMap::new();
618 entries.insert(id.clone(), "project state");
619
620 assert_eq!(entries.get(&same_id), Some(&"project state"));
621 assert_eq!(entries.get(&other_id), None);
622 }
623
624 #[cfg(windows)]
625 #[test]
626 fn windows_drive_verbatim_prefix_is_stripped() {
627 let path = windows_non_verbatim_path(PathBuf::from(r"\\?\C:\existing"));
628
629 assert_eq!(path, PathBuf::from(r"C:\existing"));
630 }
631
632 #[cfg(windows)]
633 #[test]
634 fn windows_unc_verbatim_prefix_is_stripped() {
635 let path = windows_non_verbatim_path(PathBuf::from(r"\\?\UNC\server\share\existing"));
636
637 assert_eq!(path, PathBuf::from(r"\\server\share\existing"));
638 }
639
640 #[cfg(windows)]
641 #[test]
642 fn windows_lowercase_drive_letter_is_uppercased() {
643 let path = windows_non_verbatim_path(PathBuf::from(r"c:\existing"));
644
645 assert_eq!(path, PathBuf::from(r"C:\existing"));
646 }
647}