Skip to content
Myr

filesystem.rs

This file

Path

src/filesystem.rs

158 lines · 3.9 KiB · Rust

Last changed by

Support character and block device file typesChristian Göttschebefore adoption36bc840

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;8use std::path::{Path, PathBuf};910use normpath::PathExt;1112use crate::dir_entry;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}4344pub fn is_empty(entry: &dir_entry::DirEntry) -> bool {45    if let Some(file_type) = entry.file_type() {46        if file_type.is_dir() {47            if let Ok(mut entries) = fs::read_dir(entry.path()) {48                entries.next().is_none()49            } else {50                false51            }52        } else if file_type.is_file() {53            entry.metadata().map(|m| m.len() == 0).unwrap_or(false)54        } else {55            false56        }57    } else {58        false59    }60}6162#[cfg(any(unix, target_os = "redox"))]63pub fn is_block_device(ft: fs::FileType) -> bool {64    ft.is_block_device()65}6667#[cfg(windows)]68pub fn is_block_device(_: fs::FileType) -> bool {69    false70}7172#[cfg(any(unix, target_os = "redox"))]73pub fn is_char_device(ft: fs::FileType) -> bool {74    ft.is_char_device()75}7677#[cfg(windows)]78pub fn is_char_device(_: fs::FileType) -> bool {79    false80}8182#[cfg(any(unix, target_os = "redox"))]83pub fn is_socket(ft: fs::FileType) -> bool {84    ft.is_socket()85}8687#[cfg(windows)]88pub fn is_socket(_: fs::FileType) -> bool {89    false90}9192#[cfg(any(unix, target_os = "redox"))]93pub fn is_pipe(ft: fs::FileType) -> bool {94    ft.is_fifo()95}9697#[cfg(windows)]98pub fn is_pipe(_: fs::FileType) -> bool {99    false100}101102#[cfg(any(unix, target_os = "redox"))]103pub fn osstr_to_bytes(input: &OsStr) -> Cow<[u8]> {104    use std::os::unix::ffi::OsStrExt;105    Cow::Borrowed(input.as_bytes())106}107108#[cfg(windows)]109pub fn osstr_to_bytes(input: &OsStr) -> Cow<[u8]> {110    let string = input.to_string_lossy();111112    match string {113        Cow::Owned(string) => Cow::Owned(string.into_bytes()),114        Cow::Borrowed(string) => Cow::Borrowed(string.as_bytes()),115    }116}117118/// Remove the `./` prefix from a path.119pub fn strip_current_dir(path: &Path) -> &Path {120    path.strip_prefix(".").unwrap_or(path)121}122123/// Default value for the path_separator, mainly for MSYS/MSYS2, which set the MSYSTEM124/// environment variable, and we set fd's path separator to '/' rather than Rust's default of '\'.125///126/// Returns Some to use a nonstandard path separator, or None to use rust's default on the target127/// platform.128pub fn default_path_separator() -> Option<String> {129    if cfg!(windows) {130        let msystem = env::var("MSYSTEM").ok()?;131        match msystem.as_str() {132            "MINGW64" | "MINGW32" | "MSYS" => Some("/".to_owned()),133            _ => None,134        }135    } else {136        None137    }138}139140#[cfg(test)]141mod tests {142    use super::strip_current_dir;143    use std::path::Path;144145    #[test]146    fn strip_current_dir_basic() {147        assert_eq!(strip_current_dir(Path::new("./foo")), Path::new("foo"));148        assert_eq!(strip_current_dir(Path::new("foo")), Path::new("foo"));149        assert_eq!(150            strip_current_dir(Path::new("./foo/bar/baz")),151            Path::new("foo/bar/baz")152        );153        assert_eq!(154            strip_current_dir(Path::new("foo/bar/baz")),155            Path::new("foo/bar/baz")156        );157    }158}