Skip to main content

griz_store/
paths.rs

1//! Physical parent directories identify atomic rename destinations.
2
3use std::{
4    io,
5    path::{Path, PathBuf},
6};
7
8/// Resolves existing directory aliases, retaining a missing directory suffix.
9///
10/// # Errors
11/// Returns an error for inaccessible, non-directory, or dangling-link prefixes.
12pub fn directory_path(path: &Path) -> io::Result<PathBuf> {
13    let mut prefix = path.to_path_buf();
14    let mut missing = Vec::new();
15    loop {
16        match std::fs::canonicalize(&prefix) {
17            Ok(mut directory) => {
18                require_directory(&directory)?;
19                directory.extend(missing.into_iter().rev());
20                return Ok(directory);
21            }
22            Err(error) if error.kind() == io::ErrorKind::NotFound => {
23                missing.push(missing_component(&prefix, error)?);
24                prefix = prefix
25                    .parent()
26                    .filter(|path| !path.as_os_str().is_empty())
27                    .unwrap_or_else(|| Path::new("."))
28                    .to_path_buf();
29            }
30            Err(error) => return Err(error),
31        }
32    }
33}
34
35fn follow_file_links(resolver: &mut PathResolver, path: &Path) -> io::Result<PathBuf> {
36    let mut entry = resolver.resolve(path)?;
37    let original = match std::fs::canonicalize(&entry) {
38        Ok(path) => return Ok(path),
39        Err(error) => error,
40    };
41    let mut visited = std::collections::BTreeSet::new();
42    while let Some(target) = file_link(&entry)? {
43        if !visited.insert(entry.clone()) {
44            return Err(io::Error::new(
45                io::ErrorKind::InvalidInput,
46                format!("symbolic-link cycle: {}", entry.display()),
47            ));
48        }
49        let parent = entry.parent().unwrap_or_else(|| Path::new("."));
50        entry = resolver.resolve(&parent.join(target))?;
51    }
52    if visited.is_empty() {
53        return match original.kind() {
54            io::ErrorKind::NotFound => Ok(entry),
55            _ => Err(original),
56        };
57    }
58    match std::fs::canonicalize(&entry) {
59        Ok(path) => Ok(path),
60        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(entry),
61        Err(error) => Err(error),
62    }
63}
64
65pub(crate) fn file_link(path: &Path) -> io::Result<Option<PathBuf>> {
66    match std::fs::symlink_metadata(path) {
67        Ok(metadata) if metadata.file_type().is_symlink() => std::fs::read_link(path).map(Some),
68        Ok(_) => Ok(None),
69        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
70        Err(error) => Err(error),
71    }
72}
73
74fn require_directory(path: &Path) -> io::Result<()> {
75    if std::fs::metadata(path)?.is_dir() {
76        return Ok(());
77    }
78    Err(io::Error::new(
79        io::ErrorKind::NotADirectory,
80        format!("not a directory: {}", path.display()),
81    ))
82}
83
84fn missing_component(path: &Path, original: io::Error) -> io::Result<std::ffi::OsString> {
85    match std::fs::symlink_metadata(path) {
86        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
87        Err(error) => return Err(error),
88        Ok(_) => return Err(original),
89    }
90    path.file_name()
91        .map(std::ffi::OsStr::to_os_string)
92        .ok_or(original)
93}
94
95/// Resolves a write's parent directory, retaining its final directory entry.
96///
97/// # Errors
98/// Returns an error when the parent contains an invalid directory prefix.
99pub fn destination_path(path: &Path) -> io::Result<PathBuf> {
100    PathResolver::default().resolve(path)
101}
102
103/// Directory and file-alias identities retained for one batch of paths.
104#[derive(Default)]
105pub struct PathResolver {
106    directories: std::collections::BTreeMap<PathBuf, PathBuf>,
107    files: std::collections::BTreeMap<PathBuf, PathBuf>,
108}
109
110impl PathResolver {
111    /// Resolves links and existing filename spelling, caching each path for this batch.
112    ///
113    /// # Errors
114    /// Returns an error for inaccessible paths or symbolic-link cycles.
115    pub fn resolve_file(&mut self, path: &Path) -> io::Result<PathBuf> {
116        if let Some(target) = self.files.get(path) {
117            return Ok(target.clone());
118        }
119        let target = follow_file_links(self, path)?;
120        self.files.insert(path.to_path_buf(), target.clone());
121        Ok(target)
122    }
123
124    /// Resolves a destination, looking up each submitted parent only once.
125    ///
126    /// # Errors
127    /// Returns an error when the parent contains an invalid directory prefix.
128    pub fn resolve(&mut self, path: &Path) -> io::Result<PathBuf> {
129        let Some(name) = path.file_name() else {
130            return directory_path(path);
131        };
132        let parent = path
133            .parent()
134            .filter(|path| !path.as_os_str().is_empty())
135            .unwrap_or_else(|| Path::new("."));
136        if !self.directories.contains_key(parent) {
137            self.directories
138                .insert(parent.to_path_buf(), directory_path(parent)?);
139        }
140        Ok(self.directories[parent].join(name))
141    }
142}