Skip to main content

workyard_system/
identity.rs

1#[cfg(windows)]
2use std::fs::OpenOptions;
3use std::{fs::File, path::Path};
4use workyard_core::Problem;
5
6/// Read the volume serial number and file index from the open Windows handle.
7#[cfg(windows)]
8pub fn file_identity(file: &File) -> Result<(u64, u64), Problem> {
9	use std::os::windows::io::AsRawHandle;
10	use windows_sys::Win32::Storage::FileSystem::{
11		BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
12	};
13
14	let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
15
16	// SAFETY: File owns the valid handle and info is a correctly sized output.
17	if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
18		return Err(Problem::io(
19			"Inspect file identity",
20			std::io::Error::last_os_error(),
21		));
22	}
23
24	Ok((
25		info.dwVolumeSerialNumber as u64,
26		((info.nFileIndexHigh as u64) << 32) | info.nFileIndexLow as u64,
27	))
28}
29
30/// Read the native filesystem identity of the selected file.
31#[cfg(unix)]
32pub fn file_identity(file: &File) -> Result<(u64, u64), Problem> {
33	use std::os::unix::fs::MetadataExt;
34
35	let metadata = file
36		.metadata()
37		.map_err(|e| Problem::io("Inspect file identity", e))?;
38
39	Ok((metadata.dev(), metadata.ino()))
40}
41
42/// Identify a named entry without dereferencing a final symlink.
43#[cfg(unix)]
44pub fn entry_identity(path: &Path) -> Result<(u64, u64), Problem> {
45	use std::os::unix::fs::MetadataExt;
46
47	let metadata = path
48		.symlink_metadata()
49		.map_err(|error| Problem::io("Inspect workspace entry identity", error))?;
50	Ok((metadata.dev(), metadata.ino()))
51}
52
53/// Identify the directory entry itself, including a reparse point, using its Windows handle.
54#[cfg(windows)]
55pub fn entry_identity(path: &Path) -> Result<(u64, u64), Problem> {
56	use std::os::windows::fs::OpenOptionsExt;
57	use windows_sys::Win32::Storage::FileSystem::{
58		FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES,
59	};
60
61	let entry = OpenOptions::new()
62		.access_mode(FILE_READ_ATTRIBUTES)
63		.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
64		.open(path)
65		.map_err(|error| Problem::io("Open workspace entry identity", error))?;
66	file_identity(&entry)
67}
68
69/// Read the native filesystem identity of the selected directory.
70pub fn directory_identity(path: &Path) -> Result<String, Problem> {
71	#[cfg(unix)]
72	let directory = File::open(path).map_err(|e| Problem::io("Open repository identity", e))?;
73
74	#[cfg(windows)]
75	let directory = {
76		use std::os::windows::fs::OpenOptionsExt;
77		OpenOptions::new()
78			.read(true)
79			.custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS)
80			.open(path)
81			.map_err(|e| Problem::io("Open repository identity", e))?
82	};
83
84	let (volume, file) = file_identity(&directory)?;
85
86	Ok(format!("{volume:x}:{file:x}"))
87}