Skip to main content

workyard_state/
paths.rs

1use std::path::{Component, Path, PathBuf};
2use workyard_core::Problem;
3
4/// Resolve existing ancestors so absent destinations still compare through symlinks.
5pub fn canonical_future(path: &Path) -> Result<PathBuf, Problem> {
6	let absolute = if path.is_absolute() {
7		path.to_path_buf()
8	} else {
9		std::env::current_dir()
10			.map_err(|e| Problem::io("Read current directory", e))?
11			.join(path)
12	};
13	let mut resolved = PathBuf::new();
14	let mut components = absolute.components().peekable();
15	while let Some(component) = components.next() {
16		match component {
17			Component::Prefix(prefix) if components.peek() == Some(&Component::RootDir) => {
18				// A drive prefix alone is not the drive root; inspect it with its separator.
19				resolved.push(prefix.as_os_str());
20				continue;
21			}
22			Component::CurDir => continue,
23			Component::ParentDir => {
24				resolved.pop();
25			}
26			other => resolved.push(other),
27		}
28		match resolved.symlink_metadata() {
29			Ok(_) => {
30				resolved = resolved
31					.canonicalize()
32					.map_err(|e| Problem::io(format!("Resolve {resolved:?}"), e))?
33			}
34			Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
35			Err(error) => return Err(Problem::io(format!("Inspect {resolved:?}"), error)),
36		}
37	}
38
39	Ok(resolved)
40}
41
42/// Check path presence while preserving errors that prevent inspection.
43pub fn exists(path: &Path) -> Result<bool, Problem> {
44	match path.symlink_metadata() {
45		Ok(_) => Ok(true),
46		Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
47		Err(error) => Err(Problem::io(format!("Inspect {path:?}"), error)),
48	}
49}
50
51#[cfg(all(test, windows))]
52#[test]
53fn resolves_existing_and_future_paths_under_a_windows_root() {
54	let fixture = tempfile::tempdir().unwrap();
55	let canonical = fixture.path().canonicalize().unwrap();
56	for directory in [fixture.path(), canonical.as_path()] {
57		assert_eq!(canonical_future(directory).unwrap(), canonical);
58		let future = directory.join("not created");
59		assert_eq!(
60			canonical_future(&future).unwrap(),
61			canonical.join("not created")
62		);
63		assert!(!future.exists());
64	}
65}