Skip to content
Myr

filesystem.rs

This file

Path

src/filesystem.rs

148 lines · 3.7 KiB · Rust

Last changed by

Fix directory-existence check on WindowsDavid Peterbefore adoption2d398dc

History of this file

Take it

1use std::borrow::Cow;2use std::env;3use std::ffi::OsStr;4use std::fs;5use std::io;6#[cfg(any(unix, target_os = "redox"))]7use std::os::unix::fs::{FileTypeExt, PermissionsExt};8use std::path::{Path, PathBuf};910use normpath::PathExt;1112use crate::walk;1314pub fn path_absolute_form(path: &Path) -> io::Result<PathBuf> {15    if path.is_absolute() {16        return Ok(path.to_path_buf());17    }1819    let path = path.strip_prefix(".").unwrap_or(path);20    env::current_dir().map(|path_buf| path_buf.join(path))21}2223pub fn absolute_path(path: &Path) -> io::Result<PathBuf> {24    let path_buf = path_absolute_form(path)?;2526    #[cfg(windows)]27    let path_buf = Path::new(28        path_buf29            .as_path()30            .to_string_lossy()31            .trim_start_matches(r"\\?\"),32    )33    .to_path_buf();3435    Ok(path_buf)36}3738pub fn is_existing_directory(path: &Path) -> bool {39    // Note: we do not use `.exists()` here, as `.` always exists, even if40    // the CWD has been deleted.41    path.is_dir() && (path.file_name().is_some() || path.normalize().is_ok())42}4344#[cfg(any(unix, target_os = "redox"))]45pub fn is_executable(md: &fs::Metadata) -> bool {46    md.permissions().mode() & 0o111 != 047}4849#[cfg(windows)]50pub fn is_executable(_: &fs::Metadata) -> bool {51    false52}5354pub fn is_empty(entry: &walk::DirEntry) -> bool {55    if let Some(file_type) = entry.file_type() {56        if file_type.is_dir() {57            if let Ok(mut entries) = fs::read_dir(entry.path()) {58                entries.next().is_none()59            } else {60                false61            }62        } else if file_type.is_file() {63            entry.metadata().map(|m| m.len() == 0).unwrap_or(false)64        } else {65            false66        }67    } else {68        false69    }70}7172#[cfg(any(unix, target_os = "redox"))]73pub fn is_socket(ft: fs::FileType) -> bool {74    ft.is_socket()75}7677#[cfg(windows)]78pub fn is_socket(_: fs::FileType) -> bool {79    false80}8182#[cfg(any(unix, target_os = "redox"))]83pub fn is_pipe(ft: fs::FileType) -> bool {84    ft.is_fifo()85}8687#[cfg(windows)]88pub fn is_pipe(_: fs::FileType) -> bool {89    false90}9192#[cfg(any(unix, target_os = "redox"))]93pub fn osstr_to_bytes(input: &OsStr) -> Cow<[u8]> {94    use std::os::unix::ffi::OsStrExt;95    Cow::Borrowed(input.as_bytes())96}9798#[cfg(windows)]99pub fn osstr_to_bytes(input: &OsStr) -> Cow<[u8]> {100    let string = input.to_string_lossy();101102    match string {103        Cow::Owned(string) => Cow::Owned(string.into_bytes()),104        Cow::Borrowed(string) => Cow::Borrowed(string.as_bytes()),105    }106}107108/// Remove the `./` prefix from a path.109pub fn strip_current_dir(path: &Path) -> &Path {110    path.strip_prefix(".").unwrap_or(path)111}112113/// Default value for the path_separator, mainly for MSYS/MSYS2, which set the MSYSTEM114/// environment variable, and we set fd's path separator to '/' rather than Rust's default of '\'.115///116/// Returns Some to use a nonstandard path separator, or None to use rust's default on the target117/// platform.118pub fn default_path_separator() -> Option<String> {119    if cfg!(windows) {120        let msystem = env::var("MSYSTEM").ok()?;121        match msystem.as_str() {122            "MINGW64" | "MINGW32" | "MSYS" => Some("/".to_owned()),123            _ => None,124        }125    } else {126        None127    }128}129130#[cfg(test)]131mod tests {132    use super::strip_current_dir;133    use std::path::Path;134135    #[test]136    fn strip_current_dir_basic() {137        assert_eq!(strip_current_dir(Path::new("./foo")), Path::new("foo"));138        assert_eq!(strip_current_dir(Path::new("foo")), Path::new("foo"));139        assert_eq!(140            strip_current_dir(Path::new("./foo/bar/baz")),141            Path::new("foo/bar/baz")142        );143        assert_eq!(144            strip_current_dir(Path::new("foo/bar/baz")),145            Path::new("foo/bar/baz")146        );147    }148}