1use std::fs;
2use std::io::ErrorKind;
3use std::path::{Path, PathBuf};
4
5use crate::path::ValidatedRelativePath;
6use crate::{WorkspacePathError, WorkspacePathErrorCode};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct WorkspaceRoot {
27 host_path: PathBuf,
28 identity: ObjectIdentity,
29}
30
31impl WorkspaceRoot {
32 pub fn new(path: impl AsRef<Path>) -> Result<Self, WorkspacePathError> {
39 let host_path = fs::canonicalize(path.as_ref()).map_err(|error| {
40 if error.kind() == ErrorKind::NotFound {
41 WorkspacePathError::new(WorkspacePathErrorCode::WorkspaceNotFound)
42 } else {
43 WorkspacePathError::new(WorkspacePathErrorCode::FilesystemFailure)
44 }
45 })?;
46 let metadata = fs::metadata(&host_path)
47 .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::FilesystemFailure))?;
48 if !metadata.is_dir() {
49 return Err(WorkspacePathError::new(
50 WorkspacePathErrorCode::WorkspaceNotDirectory,
51 ));
52 }
53 Ok(Self {
54 host_path,
55 identity: ObjectIdentity::from_metadata(&metadata),
56 })
57 }
58
59 #[must_use]
61 pub fn host_path(&self) -> &Path {
62 &self.host_path
63 }
64
65 pub fn resolve_existing(&self, path: &str) -> Result<ResolvedExistingPath, WorkspacePathError> {
76 self.verify_root()?;
77 let relative = ValidatedRelativePath::parse(path)?;
78 let candidate = relative.join_to(&self.host_path);
79 let host_path = fs::canonicalize(&candidate).map_err(|error| {
80 if error.kind() == ErrorKind::NotFound {
81 WorkspacePathError::new(WorkspacePathErrorCode::TargetNotFound)
82 } else {
83 WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
84 }
85 })?;
86 self.require_contained(&host_path)?;
87 let metadata = fs::metadata(&host_path)
88 .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget))?;
89 Ok(ResolvedExistingPath {
90 display_path: relative.display().to_owned(),
91 host_path,
92 workspace_root: self.host_path.clone(),
93 identity: ObjectIdentity::from_metadata(&metadata),
94 })
95 }
96
97 pub fn revalidate_existing(
104 &self,
105 target: &ResolvedExistingPath,
106 ) -> Result<(), WorkspacePathError> {
107 if target.workspace_root != self.host_path {
108 return Err(WorkspacePathError::new(
109 WorkspacePathErrorCode::CapabilityMismatch,
110 ));
111 }
112 let current = self
113 .resolve_existing(target.display_path())
114 .map_err(|error| match error.code() {
115 WorkspacePathErrorCode::TargetNotFound
116 | WorkspacePathErrorCode::UnresolvableTarget => {
117 WorkspacePathError::new(WorkspacePathErrorCode::PathChanged)
118 }
119 _ => error,
120 })?;
121 if current.host_path != target.host_path || current.identity != target.identity {
122 return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathChanged));
123 }
124 Ok(())
125 }
126
127 pub fn verify_opened_existing(
138 &self,
139 target: &ResolvedExistingPath,
140 metadata: &fs::Metadata,
141 ) -> Result<(), WorkspacePathError> {
142 if target.workspace_root != self.host_path {
143 return Err(WorkspacePathError::new(
144 WorkspacePathErrorCode::CapabilityMismatch,
145 ));
146 }
147 self.verify_root()?;
148 if ObjectIdentity::from_metadata(metadata) != target.identity {
149 return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathChanged));
150 }
151 Ok(())
152 }
153
154 pub fn resolve_mutation(&self, path: &str) -> Result<ResolvedMutationPath, WorkspacePathError> {
166 self.verify_root()?;
167 let relative = ValidatedRelativePath::parse(path)?;
168 if relative.display() == "." {
169 return Err(WorkspacePathError::new(
170 WorkspacePathErrorCode::WorkspaceRootMutation,
171 ));
172 }
173 let candidate = relative.join_to(&self.host_path);
174
175 if let Ok(host_path) = fs::canonicalize(&candidate) {
176 self.require_contained(&host_path)?;
177 let metadata = fs::metadata(&host_path)
178 .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget))?;
179 Ok(ResolvedMutationPath {
180 display_path: relative.display().to_owned(),
181 host_path: host_path.clone(),
182 workspace_root: self.host_path.clone(),
183 target_existed: true,
184 anchor_path: host_path,
185 anchor_identity: ObjectIdentity::from_metadata(&metadata),
186 })
187 } else {
188 if fs::symlink_metadata(&candidate).is_ok() {
189 return Err(WorkspacePathError::new(
190 WorkspacePathErrorCode::UnresolvableTarget,
191 ));
192 }
193 self.resolve_prospective(&relative, &candidate)
194 }
195 }
196
197 pub fn revalidate_mutation(
208 &self,
209 target: &ResolvedMutationPath,
210 ) -> Result<(), WorkspacePathError> {
211 if target.workspace_root != self.host_path {
212 return Err(WorkspacePathError::new(
213 WorkspacePathErrorCode::CapabilityMismatch,
214 ));
215 }
216 let current = self.resolve_mutation(target.display_path())?;
217 if current.host_path != target.host_path
218 || current.target_existed != target.target_existed
219 || current.anchor_path != target.anchor_path
220 || current.anchor_identity != target.anchor_identity
221 {
222 return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathChanged));
223 }
224 Ok(())
225 }
226
227 fn resolve_prospective(
228 &self,
229 relative: &ValidatedRelativePath,
230 candidate: &Path,
231 ) -> Result<ResolvedMutationPath, WorkspacePathError> {
232 let mut ancestor = candidate
233 .parent()
234 .ok_or_else(|| WorkspacePathError::new(WorkspacePathErrorCode::InvalidPath))?;
235 loop {
236 match fs::symlink_metadata(ancestor) {
237 Ok(metadata) => {
238 let anchor_path = fs::canonicalize(ancestor).map_err(|_| {
239 WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
240 })?;
241 self.require_contained(&anchor_path)?;
242 let followed_metadata = fs::metadata(&anchor_path).map_err(|_| {
243 WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
244 })?;
245 if !followed_metadata.is_dir() {
246 return Err(WorkspacePathError::new(
247 WorkspacePathErrorCode::ParentNotDirectory,
248 ));
249 }
250 let suffix = candidate.strip_prefix(ancestor).map_err(|_| {
251 WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
252 })?;
253 return Ok(ResolvedMutationPath {
254 display_path: relative.display().to_owned(),
255 host_path: anchor_path.join(suffix),
256 workspace_root: self.host_path.clone(),
257 target_existed: false,
258 anchor_path,
259 anchor_identity: ObjectIdentity::from_metadata(&metadata),
260 });
261 }
262 Err(error) if error.kind() == ErrorKind::NotFound => {
263 ancestor = ancestor.parent().ok_or_else(|| {
264 WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
265 })?;
266 }
267 Err(_) => {
268 return Err(WorkspacePathError::new(
269 WorkspacePathErrorCode::FilesystemFailure,
270 ));
271 }
272 }
273 }
274 }
275
276 fn verify_root(&self) -> Result<(), WorkspacePathError> {
277 let current = fs::canonicalize(&self.host_path)
278 .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::FilesystemFailure))?;
279 let metadata = fs::metadata(¤t)
280 .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::FilesystemFailure))?;
281 if current != self.host_path
282 || !metadata.is_dir()
283 || ObjectIdentity::from_metadata(&metadata) != self.identity
284 {
285 return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathChanged));
286 }
287 Ok(())
288 }
289
290 fn require_contained(&self, path: &Path) -> Result<(), WorkspacePathError> {
291 if path.starts_with(&self.host_path) {
292 Ok(())
293 } else {
294 Err(WorkspacePathError::new(
295 WorkspacePathErrorCode::OutsideWorkspace,
296 ))
297 }
298 }
299}
300
301#[derive(Debug, Clone, PartialEq, Eq)]
303pub struct ResolvedExistingPath {
304 display_path: String,
305 host_path: PathBuf,
306 workspace_root: PathBuf,
307 identity: ObjectIdentity,
308}
309
310impl ResolvedExistingPath {
311 #[must_use]
313 pub fn display_path(&self) -> &str {
314 &self.display_path
315 }
316
317 #[must_use]
319 pub fn host_path(&self) -> &Path {
320 &self.host_path
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Eq)]
326pub struct ResolvedMutationPath {
327 display_path: String,
328 host_path: PathBuf,
329 workspace_root: PathBuf,
330 target_existed: bool,
331 anchor_path: PathBuf,
332 anchor_identity: ObjectIdentity,
333}
334
335impl ResolvedMutationPath {
336 #[must_use]
338 pub fn display_path(&self) -> &str {
339 &self.display_path
340 }
341
342 #[must_use]
347 pub fn host_path(&self) -> &Path {
348 &self.host_path
349 }
350
351 #[must_use]
353 pub const fn target_existed_at_resolution(&self) -> bool {
354 self.target_existed
355 }
356}
357
358#[derive(Debug, Clone, PartialEq, Eq)]
359struct ObjectIdentity {
360 #[cfg(unix)]
361 device: u64,
362 #[cfg(unix)]
363 inode: u64,
364 #[cfg(windows)]
365 file_attributes: u32,
366 #[cfg(windows)]
367 creation_time: u64,
368 #[cfg(windows)]
369 last_write_time: u64,
370 #[cfg(windows)]
371 file_size: u64,
372 #[cfg(not(any(unix, windows)))]
373 length: u64,
374 #[cfg(not(any(unix, windows)))]
375 modified: Option<std::time::SystemTime>,
376}
377
378impl ObjectIdentity {
379 fn from_metadata(metadata: &fs::Metadata) -> Self {
380 #[cfg(unix)]
381 {
382 use std::os::unix::fs::MetadataExt;
383 Self {
384 device: metadata.dev(),
385 inode: metadata.ino(),
386 }
387 }
388 #[cfg(windows)]
389 {
390 use std::os::windows::fs::MetadataExt;
391 Self {
392 file_attributes: metadata.file_attributes(),
393 creation_time: metadata.creation_time(),
394 last_write_time: metadata.last_write_time(),
395 file_size: metadata.file_size(),
396 }
397 }
398 #[cfg(not(any(unix, windows)))]
399 {
400 Self {
401 length: metadata.len(),
402 modified: metadata.modified().ok(),
403 }
404 }
405 }
406}