Debian Codegraph @

rust/hg-core/src/vfs.rs

raw
1 use std::fs::File;
2 use std::fs::Metadata;
3 use std::fs::OpenOptions;
4 use std::io::ErrorKind;
5 use std::io::Read;
6 use std::io::Seek;
7 use std::io::Write;
8 use std::os::fd::AsRawFd;
9 use std::os::unix::fs::FileExt;
10 use std::os::unix::fs::MetadataExt;
11 use std::os::unix::fs::PermissionsExt;
12 use std::path::Path;
13 use std::path::PathBuf;
14 #[cfg(test)]
15 use std::sync::atomic::AtomicUsize;
16 #[cfg(test)]
17 use std::sync::atomic::Ordering;
18 use std::sync::OnceLock;
19
20 use dyn_clone::DynClone;
21 use format_bytes::format_bytes;
22 use memmap2::Mmap;
23 use memmap2::MmapOptions;
24 use rand::distr::Alphanumeric;
25 use rand::distr::SampleString;
26
27 use crate::errors::HgError;
28 use crate::errors::HgResultExt;
29 use crate::errors::IoErrorContext;
30 use crate::errors::IoResultExt;
31 use crate::exit_codes;
32 use crate::revlog::path_encode::path_encode;
33 use crate::revlog::path_encode::PathEncoding;
34 use crate::utils::files::get_bytes_from_path;
35 use crate::utils::files::get_path_from_bytes;
36
37 /// Filesystem access abstraction for the contents of a given "base" diretory
38 #[derive(Clone)]
39 pub struct VfsImpl {
40 pub(crate) base: PathBuf,
41 pub readonly: bool,
42 pub mode: Option<u32>,
43 pub encoding: PathEncoding,
44 }
45
46 struct FileNotFound(std::io::Error, PathBuf);
47
48 /// Store the umask for the whole process since it's expensive to get.
49 static UMASK: OnceLock<u32> = OnceLock::new();
50
51 pub fn get_umask() -> u32 {
52 *UMASK.get_or_init(|| unsafe {
53 // TODO is there any way of getting the umask without temporarily
54 // setting it? Doesn't this affect all threads in this tiny window?
55 let mask = libc::umask(0);
56 libc::umask(mask);
57 #[allow(clippy::useless_conversion)]
58 (mask & 0o777).into()
59 })
60 }
61
62 /// Return the (unix) mode with which we will create/fix files
63 fn get_mode(base: impl AsRef<Path>) -> Option<u32> {
64 match base.as_ref().metadata() {
65 Ok(meta) => {
66 // files in .hg/ will be created using this mode
67 let mode = meta.mode();
68 // avoid some useless chmods
69 if (0o777 & !get_umask()) == (0o777 & mode) {
70 None
71 } else {
72 Some(mode)
73 }
74 }
75 Err(_) => None,
76 }
77 }
78
79 impl VfsImpl {
80 pub fn new(base: PathBuf, readonly: bool, encoding: PathEncoding) -> Self {
81 let mode = get_mode(&base);
82 Self { base, readonly, mode, encoding }
83 }
84
85 // XXX these methods are probably redundant with VFS trait?
86
87 pub fn join(&self, relative_path: impl AsRef<Path>) -> PathBuf {
88 self.base.join(relative_path)
89 }
90
91 pub fn symlink_metadata(
92 &self,
93 relative_path: impl AsRef<Path>,
94 ) -> Result<std::fs::Metadata, HgError> {
95 let path = self.join(relative_path);
96 std::fs::symlink_metadata(&path).when_reading_file(&path)
97 }
98
99 pub fn read_link(
100 &self,
101 relative_path: impl AsRef<Path>,
102 ) -> Result<PathBuf, HgError> {
103 let path = self.join(relative_path);
104 std::fs::read_link(&path).when_reading_file(&path)
105 }
106
107 pub fn read(
108 &self,
109 relative_path: impl AsRef<Path>,
110 ) -> Result<Vec<u8>, HgError> {
111 let path = self.join(relative_path);
112 std::fs::read(&path).when_reading_file(&path)
113 }
114
115 /// Returns `Ok(None)` if the file does not exist.
116 pub fn try_read(
117 &self,
118 relative_path: impl AsRef<Path>,
119 ) -> Result<Option<Vec<u8>>, HgError> {
120 match self.read(relative_path) {
121 Err(e) => match &e {
122 HgError::IoError { error, .. } => match error.kind() {
123 ErrorKind::NotFound => Ok(None),
124 _ => Err(e),
125 },
126 _ => Err(e),
127 },
128 Ok(v) => Ok(Some(v)),
129 }
130 }
131
132 fn mmap_open_gen(
133 &self,
134 relative_path: impl AsRef<Path>,
135 ) -> Result<Result<Mmap, FileNotFound>, HgError> {
136 let path = self.join(relative_path);
137 let file = match std::fs::File::open(&path) {
138 Err(err) => {
139 if let ErrorKind::NotFound = err.kind() {
140 return Ok(Err(FileNotFound(err, path)));
141 };
142 return (Err(err)).when_reading_file(&path);
143 }
144 Ok(file) => file,
145 };
146 // Safety is "enforced" by locks and assuming other processes are
147 // well-behaved. If any misbehaving or malicious process does touch
148 // the index, it could lead to corruption. This is inherent
149 // to file-based `mmap`, though some platforms have some ways of
150 // mitigating.
151 // TODO linux: set the immutable flag with `chattr(1)`?
152 let mmap = unsafe { MmapOptions::new().map(&file) }
153 .when_reading_file(&path)?;
154 Ok(Ok(mmap))
155 }
156
157 pub fn mmap_open_opt(
158 &self,
159 relative_path: impl AsRef<Path>,
160 ) -> Result<Option<Mmap>, HgError> {
161 self.mmap_open_gen(relative_path).map(|res| res.ok())
162 }
163
164 pub fn mmap_open(
165 &self,
166 relative_path: impl AsRef<Path>,
167 ) -> Result<Mmap, HgError> {
168 match self.mmap_open_gen(relative_path)? {
169 Err(FileNotFound(err, path)) => Err(err).when_reading_file(&path),
170 Ok(res) => Ok(res),
171 }
172 }
173
174 pub fn create_working_copy(
175 &self,
176 filename: &Path,
177 ) -> Result<VfsFile, HgError> {
178 if self.readonly {
179 return Err(HgError::abort(
180 "write access in a readonly vfs",
181 exit_codes::ABORT,
182 None,
183 ));
184 }
185 let path = self.base.join(filename);
186
187 // This avoids permission errors if the file somehow already exists
188 // Let it fail: either it didn't exist (good), or we really don't have
189 // the rights to do anything about this file, let `open` fail.
190 // This also removes hardlinks, takes care of non-fatal permissions.
191 std::fs::remove_file(&path)
192 .when_writing_file(&path)
193 .io_not_found_as_none()?;
194
195 let file = OpenOptions::new()
196 .create(true)
197 .truncate(true)
198 .write(true)
199 .read(true)
200 .open(&path)
201 .when_writing_file(&path)?;
202
203 Ok(VfsFile::Normal { file, check_ambig: None, path: path.to_owned() })
204 }
205
206 #[cfg(unix)]
207 pub fn create_symlink(
208 &self,
209 relative_link_path: impl AsRef<Path>,
210 target_path: impl AsRef<Path>,
211 ) -> Result<(), HgError> {
212 let link_path = self.join(relative_link_path);
213 std::os::unix::fs::symlink(target_path, &link_path)
214 .when_writing_file(&link_path)
215 }
216
217 /// Write `contents` into a temporary file, then rename to `relative_path`.
218 /// This makes writing to a file "atomic": a reader opening that path will
219 /// see either the previous contents of the file or the complete new
220 /// content, never a partial write.
221 pub fn atomic_write(
222 &self,
223 relative_path: impl AsRef<Path>,
224 contents: &[u8],
225 ) -> Result<(), HgError> {
226 let mut tmp = tempfile::Builder::new()
227 .permissions(std::fs::Permissions::from_mode(0o666))
228 .tempfile_in(&self.base)
229 .when_writing_file(&self.base)?;
230 tmp.write_all(contents)
231 .and_then(|()| tmp.flush())
232 .when_writing_file(tmp.path())?;
233 let path = self.join(relative_path);
234 tmp.persist(&path).map_err(|e| e.error).when_writing_file(&path)?;
235 Ok(())
236 }
237 }
238
239 fn fs_metadata(
240 path: impl AsRef<Path>,
241 ) -> Result<Option<std::fs::Metadata>, HgError> {
242 let path = path.as_ref();
243 match path.metadata() {
244 Ok(meta) => Ok(Some(meta)),
245 Err(error) => match error.kind() {
246 // TODO: when we require a Rust version where `NotADirectory` is
247 // stable, invert this logic and return None for it and `NotFound`
248 // and propagate any other error.
249 ErrorKind::PermissionDenied => Err(error).with_context(|| {
250 IoErrorContext::ReadingMetadata(path.to_owned())
251 }),
252 _ => Ok(None),
253 },
254 }
255 }
256
257 /// Abstraction over the files handled by a [`Vfs`].
258 #[derive(Debug)]
259 pub enum VfsFile {
260 Atomic(AtomicFile),
261
262 Normal {
263 file: File,
264 path: PathBuf,
265 /// If `Some`, check (and maybe fix) this file's timestamp ambiguity.
266 /// See [`is_filetime_ambiguous`].
267 check_ambig: Option<Metadata>,
268 },
269 }
270
271 impl VfsFile {
272 pub fn normal(file: File, path: PathBuf) -> Self {
273 Self::Normal { file, check_ambig: None, path }
274 }
275 pub fn normal_check_ambig(
276 file: File,
277 path: PathBuf,
278 ) -> Result<Self, HgError> {
279 Ok(Self::Normal {
280 file,
281 check_ambig: Some(path.metadata().when_reading_file(&path)?),
282 path,
283 })
284 }
285
286 pub fn try_clone(&self) -> Result<VfsFile, HgError> {
287 Ok(match self {
288 VfsFile::Atomic(AtomicFile {
289 fp,
290 temp_path,
291 check_ambig,
292 target_name,
293 is_open,
294 }) => Self::Atomic(AtomicFile {
295 fp: fp.try_clone().when_reading_file(temp_path)?,
296 temp_path: temp_path.clone(),
297 check_ambig: *check_ambig,
298 target_name: target_name.clone(),
299 is_open: *is_open,
300 }),
301 VfsFile::Normal { file, check_ambig, path } => Self::Normal {
302 file: file.try_clone().when_reading_file(path)?,
303 check_ambig: check_ambig.clone(),
304 path: path.to_owned(),
305 },
306 })
307 }
308 pub fn set_len(&self, len: u64) -> Result<(), std::io::Error> {
309 match self {
310 VfsFile::Atomic(atomic_file) => atomic_file.fp.set_len(len),
311 VfsFile::Normal { file, .. } => file.set_len(len),
312 }
313 }
314
315 pub fn metadata(&self) -> Result<std::fs::Metadata, std::io::Error> {
316 match self {
317 VfsFile::Atomic(atomic_file) => atomic_file.fp.metadata(),
318 VfsFile::Normal { file, .. } => file.metadata(),
319 }
320 }
321 }
322
323 impl FileExt for VfsFile {
324 fn read_at(&self, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
325 match self {
326 VfsFile::Atomic(atomic_file) => atomic_file.fp.read_at(buf, offset),
327 VfsFile::Normal { file, .. } => file.read_at(buf, offset),
328 }
329 }
330
331 fn write_at(&self, buf: &[u8], offset: u64) -> std::io::Result<usize> {
332 match self {
333 VfsFile::Atomic(atomic_file) => {
334 atomic_file.fp.write_at(buf, offset)
335 }
336 VfsFile::Normal { file, .. } => file.write_at(buf, offset),
337 }
338 }
339 }
340
341 impl AsRawFd for VfsFile {
342 fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
343 match self {
344 VfsFile::Atomic(atomic_file) => atomic_file.fp.as_raw_fd(),
345 VfsFile::Normal { file, .. } => file.as_raw_fd(),
346 }
347 }
348 }
349
350 impl Seek for VfsFile {
351 fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
352 match self {
353 VfsFile::Atomic(atomic_file) => atomic_file.seek(pos),
354 VfsFile::Normal { file, .. } => file.seek(pos),
355 }
356 }
357 }
358
359 impl Read for VfsFile {
360 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
361 match self {
362 VfsFile::Atomic(atomic_file) => atomic_file.fp.read(buf),
363 VfsFile::Normal { file, .. } => file.read(buf),
364 }
365 }
366 }
367
368 impl Write for VfsFile {
369 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
370 match self {
371 VfsFile::Atomic(atomic_file) => atomic_file.fp.write(buf),
372 VfsFile::Normal { file, .. } => file.write(buf),
373 }
374 }
375
376 fn flush(&mut self) -> std::io::Result<()> {
377 match self {
378 VfsFile::Atomic(atomic_file) => atomic_file.fp.flush(),
379 VfsFile::Normal { file, .. } => file.flush(),
380 }
381 }
382 }
383
384 impl Drop for VfsFile {
385 fn drop(&mut self) {
386 if let VfsFile::Normal { path, check_ambig: Some(old), .. } = self {
387 avoid_timestamp_ambiguity(path, old)
388 }
389 }
390 }
391
392 /// Records the number of times we've fixed a timestamp ambiguity, only
393 /// applicable for tests.
394 #[cfg(test)]
395 static TIMESTAMP_FIXES_CALLS: AtomicUsize = AtomicUsize::new(0);
396
397 fn avoid_timestamp_ambiguity(path: &Path, old: &Metadata) {
398 if let Ok(new) = path.metadata() {
399 let is_ambiguous = is_filetime_ambiguous(&new, old);
400 if is_ambiguous {
401 let advanced =
402 filetime::FileTime::from_unix_time(old.mtime() + 1, 0);
403 if filetime::set_file_times(path, advanced, advanced).is_ok() {
404 #[cfg(test)]
405 {
406 TIMESTAMP_FIXES_CALLS.fetch_add(1, Ordering::Relaxed);
407 }
408 }
409 }
410 }
411 }
412
413 /// Examine whether new stat is ambiguous against old one
414 ///
415 /// `S[N]` below means stat of a file at `N`-th change:
416 ///
417 /// - `S[n-1].ctime < S[n].ctime`: can detect change of a file
418 /// - `S[n-1].ctime == S[n].ctime`
419 /// - `S[n-1].ctime < S[n].mtime`: means natural advancing (*1)
420 /// - `S[n-1].ctime == S[n].mtime`: is ambiguous (*2)
421 /// - `S[n-1].ctime > S[n].mtime`: never occurs naturally (don't care)
422 /// - `S[n-1].ctime > S[n].ctime`: never occurs naturally (don't care)
423 ///
424 /// Case (*2) above means that a file was changed twice or more at
425 /// same time in sec (= `S[n-1].ctime`), and comparison of timestamp
426 /// is ambiguous.
427 ///
428 /// Base idea to avoid such ambiguity is "advance mtime 1 sec, if
429 /// timestamp is ambiguous".
430 ///
431 /// But advancing mtime only in case (*2) doesn't work as
432 /// expected, because naturally advanced `S[n].mtime` in case (*1)
433 /// might be equal to manually advanced `S[n-1 or earlier].mtime`.
434 ///
435 /// Therefore, all `S[n-1].ctime == S[n].ctime` cases should be
436 /// treated as ambiguous regardless of mtime, to avoid overlooking
437 /// by confliction between such mtime.
438 ///
439 /// Advancing mtime `if isambig(new, old)` ensures `S[n-1].mtime !=
440 /// S[n].mtime`, even if size of a file isn't changed.
441 pub fn is_filetime_ambiguous(new: &Metadata, old: &Metadata) -> bool {
442 new.ctime() == old.ctime()
443 }
444
445 /// Writable file object that atomically updates a file
446 ///
447 /// All writes will go to a temporary copy of the original file. Call
448 /// [`Self::close`] when you are done writing, and [`Self`] will rename
449 /// the temporary copy to the original name, making the changes
450 /// visible. If the object is destroyed without being closed, all your
451 /// writes are discarded.
452 #[derive(Debug)]
453 pub struct AtomicFile {
454 /// The temporary file to write to
455 fp: std::fs::File,
456 /// Path of the temp file
457 temp_path: PathBuf,
458 /// Used when stat'ing the file, is useful only if the target file is
459 /// guarded by any lock (e.g. repo.lock or repo.wlock).
460 check_ambig: bool,
461 /// Path of the target file
462 target_name: PathBuf,
463 /// Whether the file is open or not
464 is_open: bool,
465 }
466
467 impl AtomicFile {
468 pub fn new(
469 target_path: impl AsRef<Path>,
470 empty: bool,
471 check_ambig: bool,
472 ) -> Result<Self, HgError> {
473 let target_path = target_path.as_ref().to_owned();
474
475 let random_id = Alphanumeric.sample_string(&mut rand::rng(), 12);
476 let filename = target_path.file_name().expect("target has no filename");
477 let filename = get_bytes_from_path(filename);
478 let temp_filename =
479 format_bytes!(b".{}-{}~", filename, random_id.as_bytes());
480 let temp_path =
481 target_path.with_file_name(get_path_from_bytes(&temp_filename));
482
483 if !empty {
484 std::fs::copy(&target_path, &temp_path)
485 .with_context(|| IoErrorContext::CopyingFile {
486 from: target_path.to_owned(),
487 to: temp_path.to_owned(),
488 })
489 // If it doesn't exist, create it on open
490 .io_not_found_as_none()?;
491 }
492 let fp = std::fs::OpenOptions::new()
493 .write(true)
494 .create(true)
495 .truncate(empty)
496 .open(&temp_path)
497 .when_writing_file(&temp_path)?;
498
499 Ok(Self {
500 fp,
501 temp_path,
502 check_ambig,
503 target_name: target_path,
504 is_open: true,
505 })
506 }
507
508 pub fn from_file(
509 fp: std::fs::File,
510 check_ambig: bool,
511 temp_name: PathBuf,
512 target_name: PathBuf,
513 ) -> Self {
514 Self {
515 fp,
516 check_ambig,
517 temp_path: temp_name,
518 target_name,
519 is_open: true,
520 }
521 }
522
523 /// Write `buf` to the temporary file
524 pub fn write_all(&mut self, buf: &[u8]) -> Result<(), std::io::Error> {
525 self.fp.write_all(buf)
526 }
527
528 fn target(&self) -> PathBuf {
529 self.temp_path
530 .parent()
531 .expect("should not be at the filesystem root")
532 .join(&self.target_name)
533 }
534
535 /// Close the temporary file and rename to the target
536 pub fn close(mut self) -> Result<(), std::io::Error> {
537 self.fp.flush()?;
538 let target = self.target();
539 if self.check_ambig {
540 if let Ok(stat) = target.metadata() {
541 std::fs::rename(&self.temp_path, &target)?;
542 avoid_timestamp_ambiguity(&target, &stat);
543 } else {
544 std::fs::rename(&self.temp_path, target)?;
545 }
546 } else {
547 std::fs::rename(&self.temp_path, target)?;
548 }
549 self.is_open = false;
550 Ok(())
551 }
552 }
553
554 impl Seek for AtomicFile {
555 fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
556 self.fp.seek(pos)
557 }
558 }
559
560 impl Drop for AtomicFile {
561 fn drop(&mut self) {
562 if self.is_open {
563 std::fs::remove_file(&self.temp_path).ok();
564 }
565 }
566 }
567
568 /// Abstracts over the VFS to allow for different implementations of the
569 /// filesystem layer (like passing one from Python).
570 pub trait Vfs: Sync + Send + DynClone {
571 /// Open a [`VfsFile::Normal`] for reading the file at `filename`,
572 /// relative to this VFS's root.
573 fn open(&self, filename: &Path) -> Result<VfsFile, HgError>;
574 /// Open a [`VfsFile::Normal`] for writing and reading the file at
575 /// `filename`, relative to this VFS's root.
576 fn open_write(&self, filename: &Path) -> Result<VfsFile, HgError>;
577 /// Open a [`VfsFile::Normal`] for reading and writing the file at
578 /// `filename`, relative to this VFS's root. This file will be checked
579 /// for an ambiguous mtime on [`drop`]. See [`is_filetime_ambiguous`].
580 fn open_check_ambig(&self, filename: &Path) -> Result<VfsFile, HgError>;
581 /// Create a [`VfsFile::Normal`] for reading and writing the file at
582 /// `filename`, relative to this VFS's root. If the file already exists,
583 /// it will be truncated to 0 bytes.
584 fn create(
585 &self,
586 filename: &Path,
587 check_ambig: bool,
588 ) -> Result<VfsFile, HgError>;
589 /// Create a [`VfsFile::Atomic`] for reading and writing the file at
590 /// `filename`, relative to this VFS's root. If the file already exists,
591 /// it will be truncated to 0 bytes.
592 fn create_atomic(
593 &self,
594 filename: &Path,
595 check_ambig: bool,
596 ) -> Result<VfsFile, HgError>;
597 /// Return the total file size in bytes of the open `file`. Errors are
598 /// usual IO errors (invalid file handle, permissions, etc.)
599 fn file_size(&self, file: &VfsFile) -> Result<u64, HgError>;
600 /// Return `true` if `filename` exists relative to this VFS's root. Errors
601 /// will coerce to `false`, to this also returns `false` if there are
602 /// IO problems. This is fine because any operation that actually tries
603 /// to do anything with this path will get the same error.
604 fn exists(&self, filename: &Path) -> bool;
605 /// Remove the file at `filename` relative to this VFS's root. Errors
606 /// are the usual IO errors (lacking permission, file does not exist, etc.)
607 fn unlink(&self, filename: &Path) -> Result<(), HgError>;
608 /// Rename the file `from` to `to`, both relative to this VFS's root.
609 /// Errors are the usual IO errors (lacking permission, file does not
610 /// exist, etc.). If `check_ambig` is `true`, the VFS will check for an
611 /// ambiguous mtime on rename. See [`is_filetime_ambiguous`].
612 fn rename(
613 &self,
614 from: &Path,
615 to: &Path,
616 check_ambig: bool,
617 ) -> Result<(), HgError>;
618 /// Rename the file `from` to `to`, both relative to this VFS's root.
619 /// Errors are the usual IO errors (lacking permission, file does not
620 /// exist, etc.). If `check_ambig` is passed, the VFS will check for an
621 /// ambiguous mtime on rename. See [`is_filetime_ambiguous`].
622 fn copy(&self, from: &Path, to: &Path) -> Result<(), HgError>;
623 /// Returns the absolute root path of this VFS, relative to which all
624 /// operations are done.
625 fn base(&self) -> &Path;
626 }
627
628 /// These methods will need to be implemented once `rhg` (and other) non-Python
629 /// users of `hg-core` start doing more on their own, like writing to files.
630 impl Vfs for VfsImpl {
631 fn open(&self, filename: &Path) -> Result<VfsFile, HgError> {
632 // TODO auditpath
633 let path = self.base.join(filename);
634 Ok(VfsFile::normal(
635 std::fs::File::open(&path).when_reading_file(&path)?,
636 filename.to_owned(),
637 ))
638 }
639
640 fn open_write(&self, filename: &Path) -> Result<VfsFile, HgError> {
641 if self.readonly {
642 return Err(HgError::abort(
643 "write access in a readonly vfs",
644 exit_codes::ABORT,
645 None,
646 ));
647 }
648 // TODO auditpath
649 let path = self.base.join(filename);
650 copy_in_place_if_hardlink(&path)?;
651
652 Ok(VfsFile::normal(
653 OpenOptions::new()
654 .create(false)
655 .create_new(false)
656 .write(true)
657 .read(true)
658 .open(&path)
659 .when_writing_file(&path)?,
660 path.to_owned(),
661 ))
662 }
663
664 fn open_check_ambig(&self, filename: &Path) -> Result<VfsFile, HgError> {
665 if self.readonly {
666 return Err(HgError::abort(
667 "write access in a readonly vfs",
668 exit_codes::ABORT,
669 None,
670 ));
671 }
672
673 let path = self.base.join(filename);
674 copy_in_place_if_hardlink(&path)?;
675
676 // TODO auditpath
677 VfsFile::normal_check_ambig(
678 OpenOptions::new()
679 .write(true)
680 .read(true) // Can be used for reading to save on `open` calls
681 .create(false)
682 .open(&path)
683 .when_reading_file(&path)?,
684 path.to_owned(),
685 )
686 }
687
688 fn create(
689 &self,
690 filename: &Path,
691 check_ambig: bool,
692 ) -> Result<VfsFile, HgError> {
693 if self.readonly {
694 return Err(HgError::abort(
695 "write access in a readonly vfs",
696 exit_codes::ABORT,
697 None,
698 ));
699 }
700 // TODO auditpath
701 let path = self.base.join(filename);
702 let parent = path.parent().expect("file at root");
703 std::fs::create_dir_all(parent).when_writing_file(parent)?;
704 // This avoids permission errors if the file somehow already exists
705 // Let it fail: either it didn't exist (good), or we really don't have
706 // the rights to do anything about this file, let `open` fail.
707 std::fs::remove_file(&path)
708 .when_writing_file(&path)
709 .io_not_found_as_none()?;
710
711 let file = OpenOptions::new()
712 .create(true)
713 .truncate(true)
714 .write(true)
715 .read(true)
716 .open(&path)
717 .when_writing_file(&path)?;
718
719 if let Some(mode) = self.mode {
720 // Creating the file with the right permission (with `.mode()`)
721 // may not work since umask takes effect for file creation.
722 // So we need to fix the permission after creating the file.
723 // TODO figure out a performant way of doing this, as this
724 // introduces contention and a lot of folders are in common.
725 fix_directory_permissions(&self.base, &path, mode)?;
726 let perm = std::fs::Permissions::from_mode(mode & 0o666);
727 std::fs::set_permissions(&path, perm).when_writing_file(&path)?;
728 }
729
730 Ok(VfsFile::Normal {
731 file,
732 check_ambig: if check_ambig {
733 Some(path.metadata().when_reading_file(&path)?)
734 } else {
735 None
736 },
737 path: path.to_owned(),
738 })
739 }
740
741 fn create_atomic(
742 &self,
743 _filename: &Path,
744 _check_ambig: bool,
745 ) -> Result<VfsFile, HgError> {
746 todo!()
747 }
748
749 fn file_size(&self, file: &VfsFile) -> Result<u64, HgError> {
750 Ok(file
751 .metadata()
752 .map_err(|e| {
753 HgError::abort(
754 format!("Could not get file metadata: {}", e),
755 exit_codes::ABORT,
756 None,
757 )
758 })?
759 .size())
760 }
761
762 fn exists(&self, filename: &Path) -> bool {
763 self.base.join(filename).exists()
764 }
765
766 fn unlink(&self, filename: &Path) -> Result<(), HgError> {
767 if self.readonly {
768 return Err(HgError::abort(
769 "write access in a readonly vfs",
770 exit_codes::ABORT,
771 None,
772 ));
773 }
774 let path = self.base.join(filename);
775 std::fs::remove_file(&path)
776 .with_context(|| IoErrorContext::RemovingFile(path))
777 }
778
779 fn rename(
780 &self,
781 from: &Path,
782 to: &Path,
783 check_ambig: bool,
784 ) -> Result<(), HgError> {
785 if self.readonly {
786 return Err(HgError::abort(
787 "write access in a readonly vfs",
788 exit_codes::ABORT,
789 None,
790 ));
791 }
792 let old_stat = if check_ambig {
793 Some(
794 from.metadata()
795 .when_reading_file(from)
796 .io_not_found_as_none()?,
797 )
798 } else {
799 None
800 };
801 let from = self.base.join(from);
802 let to = self.base.join(to);
803 std::fs::rename(&from, &to).with_context(|| {
804 IoErrorContext::RenamingFile { from, to: to.to_owned() }
805 })?;
806 if let Some(Some(old)) = old_stat {
807 avoid_timestamp_ambiguity(&to, &old);
808 }
809 Ok(())
810 }
811
812 fn copy(&self, from: &Path, to: &Path) -> Result<(), HgError> {
813 let from = self.base.join(from);
814 let to = self.base.join(to);
815 std::fs::copy(&from, &to)
816 .with_context(|| IoErrorContext::CopyingFile { from, to })
817 .map(|_| ())
818 }
819
820 fn base(&self) -> &Path {
821 &self.base
822 }
823 }
824
825 fn fix_directory_permissions(
826 base: &Path,
827 path: &Path,
828 mode: u32,
829 ) -> Result<(), HgError> {
830 let mut ancestors = path.ancestors();
831 ancestors.next(); // yields the path itself
832
833 for ancestor in ancestors {
834 if ancestor == base {
835 break;
836 }
837 let perm = std::fs::Permissions::from_mode(mode);
838 std::fs::set_permissions(ancestor, perm).when_writing_file(ancestor)?;
839 }
840 Ok(())
841 }
842
843 /// A VFS that understands file encoding
844 ///
845 /// TODO Only works when using from Python for now.
846 pub struct EncodedVfs {
847 inner: VfsImpl,
848 }
849
850 impl Clone for EncodedVfs {
851 fn clone(&self) -> Self {
852 Self { inner: self.inner.clone() }
853 }
854 }
855
856 impl EncodedVfs {
857 pub fn new(base: PathBuf, readonly: bool, encoding: PathEncoding) -> Self {
858 let inner = VfsImpl::new(base, readonly, encoding);
859 Self { inner }
860 }
861 }
862
863 impl Vfs for EncodedVfs {
864 fn open(&self, filename: &Path) -> Result<VfsFile, HgError> {
865 let encoded =
866 path_encode(&get_bytes_from_path(filename), self.inner.encoding);
867 let filename = get_path_from_bytes(&encoded);
868 self.inner.open(filename)
869 }
870
871 fn open_write(&self, filename: &Path) -> Result<VfsFile, HgError> {
872 let encoded =
873 path_encode(&get_bytes_from_path(filename), self.inner.encoding);
874 let encoded_path = get_path_from_bytes(&encoded);
875 self.inner.open_write(encoded_path)
876 }
877
878 fn open_check_ambig(&self, filename: &Path) -> Result<VfsFile, HgError> {
879 let encoded =
880 path_encode(&get_bytes_from_path(filename), self.inner.encoding);
881 let filename = get_path_from_bytes(&encoded);
882 self.inner.open_check_ambig(filename)
883 }
884
885 fn create(
886 &self,
887 filename: &Path,
888 check_ambig: bool,
889 ) -> Result<VfsFile, HgError> {
890 let encoded =
891 path_encode(&get_bytes_from_path(filename), self.inner.encoding);
892 let encoded_path = get_path_from_bytes(&encoded);
893 self.inner.create(encoded_path, check_ambig)
894 }
895
896 fn create_atomic(
897 &self,
898 filename: &Path,
899 check_ambig: bool,
900 ) -> Result<VfsFile, HgError> {
901 let encoded =
902 path_encode(&get_bytes_from_path(filename), self.inner.encoding);
903 let filename = get_path_from_bytes(&encoded);
904 self.inner.create_atomic(filename, check_ambig)
905 }
906
907 fn file_size(&self, file: &VfsFile) -> Result<u64, HgError> {
908 self.inner.file_size(file)
909 }
910
911 fn exists(&self, filename: &Path) -> bool {
912 let encoded =
913 path_encode(&get_bytes_from_path(filename), self.inner.encoding);
914 let filename = get_path_from_bytes(&encoded);
915 self.inner.exists(filename)
916 }
917
918 fn unlink(&self, filename: &Path) -> Result<(), HgError> {
919 let encoded =
920 path_encode(&get_bytes_from_path(filename), self.inner.encoding);
921 let filename = get_path_from_bytes(&encoded);
922 self.inner.unlink(filename)
923 }
924
925 fn rename(
926 &self,
927 from: &Path,
928 to: &Path,
929 check_ambig: bool,
930 ) -> Result<(), HgError> {
931 let encoded =
932 path_encode(&get_bytes_from_path(from), self.inner.encoding);
933 let from = get_path_from_bytes(&encoded);
934 let encoded =
935 path_encode(&get_bytes_from_path(to), self.inner.encoding);
936 let to = get_path_from_bytes(&encoded);
937 self.inner.rename(from, to, check_ambig)
938 }
939
940 fn copy(&self, from: &Path, to: &Path) -> Result<(), HgError> {
941 let encoded =
942 path_encode(&get_bytes_from_path(from), self.inner.encoding);
943 let from = get_path_from_bytes(&encoded);
944 let encoded =
945 path_encode(&get_bytes_from_path(to), self.inner.encoding);
946 let to = get_path_from_bytes(&encoded);
947 self.inner.copy(from, to)
948 }
949 fn base(&self) -> &Path {
950 self.inner.base()
951 }
952 }
953
954 /// Detects whether `path` is a hardlink and does a tmp copy + rename erase
955 /// to turn it into its own file. Revlogs are usually hardlinked when doing
956 /// a local clone, and we don't want to modify the original repo.
957 fn copy_in_place_if_hardlink(path: &Path) -> Result<(), HgError> {
958 let metadata = path.metadata().when_writing_file(path)?;
959 if metadata.nlink() > 1 {
960 // If it's hardlinked, copy it and rename it back before changing it.
961 let tmpdir = path.parent().expect("file at root");
962 let name = Alphanumeric.sample_string(&mut rand::rng(), 16);
963 let tmpfile = tmpdir.join(name);
964 std::fs::create_dir_all(tmpfile.parent().expect("file at root"))
965 .with_context(|| IoErrorContext::CopyingFile {
966 from: path.to_owned(),
967 to: tmpfile.to_owned(),
968 })?;
969 std::fs::copy(path, &tmpfile).with_context(|| {
970 IoErrorContext::CopyingFile {
971 from: path.to_owned(),
972 to: tmpfile.to_owned(),
973 }
974 })?;
975 std::fs::rename(&tmpfile, path).with_context(|| {
976 IoErrorContext::RenamingFile { from: tmpfile, to: path.to_owned() }
977 })?;
978 }
979 Ok(())
980 }
981
982 pub fn is_revlog_file(path: impl AsRef<Path>) -> bool {
983 path.as_ref()
984 .extension()
985 .map(|ext| {
986 ["i", "idx", "d", "dat", "n", "nd", "sda"]
987 .contains(&ext.to_string_lossy().as_ref())
988 })
989 .unwrap_or(false)
990 }
991
992 pub(crate) fn is_dir(path: impl AsRef<Path>) -> Result<bool, HgError> {
993 Ok(fs_metadata(path)?.is_some_and(|meta| meta.is_dir()))
994 }
995
996 pub(crate) fn is_file(path: impl AsRef<Path>) -> Result<bool, HgError> {
997 Ok(fs_metadata(path)?.is_some_and(|meta| meta.is_file()))
998 }
999
1000 /// Returns whether the given `path` is on a network file system.
1001 /// Taken from `cargo`'s codebase.
1002 #[cfg(target_os = "linux")]
1003 pub(crate) fn is_on_nfs_mount(path: impl AsRef<Path>) -> bool {
1004 use std::ffi::CString;
1005 use std::mem;
1006 use std::os::unix::prelude::*;
1007
1008 let path = match CString::new(path.as_ref().as_os_str().as_bytes()) {
1009 Ok(path) => path,
1010 Err(_) => return false,
1011 };
1012
1013 unsafe {
1014 let mut buf: libc::statfs = mem::zeroed();
1015 let r = libc::statfs(path.as_ptr(), &mut buf);
1016
1017 r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
1018 }
1019 }
1020
1021 /// Similar to what Cargo does; although detecting NFS (or non-local
1022 /// file systems) _should_ be possible on other operating systems,
1023 /// we'll just assume that mmap() works there, for now; after all,
1024 /// _some_ functionality is better than a compile error, i.e. none at
1025 /// all
1026 #[cfg(not(target_os = "linux"))]
1027 pub(crate) fn is_on_nfs_mount(_path: impl AsRef<Path>) -> bool {
1028 false
1029 }
1030
1031 #[cfg(test)]
1032 mod tests {
1033 use super::*;
1034
1035 #[test]
1036 fn test_atomic_file() {
1037 let dir = tempfile::tempdir().unwrap().into_path();
1038 let target_path = dir.join("sometargetname");
1039
1040 for empty in [true, false] {
1041 let file = AtomicFile::new(&target_path, empty, false).unwrap();
1042 assert!(file.is_open);
1043 let filename =
1044 file.temp_path.file_name().unwrap().to_str().unwrap();
1045 // Make sure we have a coherent temp name
1046 assert_eq!(filename.len(), 29, "{}", filename);
1047 assert!(filename.contains("sometargetname"));
1048
1049 // Make sure the temp file is created in the same folder
1050 assert_eq!(target_path.parent(), file.temp_path.parent());
1051 }
1052
1053 assert!(!target_path.exists());
1054 std::fs::write(&target_path, "version 1").unwrap();
1055 let mut file = AtomicFile::new(&target_path, false, false).unwrap();
1056 file.write_all(b"version 2!").unwrap();
1057 assert_eq!(std::fs::read(&target_path).unwrap(), b"version 1".to_vec());
1058 let temp_path = file.temp_path.to_owned();
1059 // test that dropping the file should discard the temp file and not
1060 // affect the target path.
1061 drop(file);
1062 assert_eq!(std::fs::read(&target_path).unwrap(), b"version 1".to_vec());
1063 assert!(!temp_path.exists());
1064
1065 let mut file = AtomicFile::new(&target_path, false, false).unwrap();
1066 file.write_all(b"version 2!").unwrap();
1067 assert_eq!(std::fs::read(&target_path).unwrap(), b"version 1".to_vec());
1068 file.close().unwrap();
1069 assert_eq!(
1070 std::fs::read(&target_path).unwrap(),
1071 b"version 2!".to_vec(),
1072 "{}",
1073 std::fs::read_to_string(&target_path).unwrap()
1074 );
1075 assert!(target_path.exists());
1076 assert!(!temp_path.exists());
1077 }
1078
1079 #[test]
1080 fn test_vfs_file_check_ambig() {
1081 let dir = tempfile::tempdir().unwrap().into_path();
1082 let file_path = dir.join("file");
1083
1084 fn vfs_file_write(file_path: &Path, check_ambig: bool) {
1085 let file = std::fs::OpenOptions::new()
1086 .write(true)
1087 .open(file_path)
1088 .unwrap();
1089 let old_stat = if check_ambig {
1090 Some(file.metadata().unwrap())
1091 } else {
1092 None
1093 };
1094
1095 let mut vfs_file = VfsFile::Normal {
1096 file,
1097 path: file_path.to_owned(),
1098 check_ambig: old_stat,
1099 };
1100 vfs_file.write_all(b"contents").unwrap();
1101 }
1102
1103 std::fs::OpenOptions::new()
1104 .write(true)
1105 .create(true)
1106 .truncate(false)
1107 .open(&file_path)
1108 .unwrap();
1109
1110 let number_of_writes = 3;
1111
1112 // Try multiple times, because reproduction of an ambiguity depends
1113 // on "filesystem time"
1114 for _ in 0..5 {
1115 TIMESTAMP_FIXES_CALLS.store(0, Ordering::Relaxed);
1116 vfs_file_write(&file_path, false);
1117 let old_stat = file_path.metadata().unwrap();
1118 if old_stat.ctime() != old_stat.mtime() {
1119 // subsequent changing never causes ambiguity
1120 continue;
1121 }
1122
1123 // Repeat atomic write with `check_ambig == true`, to examine
1124 // whether the mtime is advanced multiple times as expected
1125 for _ in 0..number_of_writes {
1126 vfs_file_write(&file_path, true);
1127 }
1128 let new_stat = file_path.metadata().unwrap();
1129 if !is_filetime_ambiguous(&new_stat, &old_stat) {
1130 // timestamp ambiguity was naturally avoided while repetition
1131 continue;
1132 }
1133
1134 assert_eq!(
1135 TIMESTAMP_FIXES_CALLS.load(Ordering::Relaxed),
1136 number_of_writes
1137 );
1138 assert_eq!(
1139 old_stat.mtime() + number_of_writes as i64,
1140 file_path.metadata().unwrap().mtime()
1141 );
1142 break;
1143 }
1144 // If we've arrived here without breaking, we might not have
1145 // tested anything because the platform is too slow. This test will
1146 // still work on fast platforms.
1147 }
1148 }