Skip to main content

dayzmake_core/
fileid.rs

1//! File identity: whether two paths name the same file, whatever their spelling.
2
3use std::path::Path;
4
5/// The identity of an existing file: device and inode on unix, volume serial number and file index on Windows.
6///
7/// Two ids are equal when the paths they were taken from name the same file: through a hard link, a symlink, a
8/// different case on a case-insensitive file system, or a relative and an absolute spelling.
9///
10/// A `FileId` holds an open handle to the file. On Windows the identity is valid only while that handle is open,
11/// so keep the `FileId` alive for as long as it is compared. Creating many ids at once holds many open files.
12///
13/// `same-file` compares a 32-bit volume serial number and a 64-bit file index, but `ReFS` (Dev Drive) file ids are
14/// 128 bits, so two different files could compare equal there. Two ids therefore also have to agree on the file
15/// length to be equal; a pair of different files of the same length on `ReFS` is the one case left undetected.
16///
17/// The length is read when two ids are compared, not when they are created (a growing temp file stays equal to
18/// itself). Two ids compare equal only if both lengths can be read and match, so an id is not necessarily equal to
19/// itself and the type is `PartialEq` only.
20#[derive(Debug)]
21pub struct FileId(same_file::Handle);
22
23impl FileId {
24    fn len(&self) -> Option<u64> {
25        self.0.as_file().metadata().ok().map(|m| m.len())
26    }
27}
28
29impl PartialEq for FileId {
30    fn eq(&self, other: &FileId) -> bool {
31        // the length is read now, not at creation: the same file always has one length at one moment
32        let len = self.len();
33        self.0 == other.0 && len.is_some() && len == other.len()
34    }
35}
36
37impl FileId {
38    /// The identity of the file at `path` (symlinks are followed), or `None` when it cannot be opened
39    /// (missing, removed meanwhile, no permission) or is neither a regular file nor a folder (a FIFO or
40    /// device is never opened). A file without an identity is never the same as another one.
41    #[must_use]
42    pub fn of(path: &Path) -> Option<FileId> {
43        // opening a FIFO or a device can block, so only regular files and folders are opened
44        let meta = std::fs::metadata(path).ok()?;
45        if !meta.is_file() && !meta.is_dir() {
46            return None;
47        }
48        // an unopenable file is "not the same file" by contract
49        same_file::Handle::from_path(path).ok().map(FileId)
50    }
51}
52
53impl FileId {
54    /// The identity of the file standard output is redirected to, or `None` unless that is a regular file: a
55    /// terminal, a device, a closed stdout or a failed duplicate all give `None`.
56    ///
57    /// The identity is taken from a duplicate of the stdout descriptor (handle on Windows), owned by the returned
58    /// id, so dropping it never closes the process's real stdout. On Windows a pipe or `NUL` may get an identity; a
59    /// pipe lives on the named-pipe file system's volume and never matches a file on a disk volume, so nothing is
60    /// excluded (`NUL` is no disk file either, so an identity for it is harmless).
61    #[must_use]
62    pub fn stdout() -> Option<FileId> {
63        #[cfg(any(unix, windows))]
64        {
65            #[cfg(unix)]
66            let owned = {
67                use std::os::fd::AsFd;
68                std::io::stdout().as_fd().try_clone_to_owned().ok()?
69            };
70            #[cfg(windows)]
71            let owned = {
72                use std::os::windows::io::AsHandle;
73                std::io::stdout().as_handle().try_clone_to_owned().ok()?
74            };
75            let file = std::fs::File::from(owned);
76            if !file.metadata().ok()?.is_file() {
77                return None;
78            }
79            same_file::Handle::from_file(file).ok().map(FileId)
80        }
81        #[cfg(not(any(unix, windows)))]
82        {
83            None
84        }
85    }
86}
87
88/// Whether `a` and `b` name the same existing file. `false` when either cannot be opened.
89#[must_use]
90pub fn is_same_file(a: &Path, b: &Path) -> bool {
91    match (FileId::of(a), FileId::of(b)) {
92        (Some(a), Some(b)) => a == b,
93        _ => false,
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn same_and_different_files() {
103        let dir = tempfile::tempdir().unwrap();
104        let a = dir.path().join("a");
105        let b = dir.path().join("b");
106        std::fs::write(&a, "x").unwrap();
107        std::fs::write(&b, "x").unwrap();
108        assert!(is_same_file(&a, &a));
109        assert!(is_same_file(&a, &dir.path().join(".").join("a")));
110        assert!(!is_same_file(&a, &b));
111    }
112
113    #[test]
114    fn a_missing_file_is_never_the_same() {
115        let dir = tempfile::tempdir().unwrap();
116        let a = dir.path().join("a");
117        let gone = dir.path().join("gone");
118        std::fs::write(&a, "x").unwrap();
119        assert!(FileId::of(&gone).is_none());
120        assert!(!is_same_file(&a, &gone));
121        assert!(!is_same_file(&gone, &gone));
122    }
123
124    #[test]
125    fn different_files_of_different_length_never_match() {
126        let dir = tempfile::tempdir().unwrap();
127        let a = dir.path().join("a");
128        let b = dir.path().join("b");
129        std::fs::write(&a, "x").unwrap();
130        std::fs::write(&b, "xyz").unwrap();
131        assert!(!is_same_file(&a, &b));
132        // the same file stays the same while it grows
133        let before = FileId::of(&a).unwrap();
134        std::fs::write(&a, "longer").unwrap();
135        assert_eq!(before, FileId::of(&a).unwrap());
136    }
137
138    #[test]
139    fn stdout_identity_leaves_stdout_open() {
140        // under the test harness stdout is a pipe or a file; either way the lookup must not close it
141        let _ = FileId::stdout();
142        let _ = FileId::stdout();
143        #[cfg(unix)]
144        {
145            use std::os::fd::AsFd;
146            // fd 1 is still open: it can be duplicated again
147            assert!(std::io::stdout().as_fd().try_clone_to_owned().is_ok());
148        }
149        std::io::Write::flush(&mut std::io::stdout()).unwrap();
150    }
151
152    #[cfg(unix)]
153    #[test]
154    fn hard_links_and_symlinks_are_the_same_file() {
155        let dir = tempfile::tempdir().unwrap();
156        let a = dir.path().join("a");
157        std::fs::write(&a, "x").unwrap();
158        std::fs::hard_link(&a, dir.path().join("h")).unwrap();
159        std::os::unix::fs::symlink("a", dir.path().join("s")).unwrap();
160        assert!(is_same_file(&a, &dir.path().join("h")));
161        assert!(is_same_file(&a, &dir.path().join("s")));
162    }
163}