Skip to main content

cargo_util/
paths.rs

1//! Various utilities for working with files and paths.
2
3use anyhow::{Context, Result};
4use filetime::FileTime;
5use std::env;
6use std::ffi::{OsStr, OsString};
7use std::fs::{self, File, Metadata, OpenOptions};
8use std::io;
9use std::io::prelude::*;
10use std::iter;
11use std::path::{Component, Path, PathBuf};
12use tempfile::Builder as TempFileBuilder;
13
14/// Joins paths into a string suitable for the `PATH` environment variable.
15///
16/// This is equivalent to [`std::env::join_paths`], but includes a more
17/// detailed error message. The given `env` argument is the name of the
18/// environment variable this is will be used for, which is included in the
19/// error message.
20pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> Result<OsString> {
21    env::join_paths(paths.iter()).with_context(|| {
22        let mut message = format!(
23            "failed to join paths from `${env}` together\n\n\
24             Check if any of path segments listed below contain an \
25             unterminated quote character or path separator:"
26        );
27        for path in paths {
28            use std::fmt::Write;
29            write!(&mut message, "\n    {:?}", Path::new(path)).unwrap();
30        }
31
32        message
33    })
34}
35
36/// Returns the name of the environment variable used for searching for
37/// dynamic libraries.
38pub fn dylib_path_envvar() -> &'static str {
39    if cfg!(windows) {
40        "PATH"
41    } else if cfg!(target_os = "macos") {
42        // When loading and linking a dynamic library or bundle, dlopen
43        // searches in LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PWD, and
44        // DYLD_FALLBACK_LIBRARY_PATH.
45        // In the Mach-O format, a dynamic library has an "install path."
46        // Clients linking against the library record this path, and the
47        // dynamic linker, dyld, uses it to locate the library.
48        // dyld searches DYLD_LIBRARY_PATH *before* the install path.
49        // dyld searches DYLD_FALLBACK_LIBRARY_PATH only if it cannot
50        // find the library in the install path.
51        // Setting DYLD_LIBRARY_PATH can easily have unintended
52        // consequences.
53        //
54        // Also, DYLD_LIBRARY_PATH appears to have significant performance
55        // penalty starting in 10.13. Cargo's testsuite ran more than twice as
56        // slow with it on CI.
57        "DYLD_FALLBACK_LIBRARY_PATH"
58    } else if cfg!(target_os = "aix") {
59        "LIBPATH"
60    } else if cfg!(target_os = "haiku") {
61        "LIBRARY_PATH"
62    } else {
63        "LD_LIBRARY_PATH"
64    }
65}
66
67/// Returns a list of directories that are searched for dynamic libraries.
68///
69/// Note that some operating systems will have defaults if this is empty that
70/// will need to be dealt with.
71pub fn dylib_path() -> Vec<PathBuf> {
72    match env::var_os(dylib_path_envvar()) {
73        Some(var) => env::split_paths(&var).collect(),
74        None => Vec::new(),
75    }
76}
77
78/// Normalize a path, removing things like `.` and `..`.
79///
80/// CAUTION: This does not resolve symlinks (unlike
81/// [`std::fs::canonicalize`]). This may cause incorrect or surprising
82/// behavior at times. This should be used carefully. Unfortunately,
83/// [`std::fs::canonicalize`] can be hard to use correctly, since it can often
84/// fail, or on Windows returns annoying device paths. This is a problem Cargo
85/// needs to improve on.
86pub fn normalize_path(path: &Path) -> PathBuf {
87    let mut components = path.components().peekable();
88    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
89        components.next();
90        PathBuf::from(c.as_os_str())
91    } else {
92        PathBuf::new()
93    };
94
95    for component in components {
96        match component {
97            Component::Prefix(..) => unreachable!(),
98            Component::RootDir => {
99                ret.push(Component::RootDir);
100            }
101            Component::CurDir => {}
102            Component::ParentDir => {
103                if ret.ends_with(Component::ParentDir) {
104                    ret.push(Component::ParentDir);
105                } else {
106                    let popped = ret.pop();
107                    if !popped && !ret.has_root() {
108                        ret.push(Component::ParentDir);
109                    }
110                }
111            }
112            Component::Normal(c) => {
113                ret.push(c);
114            }
115        }
116    }
117    ret
118}
119
120/// Returns the absolute path of where the given executable is located based
121/// on searching the `PATH` environment variable.
122///
123/// Returns an error if it cannot be found.
124pub fn resolve_executable(exec: &Path) -> Result<PathBuf> {
125    if exec.components().count() == 1 {
126        let paths = env::var_os("PATH").ok_or_else(|| anyhow::format_err!("no PATH"))?;
127        let candidates = env::split_paths(&paths).flat_map(|path| {
128            let candidate = path.join(&exec);
129            let with_exe = if env::consts::EXE_EXTENSION.is_empty() {
130                None
131            } else {
132                Some(candidate.with_extension(env::consts::EXE_EXTENSION))
133            };
134            iter::once(candidate).chain(with_exe)
135        });
136        for candidate in candidates {
137            if candidate.is_file() {
138                return Ok(candidate);
139            }
140        }
141
142        anyhow::bail!("no executable for `{}` found in PATH", exec.display())
143    } else {
144        Ok(exec.into())
145    }
146}
147
148/// Returns metadata for a file (follows symlinks).
149///
150/// Equivalent to [`std::fs::metadata`] with better error messages.
151pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
152    let path = path.as_ref();
153    std::fs::metadata(path)
154        .with_context(|| format!("failed to load metadata for path `{}`", path.display()))
155}
156
157/// Returns metadata for a file without following symlinks.
158///
159/// Equivalent to [`std::fs::metadata`] with better error messages.
160pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
161    let path = path.as_ref();
162    std::fs::symlink_metadata(path)
163        .with_context(|| format!("failed to load metadata for path `{}`", path.display()))
164}
165
166/// Reads a file to a string.
167///
168/// Equivalent to [`std::fs::read_to_string`] with better error messages.
169pub fn read(path: &Path) -> Result<String> {
170    match String::from_utf8(read_bytes(path)?) {
171        Ok(s) => Ok(s),
172        Err(_) => anyhow::bail!("path at `{}` was not valid utf-8", path.display()),
173    }
174}
175
176/// Reads a file into a bytes vector.
177///
178/// Equivalent to [`std::fs::read`] with better error messages.
179pub fn read_bytes(path: &Path) -> Result<Vec<u8>> {
180    fs::read(path).with_context(|| format!("failed to read `{}`", path.display()))
181}
182
183/// Writes a file to disk.
184///
185/// Equivalent to [`std::fs::write`] with better error messages.
186pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
187    let path = path.as_ref();
188    fs::write(path, contents.as_ref())
189        .with_context(|| format!("failed to write `{}`", path.display()))
190}
191
192/// Writes a file to disk atomically.
193///
194/// This uses `tempfile::persist` to accomplish atomic writes.
195/// If the path is a symlink, it will follow the symlink and write to the actual target.
196pub fn write_atomic<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
197    let path = path.as_ref();
198
199    // Check if the path is a symlink and follow it if it is
200    let resolved_path;
201    let path = if path.is_symlink() {
202        let target = fs::read_link(path)
203            .with_context(|| format!("failed to read symlink at `{}`", path.display()))?;
204        resolved_path = path.parent().unwrap().join(target);
205        &resolved_path
206    } else {
207        path
208    };
209
210    // On unix platforms, get the permissions of the original file. Copy only the user/group/other
211    // read/write/execute permission bits. The tempfile lib defaults to an initial mode of 0o600,
212    // and we'll set the proper permissions after creating the file.
213    #[cfg(unix)]
214    let perms = path.metadata().ok().map(|meta| {
215        use std::os::unix::fs::PermissionsExt;
216
217        // these constants are u16 on macOS and i32 on Redox
218        let mask = (libc::S_IRWXU | libc::S_IRWXG | libc::S_IRWXO) as u32;
219        let mode = meta.permissions().mode() & mask;
220
221        std::fs::Permissions::from_mode(mode)
222    });
223
224    let mut tmp = TempFileBuilder::new()
225        .prefix(path.file_name().unwrap())
226        .tempfile_in(path.parent().unwrap())?;
227    tmp.write_all(contents.as_ref())?;
228
229    // On unix platforms, set the permissions on the newly created file. We can use fchmod (called
230    // by the std lib; subject to change) which ignores the umask so that the new file has the same
231    // permissions as the old file.
232    #[cfg(unix)]
233    if let Some(perms) = perms {
234        tmp.as_file().set_permissions(perms)?;
235    }
236
237    tmp.persist(path)?;
238    Ok(())
239}
240
241/// Equivalent to [`write()`], but does not write anything if the file contents
242/// are identical to the given contents.
243pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
244    (|| -> Result<()> {
245        let contents = contents.as_ref();
246        let mut f = OpenOptions::new()
247            .read(true)
248            .write(true)
249            .create(true)
250            .open(&path)?;
251        let mut orig = Vec::new();
252        f.read_to_end(&mut orig)?;
253        if orig != contents {
254            f.set_len(0)?;
255            f.seek(io::SeekFrom::Start(0))?;
256            f.write_all(contents)?;
257        }
258        Ok(())
259    })()
260    .with_context(|| format!("failed to write `{}`", path.as_ref().display()))?;
261    Ok(())
262}
263
264/// Equivalent to [`write()`], but appends to the end instead of replacing the
265/// contents.
266pub fn append(path: &Path, contents: &[u8]) -> Result<()> {
267    (|| -> Result<()> {
268        let mut f = OpenOptions::new()
269            .write(true)
270            .append(true)
271            .create(true)
272            .open(path)?;
273
274        f.write_all(contents)?;
275        Ok(())
276    })()
277    .with_context(|| format!("failed to write `{}`", path.display()))?;
278    Ok(())
279}
280
281/// Creates a new file.
282pub fn create<P: AsRef<Path>>(path: P) -> Result<File> {
283    let path = path.as_ref();
284    File::create(path).with_context(|| format!("failed to create file `{}`", path.display()))
285}
286
287/// Opens an existing file.
288pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
289    let path = path.as_ref();
290    File::open(path).with_context(|| format!("failed to open file `{}`", path.display()))
291}
292
293/// Returns the last modification time of a file.
294pub fn mtime(path: &Path) -> Result<FileTime> {
295    let meta = metadata(path)?;
296    Ok(FileTime::from_last_modification_time(&meta))
297}
298
299/// Returns the maximum mtime of the given path, recursing into
300/// subdirectories, and following symlinks.
301pub fn mtime_recursive(path: &Path) -> Result<FileTime> {
302    let meta = metadata(path)?;
303    if !meta.is_dir() {
304        return Ok(FileTime::from_last_modification_time(&meta));
305    }
306    let max_meta = walkdir::WalkDir::new(path)
307        .follow_links(true)
308        .into_iter()
309        .filter_map(|e| match e {
310            Ok(e) => Some(e),
311            Err(e) => {
312                // Ignore errors while walking. If Cargo can't access it, the
313                // build script probably can't access it, either.
314                tracing::debug!("failed to determine mtime while walking directory: {}", e);
315                None
316            }
317        })
318        .filter_map(|e| {
319            if e.path_is_symlink() {
320                // Use the mtime of both the symlink and its target, to
321                // handle the case where the symlink is modified to a
322                // different target.
323                let sym_meta = match std::fs::symlink_metadata(e.path()) {
324                    Ok(m) => m,
325                    Err(err) => {
326                        // I'm not sure when this is really possible (maybe a
327                        // race with unlinking?). Regardless, if Cargo can't
328                        // read it, the build script probably can't either.
329                        tracing::debug!(
330                            "failed to determine mtime while fetching symlink metadata of {}: {}",
331                            e.path().display(),
332                            err
333                        );
334                        return None;
335                    }
336                };
337                let sym_mtime = FileTime::from_last_modification_time(&sym_meta);
338                // Walkdir follows symlinks.
339                match e.metadata() {
340                    Ok(target_meta) => {
341                        let target_mtime = FileTime::from_last_modification_time(&target_meta);
342                        Some(sym_mtime.max(target_mtime))
343                    }
344                    Err(err) => {
345                        // Can't access the symlink target. If Cargo can't
346                        // access it, the build script probably can't access
347                        // it either.
348                        tracing::debug!(
349                            "failed to determine mtime of symlink target for {}: {}",
350                            e.path().display(),
351                            err
352                        );
353                        Some(sym_mtime)
354                    }
355                }
356            } else {
357                let meta = match e.metadata() {
358                    Ok(m) => m,
359                    Err(err) => {
360                        // I'm not sure when this is really possible (maybe a
361                        // race with unlinking?). Regardless, if Cargo can't
362                        // read it, the build script probably can't either.
363                        tracing::debug!(
364                            "failed to determine mtime while fetching metadata of {}: {}",
365                            e.path().display(),
366                            err
367                        );
368                        return None;
369                    }
370                };
371                Some(FileTime::from_last_modification_time(&meta))
372            }
373        })
374        .max()
375        // or_else handles the case where there are no files in the directory.
376        .unwrap_or_else(|| FileTime::from_last_modification_time(&meta));
377    Ok(max_meta)
378}
379
380/// Record the current time on the filesystem (using the filesystem's clock)
381/// using the given file. Returns the current time.
382pub fn set_invocation_time(timestamp: &Path) -> Result<FileTime> {
383    // note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient,
384    // then this can be removed.
385    write(
386        &timestamp,
387        "This file has an mtime of when this was started.",
388    )?;
389    let ft = mtime(&timestamp)?;
390    tracing::debug!("invocation time for {:?} is {}", timestamp, ft);
391    Ok(ft)
392}
393
394/// Converts a path to UTF-8 bytes.
395pub fn path2bytes(path: &Path) -> Result<&[u8]> {
396    #[cfg(unix)]
397    {
398        use std::os::unix::prelude::*;
399        Ok(path.as_os_str().as_bytes())
400    }
401    #[cfg(windows)]
402    {
403        match path.as_os_str().to_str() {
404            Some(s) => Ok(s.as_bytes()),
405            None => Err(anyhow::format_err!(
406                "invalid non-unicode path: {}",
407                path.display()
408            )),
409        }
410    }
411}
412
413/// Converts UTF-8 bytes to a path.
414pub fn bytes2path(bytes: &[u8]) -> Result<PathBuf> {
415    #[cfg(unix)]
416    {
417        use std::os::unix::prelude::*;
418        Ok(PathBuf::from(OsStr::from_bytes(bytes)))
419    }
420    #[cfg(windows)]
421    {
422        use std::str;
423        match str::from_utf8(bytes) {
424            Ok(s) => Ok(PathBuf::from(s)),
425            Err(..) => Err(anyhow::format_err!("invalid non-unicode path")),
426        }
427    }
428}
429
430/// Returns an iterator that walks up the directory hierarchy towards the root.
431///
432/// Each item is a [`Path`]. It will start with the given path, finishing at
433/// the root. If the `stop_root_at` parameter is given, it will stop at the
434/// given path (which will be the last item).
435pub fn ancestors<'a>(path: &'a Path, stop_root_at: Option<&Path>) -> PathAncestors<'a> {
436    PathAncestors::new(path, stop_root_at)
437}
438
439pub struct PathAncestors<'a> {
440    current: Option<&'a Path>,
441    stop_at: Option<PathBuf>,
442}
443
444impl<'a> PathAncestors<'a> {
445    fn new(path: &'a Path, stop_root_at: Option<&Path>) -> PathAncestors<'a> {
446        let stop_at = env::var("__CARGO_TEST_ROOT")
447            .ok()
448            .map(PathBuf::from)
449            .or_else(|| stop_root_at.map(|p| p.to_path_buf()));
450        PathAncestors {
451            current: Some(path),
452            //HACK: avoid reading `~/.cargo/config` when testing Cargo itself.
453            stop_at,
454        }
455    }
456}
457
458impl<'a> Iterator for PathAncestors<'a> {
459    type Item = &'a Path;
460
461    fn next(&mut self) -> Option<&'a Path> {
462        if let Some(path) = self.current {
463            self.current = path.parent();
464
465            if let Some(ref stop_at) = self.stop_at {
466                if path == stop_at {
467                    self.current = None;
468                }
469            }
470
471            Some(path)
472        } else {
473            None
474        }
475    }
476}
477
478/// Equivalent to [`std::fs::create_dir_all`] with better error messages.
479pub fn create_dir_all(p: impl AsRef<Path>) -> Result<()> {
480    _create_dir_all(p.as_ref())
481}
482
483fn _create_dir_all(p: &Path) -> Result<()> {
484    fs::create_dir_all(p)
485        .with_context(|| format!("failed to create directory `{}`", p.display()))?;
486    Ok(())
487}
488
489/// Equivalent to [`std::fs::remove_dir_all`] with better error messages.
490///
491/// This does *not* follow symlinks.
492pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> Result<()> {
493    _remove_dir_all(p.as_ref()).or_else(|prev_err| {
494        // `std::fs::remove_dir_all` is highly specialized for different platforms
495        // and may be more reliable than a simple walk. We try the walk first in
496        // order to report more detailed errors.
497        fs::remove_dir_all(p.as_ref()).with_context(|| {
498            format!(
499                "{:?}\n\nError: failed to remove directory `{}`",
500                prev_err,
501                p.as_ref().display(),
502            )
503        })
504    })
505}
506
507fn _remove_dir_all(p: &Path) -> Result<()> {
508    if symlink_metadata(p)?.is_symlink() {
509        return remove_file(p);
510    }
511    let entries = p
512        .read_dir()
513        .with_context(|| format!("failed to read directory `{}`", p.display()))?;
514    for entry in entries {
515        let entry = entry?;
516        let path = entry.path();
517        if entry.file_type()?.is_dir() {
518            remove_dir_all(&path)?;
519        } else {
520            remove_file(&path)?;
521        }
522    }
523    remove_dir(&p)
524}
525
526/// Equivalent to [`std::fs::remove_dir`] with better error messages.
527pub fn remove_dir<P: AsRef<Path>>(p: P) -> Result<()> {
528    _remove_dir(p.as_ref())
529}
530
531fn _remove_dir(p: &Path) -> Result<()> {
532    fs::remove_dir(p).with_context(|| format!("failed to remove directory `{}`", p.display()))?;
533    Ok(())
534}
535
536/// Equivalent to [`std::fs::remove_file`] with better error messages.
537///
538/// If the file is readonly, this will attempt to change the permissions to
539/// force the file to be deleted.
540/// On Windows, if the file is a symlink to a directory, this will attempt to remove
541/// the symlink itself.
542pub fn remove_file<P: AsRef<Path>>(p: P) -> Result<()> {
543    _remove_file(p.as_ref())
544}
545
546fn _remove_file(p: &Path) -> Result<()> {
547    // For Windows, we need to check if the file is a symlink to a directory
548    // and remove the symlink itself by calling `remove_dir` instead of
549    // `remove_file`.
550    #[cfg(target_os = "windows")]
551    {
552        use std::os::windows::fs::FileTypeExt;
553        let metadata = symlink_metadata(p)?;
554        let file_type = metadata.file_type();
555        if file_type.is_symlink_dir() {
556            return remove_symlink_dir_with_permission_check(p);
557        }
558    }
559
560    remove_file_with_permission_check(p)
561}
562
563#[cfg(target_os = "windows")]
564fn remove_symlink_dir_with_permission_check(p: &Path) -> Result<()> {
565    remove_with_permission_check(fs::remove_dir, p)
566        .with_context(|| format!("failed to remove symlink dir `{}`", p.display()))
567}
568
569fn remove_file_with_permission_check(p: &Path) -> Result<()> {
570    remove_with_permission_check(fs::remove_file, p)
571        .with_context(|| format!("failed to remove file `{}`", p.display()))
572}
573
574fn remove_with_permission_check<F, P>(remove_func: F, p: P) -> io::Result<()>
575where
576    F: Fn(P) -> io::Result<()>,
577    P: AsRef<Path> + Clone,
578{
579    match remove_func(p.clone()) {
580        Ok(()) => Ok(()),
581        Err(e) => {
582            if e.kind() == io::ErrorKind::PermissionDenied
583                && set_not_readonly(p.as_ref()).unwrap_or(false)
584            {
585                remove_func(p)
586            } else {
587                Err(e)
588            }
589        }
590    }
591}
592
593fn set_not_readonly(p: &Path) -> io::Result<bool> {
594    let mut perms = p.metadata()?.permissions();
595    if !perms.readonly() {
596        return Ok(false);
597    }
598    perms.set_readonly(false);
599    fs::set_permissions(p, perms)?;
600    Ok(true)
601}
602
603/// Hardlink (file) or symlink (dir) src to dst if possible, otherwise copy it.
604///
605/// If the destination already exists, it is removed before linking.
606pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
607    let src = src.as_ref();
608    let dst = dst.as_ref();
609    _link_or_copy(src, dst)
610}
611
612fn _link_or_copy(src: &Path, dst: &Path) -> Result<()> {
613    tracing::debug!("linking {} to {}", src.display(), dst.display());
614    if same_file::is_same_file(src, dst).unwrap_or(false) {
615        return Ok(());
616    }
617
618    // NB: we can't use dst.exists(), as if dst is a broken symlink,
619    // dst.exists() will return false. This is problematic, as we still need to
620    // unlink dst in this case. symlink_metadata(dst).is_ok() will tell us
621    // whether dst exists *without* following symlinks, which is what we want.
622    if fs::symlink_metadata(dst).is_ok() {
623        remove_file(&dst)?;
624    }
625
626    let link_result = if src.is_dir() {
627        #[cfg(unix)]
628        use std::os::unix::fs::symlink;
629        #[cfg(windows)]
630        // FIXME: This should probably panic or have a copy fallback. Symlinks
631        // are not supported in all windows environments. Currently symlinking
632        // is only used for .dSYM directories on macos, but this shouldn't be
633        // accidentally relied upon.
634        use std::os::windows::fs::symlink_dir as symlink;
635
636        let dst_dir = dst.parent().unwrap();
637        let src = if src.starts_with(dst_dir) {
638            src.strip_prefix(dst_dir).unwrap()
639        } else {
640            src
641        };
642        symlink(src, dst)
643    } else {
644        if cfg!(target_os = "macos") {
645            // There seems to be a race condition with APFS when hard-linking
646            // binaries. Gatekeeper does not have signing or hash information
647            // stored in kernel when running the process. Therefore killing it.
648            // This problem does not appear when copying files as kernel has
649            // time to process it. Note that: fs::copy on macos is using
650            // CopyOnWrite (syscall fclonefileat) which should be as fast as
651            // hardlinking. See these issues for the details:
652            //
653            // * https://github.com/rust-lang/cargo/issues/7821
654            // * https://github.com/rust-lang/cargo/issues/10060
655            fs::copy(src, dst).map_or_else(
656                |e| {
657                    if e.raw_os_error()
658                        .map_or(false, |os_err| os_err == 35 /* libc::EAGAIN */)
659                    {
660                        tracing::info!("copy failed {e:?}. falling back to fs::hard_link");
661
662                        // Working around an issue copying too fast with zfs (probably related to
663                        // https://github.com/openzfsonosx/zfs/issues/809)
664                        // See https://github.com/rust-lang/cargo/issues/13838
665                        fs::hard_link(src, dst)
666                    } else {
667                        Err(e)
668                    }
669                },
670                |_| Ok(()),
671            )
672        } else {
673            fs::hard_link(src, dst)
674        }
675    };
676    link_result
677        .or_else(|err| {
678            tracing::debug!("link failed {}. falling back to fs::copy", err);
679            fs::copy(src, dst).map(|_| ())
680        })
681        .with_context(|| {
682            format!(
683                "failed to link or copy `{}` to `{}`",
684                src.display(),
685                dst.display()
686            )
687        })?;
688    Ok(())
689}
690
691/// Copies a file from one location to another.
692///
693/// Equivalent to [`std::fs::copy`] with better error messages.
694pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> {
695    let from = from.as_ref();
696    let to = to.as_ref();
697    fs::copy(from, to)
698        .with_context(|| format!("failed to copy `{}` to `{}`", from.display(), to.display()))
699}
700
701/// Changes the filesystem mtime (and atime if possible) for the given file.
702///
703/// This intentionally does not return an error, as this is sometimes not
704/// supported on network filesystems. For the current uses in Cargo, this is a
705/// "best effort" approach, and errors shouldn't be propagated.
706pub fn set_file_time_no_err<P: AsRef<Path>>(path: P, time: FileTime) {
707    let path = path.as_ref();
708    let times = fs::FileTimes::new()
709        .set_accessed(time.into())
710        .set_modified(time.into());
711    match fs::set_times(path, times) {
712        Ok(()) => tracing::debug!("set file mtime {} to {}", path.display(), time),
713        Err(e) => tracing::warn!(
714            "could not set mtime of {} to {}: {:?}",
715            path.display(),
716            time,
717            e
718        ),
719    }
720}
721
722/// Strips `base` from `path`.
723///
724/// This canonicalizes both paths before stripping. This is useful if the
725/// paths are obtained in different ways, and one or the other may or may not
726/// have been normalized in some way.
727pub fn strip_prefix_canonical(
728    path: impl AsRef<Path>,
729    base: impl AsRef<Path>,
730) -> Result<PathBuf, std::path::StripPrefixError> {
731    // Not all filesystems support canonicalize. Just ignore if it doesn't work.
732    let safe_canonicalize = |path: &Path| match path.canonicalize() {
733        Ok(p) => p,
734        Err(e) => {
735            tracing::warn!("cannot canonicalize {:?}: {:?}", path, e);
736            path.to_path_buf()
737        }
738    };
739    let canon_path = safe_canonicalize(path.as_ref());
740    let canon_base = safe_canonicalize(base.as_ref());
741    canon_path.strip_prefix(canon_base).map(|p| p.to_path_buf())
742}
743
744/// Creates an excluded from cache directory atomically with its parents as needed.
745///
746/// The atomicity only covers creating the leaf directory and exclusion from cache. Any missing
747/// parent directories will not be created in an atomic manner.
748///
749/// This function is idempotent and in addition to that it won't exclude ``p`` from cache if it
750/// already exists.
751pub fn create_dir_all_excluded_from_backups_atomic(p: impl AsRef<Path>) -> Result<()> {
752    let path = p.as_ref();
753    if path.is_dir() {
754        return Ok(());
755    }
756
757    let parent = path.parent().unwrap();
758    let base = path.file_name().unwrap();
759    create_dir_all(parent)?;
760    // We do this in two steps (first create a temporary directory and exclude
761    // it from backups, then rename it to the desired name. If we created the
762    // directory directly where it should be and then excluded it from backups
763    // we would risk a situation where cargo is interrupted right after the directory
764    // creation but before the exclusion the directory would remain non-excluded from
765    // backups because we only perform exclusion right after we created the directory
766    // ourselves.
767    //
768    // We need the tempdir created in parent instead of $TMP, because only then we can be
769    // easily sure that rename() will succeed (the new name needs to be on the same mount
770    // point as the old one).
771    let tempdir = TempFileBuilder::new().prefix(base).tempdir_in(parent)?;
772    exclude_from_backups(tempdir.path());
773    exclude_from_content_indexing(tempdir.path());
774    // Previously std::fs::create_dir_all() (through paths::create_dir_all()) was used
775    // here to create the directory directly and fs::create_dir_all() explicitly treats
776    // the directory being created concurrently by another thread or process as success,
777    // hence the check below to follow the existing behavior. If we get an error at
778    // rename() and suddenly the directory (which didn't exist a moment earlier) exists
779    // we can infer from it's another cargo process doing work.
780    if let Err(e) = fs::rename(tempdir.path(), path) {
781        if !path.exists() {
782            return Err(anyhow::Error::from(e))
783                .with_context(|| format!("failed to create directory `{}`", path.display()));
784        }
785    }
786    Ok(())
787}
788
789/// Mark an existing directory as excluded from backups and indexing.
790///
791/// Errors in marking it are ignored.
792pub fn exclude_from_backups_and_indexing(p: impl AsRef<Path>) {
793    let path = p.as_ref();
794    exclude_from_backups(path);
795    exclude_from_content_indexing(path);
796}
797
798/// Marks the directory as excluded from archives/backups.
799///
800/// This is recommended to prevent derived/temporary files from bloating backups. There are two
801/// mechanisms used to achieve this right now:
802///
803/// * A dedicated resource property excluding from Time Machine backups on macOS
804/// * CACHEDIR.TAG files supported by various tools in a platform-independent way
805fn exclude_from_backups(path: &Path) {
806    exclude_from_time_machine_and_cloud_sync(path);
807    let file = path.join("CACHEDIR.TAG");
808    if !file.exists() {
809        let _ = std::fs::write(
810            file,
811            "Signature: 8a477f597d28d172789f06886806bc55
812# This file is a cache directory tag created by cargo.
813# For information about cache directory tags see https://bford.info/cachedir/
814",
815        );
816        // Similarly to exclude_from_time_machine_and_cloud_sync() we ignore errors here as it's an optional feature.
817    }
818}
819
820/// Marks the directory as excluded from content indexing.
821///
822/// This is recommended to prevent the content of derived/temporary files from being indexed.
823/// This is very important for Windows users, as the live content indexing significantly slows
824/// cargo's I/O operations.
825///
826/// This is currently a no-op on non-Windows platforms.
827fn exclude_from_content_indexing(path: &Path) {
828    #[cfg(windows)]
829    {
830        use std::iter::once;
831        use std::os::windows::prelude::OsStrExt;
832        use windows_sys::Win32::Storage::FileSystem::{
833            FILE_ATTRIBUTE_NOT_CONTENT_INDEXED, GetFileAttributesW, SetFileAttributesW,
834        };
835
836        let path: Vec<u16> = path.as_os_str().encode_wide().chain(once(0)).collect();
837        unsafe {
838            SetFileAttributesW(
839                path.as_ptr(),
840                GetFileAttributesW(path.as_ptr()) | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,
841            );
842        }
843    }
844    #[cfg(not(windows))]
845    {
846        let _ = path;
847    }
848}
849
850#[cfg(not(target_os = "macos"))]
851fn exclude_from_time_machine_and_cloud_sync(_: &Path) {}
852
853#[cfg(target_os = "macos")]
854/// Marks files or directories as excluded from Time Machine and iCloud Drive on macOS
855fn exclude_from_time_machine_and_cloud_sync(path: &Path) {
856    use core_foundation::base::TCFType;
857    use core_foundation::{number, string, url};
858    use std::ptr;
859
860    let path = match url::CFURL::from_path(path, false) {
861        Some(url) => url,
862        None => return,
863    };
864
865    // For compatibility with old systems strings are used instead of global symbols
866    const KEY_NAMES: [&str; 2] = [
867        "NSURLIsExcludedFromBackupKey", // kCFURLIsExcludedFromBackupKey
868        "NSURLUbiquitousItemIsExcludedFromSyncKey", // kCFURLUbiquitousItemIsExcludedFromSyncKey
869    ];
870
871    for key_name in KEY_NAMES {
872        let is_excluded_key = match key_name.parse::<string::CFString>() {
873            Ok(key) => key,
874            Err(_) => continue,
875        };
876        unsafe {
877            url::CFURLSetResourcePropertyForKey(
878                path.as_concrete_TypeRef(),
879                is_excluded_key.as_concrete_TypeRef(),
880                number::kCFBooleanTrue as *const _,
881                ptr::null_mut(),
882            );
883        }
884    }
885    // Errors are ignored, since it's an optional feature and failure
886    // doesn't prevent Cargo from working
887}
888
889#[cfg(test)]
890mod tests {
891    use super::join_paths;
892    use super::normalize_path;
893    use super::write;
894    use super::write_atomic;
895
896    #[test]
897    fn test_normalize_path() {
898        let cases = &[
899            ("", ""),
900            (".", ""),
901            (".////./.", ""),
902            ("/", "/"),
903            ("/..", "/"),
904            ("/foo/bar", "/foo/bar"),
905            ("/foo/bar/", "/foo/bar"),
906            ("/foo/bar/./././///", "/foo/bar"),
907            ("/foo/bar/..", "/foo"),
908            ("/foo/bar/../..", "/"),
909            ("/foo/bar/../../..", "/"),
910            ("foo/bar", "foo/bar"),
911            ("foo/bar/", "foo/bar"),
912            ("foo/bar/./././///", "foo/bar"),
913            ("foo/bar/..", "foo"),
914            ("foo/bar/../..", ""),
915            ("foo/bar/../../..", ".."),
916            ("../../foo/bar", "../../foo/bar"),
917            ("../../foo/bar/", "../../foo/bar"),
918            ("../../foo/bar/./././///", "../../foo/bar"),
919            ("../../foo/bar/..", "../../foo"),
920            ("../../foo/bar/../..", "../.."),
921            ("../../foo/bar/../../..", "../../.."),
922        ];
923        for (input, expected) in cases {
924            let actual = normalize_path(std::path::Path::new(input));
925            assert_eq!(actual, std::path::Path::new(expected), "input: {input}");
926        }
927    }
928
929    #[test]
930    fn write_works() {
931        let original_contents = "[dependencies]\nfoo = 0.1.0";
932
933        let tmpdir = tempfile::tempdir().unwrap();
934        let path = tmpdir.path().join("Cargo.toml");
935        write(&path, original_contents).unwrap();
936        let contents = std::fs::read_to_string(&path).unwrap();
937        assert_eq!(contents, original_contents);
938    }
939    #[test]
940    fn write_atomic_works() {
941        let original_contents = "[dependencies]\nfoo = 0.1.0";
942
943        let tmpdir = tempfile::tempdir().unwrap();
944        let path = tmpdir.path().join("Cargo.toml");
945        write_atomic(&path, original_contents).unwrap();
946        let contents = std::fs::read_to_string(&path).unwrap();
947        assert_eq!(contents, original_contents);
948    }
949
950    #[test]
951    #[cfg(unix)]
952    fn write_atomic_permissions() {
953        use std::os::unix::fs::PermissionsExt;
954
955        let original_perms = std::fs::Permissions::from_mode(
956            (libc::S_IRWXU | libc::S_IRGRP | libc::S_IWGRP | libc::S_IROTH) as u32,
957        );
958
959        let tmp = tempfile::Builder::new().tempfile().unwrap();
960
961        // need to set the permissions after creating the file to avoid umask
962        tmp.as_file()
963            .set_permissions(original_perms.clone())
964            .unwrap();
965
966        // after this call, the file at `tmp.path()` will not be the same as the file held by `tmp`
967        write_atomic(tmp.path(), "new").unwrap();
968        assert_eq!(std::fs::read_to_string(tmp.path()).unwrap(), "new");
969
970        let new_perms = std::fs::metadata(tmp.path()).unwrap().permissions();
971
972        let mask = (libc::S_IRWXU | libc::S_IRWXG | libc::S_IRWXO) as u32;
973        assert_eq!(original_perms.mode(), new_perms.mode() & mask);
974    }
975
976    #[test]
977    fn join_paths_lists_paths_on_error() {
978        let valid_paths = vec!["/testing/one", "/testing/two"];
979        // does not fail on valid input
980        let _joined = join_paths(&valid_paths, "TESTING1").unwrap();
981
982        #[cfg(unix)]
983        {
984            let invalid_paths = vec!["/testing/one", "/testing/t:wo/three"];
985            let err = join_paths(&invalid_paths, "TESTING2").unwrap_err();
986            assert_eq!(
987                err.to_string(),
988                "failed to join paths from `$TESTING2` together\n\n\
989             Check if any of path segments listed below contain an \
990             unterminated quote character or path separator:\
991             \n    \"/testing/one\"\
992             \n    \"/testing/t:wo/three\"\
993             "
994            );
995        }
996        #[cfg(windows)]
997        {
998            let invalid_paths = vec!["/testing/one", "/testing/t\"wo/three"];
999            let err = join_paths(&invalid_paths, "TESTING2").unwrap_err();
1000            assert_eq!(
1001                err.to_string(),
1002                "failed to join paths from `$TESTING2` together\n\n\
1003             Check if any of path segments listed below contain an \
1004             unterminated quote character or path separator:\
1005             \n    \"/testing/one\"\
1006             \n    \"/testing/t\\\"wo/three\"\
1007             "
1008            );
1009        }
1010    }
1011
1012    #[test]
1013    fn write_atomic_symlink() {
1014        let tmpdir = tempfile::tempdir().unwrap();
1015        let target_path = tmpdir.path().join("target.txt");
1016        let symlink_path = tmpdir.path().join("symlink.txt");
1017
1018        // Create initial file
1019        write(&target_path, "initial").unwrap();
1020
1021        // Create symlink
1022        #[cfg(unix)]
1023        std::os::unix::fs::symlink(&target_path, &symlink_path).unwrap();
1024        #[cfg(windows)]
1025        std::os::windows::fs::symlink_file(&target_path, &symlink_path).unwrap();
1026
1027        // Write through symlink
1028        write_atomic(&symlink_path, "updated").unwrap();
1029
1030        // Verify both paths show the updated content
1031        assert_eq!(std::fs::read_to_string(&target_path).unwrap(), "updated");
1032        assert_eq!(std::fs::read_to_string(&symlink_path).unwrap(), "updated");
1033
1034        // Verify symlink still exists and points to the same target
1035        assert!(symlink_path.is_symlink());
1036        assert_eq!(std::fs::read_link(&symlink_path).unwrap(), target_path);
1037    }
1038
1039    #[test]
1040    fn write_atomic_relative_symlink() {
1041        let tmpdir = tempfile::tempdir().unwrap();
1042        let link_dir = tmpdir.path().join("project");
1043        let target_dir = link_dir.join("generated");
1044        let target_path = target_dir.join("target.txt");
1045        let symlink_path = link_dir.join("symlink.txt");
1046        let relative_target = std::path::Path::new("generated/target.txt");
1047
1048        std::fs::create_dir_all(&target_dir).unwrap();
1049        write(&target_path, "initial").unwrap();
1050
1051        #[cfg(unix)]
1052        std::os::unix::fs::symlink(relative_target, &symlink_path).unwrap();
1053        #[cfg(windows)]
1054        std::os::windows::fs::symlink_file(relative_target, &symlink_path).unwrap();
1055
1056        write_atomic(&symlink_path, "updated").unwrap();
1057
1058        assert_eq!(std::fs::read_to_string(&target_path).unwrap(), "updated");
1059        assert!(symlink_path.is_symlink());
1060        assert_eq!(std::fs::read_link(&symlink_path).unwrap(), relative_target);
1061    }
1062
1063    #[test]
1064    #[cfg(windows)]
1065    fn test_remove_symlink_dir() {
1066        use super::*;
1067        use std::fs;
1068        use std::os::windows::fs::symlink_dir;
1069
1070        let tmpdir = tempfile::tempdir().unwrap();
1071        let dir_path = tmpdir.path().join("testdir");
1072        let symlink_path = tmpdir.path().join("symlink");
1073
1074        fs::create_dir(&dir_path).unwrap();
1075
1076        symlink_dir(&dir_path, &symlink_path).expect("failed to create symlink");
1077
1078        assert!(symlink_path.exists());
1079
1080        assert!(remove_file(symlink_path.clone()).is_ok());
1081
1082        assert!(!symlink_path.exists());
1083        assert!(dir_path.exists());
1084    }
1085
1086    #[test]
1087    #[cfg(windows)]
1088    fn test_remove_symlink_file() {
1089        use super::*;
1090        use std::fs;
1091        use std::os::windows::fs::symlink_file;
1092
1093        let tmpdir = tempfile::tempdir().unwrap();
1094        let file_path = tmpdir.path().join("testfile");
1095        let symlink_path = tmpdir.path().join("symlink");
1096
1097        fs::write(&file_path, b"test").unwrap();
1098
1099        symlink_file(&file_path, &symlink_path).expect("failed to create symlink");
1100
1101        assert!(symlink_path.exists());
1102
1103        assert!(remove_file(symlink_path.clone()).is_ok());
1104
1105        assert!(!symlink_path.exists());
1106        assert!(file_path.exists());
1107    }
1108}