Skip to main content

psync/
files.rs

1//! File identity for `#[psync::graph(owned_files)]`: two paths name one file when the operating
2//! system says so, not when their text matches.
3//!
4//! A path is resolved once, when its region (or its loop) starts:
5//! - an existing file is identified by its device and inode (Unix), which hard links share;
6//! - every path also gets its resolved form: [`std::fs::canonicalize`] (symlinks followed) when it
7//!   exists, else its parent's canonical form joined with its name (a file about to be created),
8//!   else [`std::path::absolute`] (Rust 1.79; lexical, as a last resort).
9//!
10//! Two identities overlap when their inodes match, or when one resolved path contains the other.
11
12extern crate std;
13
14use std::path::{Path, PathBuf};
15
16/// What a path names, as far as the file system can tell when it is resolved.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct FileId {
19    /// Device and inode of the file, when it exists (Unix only).
20    pub inode: Option<(u64, u64)>,
21    /// The path with symlinks and `.`/`..` resolved as far as possible.
22    pub resolved: PathBuf,
23}
24
25impl FileId {
26    /// Resolve `path` now.
27    pub fn of(path: &dyn AsRef<Path>) -> Self {
28        let path = path.as_ref();
29        FileId {
30            inode: inode(path),
31            resolved: resolve(path),
32        }
33    }
34
35    /// Whether the two may be one file, or one a directory containing the other.
36    pub fn overlaps(&self, other: &Self) -> bool {
37        let same_inode = self.inode.is_some() && self.inode == other.inode;
38        same_inode || within(&self.resolved, &other.resolved)
39    }
40}
41
42/// Whether one path is the other or under it.
43fn within(a: &Path, b: &Path) -> bool {
44    a.starts_with(b) || b.starts_with(a)
45}
46
47/// Device and inode of an existing file.
48#[cfg(unix)]
49fn inode(path: &Path) -> Option<(u64, u64)> {
50    use std::os::unix::fs::MetadataExt;
51    std::fs::metadata(path).ok().map(|m| (m.dev(), m.ino()))
52}
53
54/// No inode outside Unix: the resolved path decides.
55#[cfg(not(unix))]
56fn inode(_path: &Path) -> Option<(u64, u64)> {
57    None
58}
59
60/// The canonical path, or the canonical parent joined with the name, or the absolute path.
61fn resolve(path: &Path) -> PathBuf {
62    std::fs::canonicalize(path)
63        .or_else(|_| canonical_parent(path))
64        .or_else(|_| std::path::absolute(path))
65        .unwrap_or_else(|_| path.to_path_buf())
66}
67
68/// For a file not created yet: its directory resolved, then its name.
69fn canonical_parent(path: &Path) -> std::io::Result<PathBuf> {
70    let missing = || std::io::Error::from(std::io::ErrorKind::NotFound);
71    let (parent, name) = (
72        path.parent().ok_or_else(missing)?,
73        path.file_name().ok_or_else(missing)?,
74    );
75    let parent = if parent.as_os_str().is_empty() {
76        Path::new(".")
77    } else {
78        parent
79    };
80    Ok(std::fs::canonicalize(parent)?.join(name))
81}
82
83/// The gate's test under `owned_files`: whether `a` and `b` may be one file.
84pub fn files_overlap(a: &dyn AsRef<Path>, b: &dyn AsRef<Path>) -> bool {
85    FileId::of(a).overlaps(&FileId::of(b))
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    fn scratch(tag: &str) -> PathBuf {
93        let dir =
94            std::env::temp_dir().join(std::format!("psync-files-{tag}-{}", std::process::id()));
95        let _ = std::fs::remove_dir_all(&dir);
96        std::fs::create_dir_all(&dir).unwrap();
97        dir
98    }
99
100    #[test]
101    fn hard_links_and_symlinks_are_one_file() {
102        let d = scratch("links");
103        std::fs::write(d.join("a"), "x").unwrap();
104        std::fs::hard_link(d.join("a"), d.join("hard")).unwrap();
105        #[cfg(unix)]
106        std::os::unix::fs::symlink(d.join("a"), d.join("soft")).unwrap();
107        assert!(files_overlap(&d.join("a"), &d.join("hard")));
108        #[cfg(unix)]
109        assert!(files_overlap(&d.join("a"), &d.join("soft")));
110        std::fs::write(d.join("b"), "y").unwrap();
111        assert!(!files_overlap(&d.join("a"), &d.join("b")));
112        std::fs::remove_dir_all(&d).unwrap();
113    }
114
115    #[test]
116    fn new_files_and_directories_resolve_by_location() {
117        let d = scratch("new");
118        std::fs::create_dir(d.join("sub")).unwrap();
119        // Not created yet: the same name in the same (resolved) directory.
120        assert!(files_overlap(&d.join("sub/../new.txt"), &d.join("new.txt")));
121        assert!(!files_overlap(&d.join("new.txt"), &d.join("other.txt")));
122        // A directory contains what is under it.
123        assert!(files_overlap(&d.join("sub"), &d.join("sub/x")));
124        std::fs::remove_dir_all(&d).unwrap();
125    }
126}