1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 11:37:44 +00:00

uucore/fs: add Not a directory cases handling, e.g. for trailing slashes

This commit is contained in:
Niyaz Nigmatullin 2022-08-15 22:38:55 +03:00
parent 0ce135bd97
commit 5af152be2c

View file

@ -22,11 +22,12 @@ use std::collections::VecDeque;
use std::env; use std::env;
use std::ffi::{OsStr, OsString}; use std::ffi::{OsStr, OsString};
use std::fs; use std::fs;
use std::fs::read_dir;
use std::hash::Hash; use std::hash::Hash;
use std::io::{Error, ErrorKind, Result as IOResult}; use std::io::{Error, ErrorKind, Result as IOResult};
#[cfg(unix)] #[cfg(unix)]
use std::os::unix::{fs::MetadataExt, io::AsRawFd}; use std::os::unix::{fs::MetadataExt, io::AsRawFd};
use std::path::{Component, Path, PathBuf}; use std::path::{Component, Path, PathBuf, MAIN_SEPARATOR};
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
use winapi_util::AsHandleRef; use winapi_util::AsHandleRef;
@ -318,6 +319,11 @@ pub fn canonicalize<P: AsRef<Path>>(
) -> IOResult<PathBuf> { ) -> IOResult<PathBuf> {
const SYMLINKS_TO_LOOK_FOR_LOOPS: i32 = 20; const SYMLINKS_TO_LOOK_FOR_LOOPS: i32 = 20;
let original = original.as_ref(); let original = original.as_ref();
let has_to_be_directory =
(miss_mode == MissingHandling::Normal || miss_mode == MissingHandling::Existing) && {
let path_str = original.to_string_lossy();
path_str.ends_with(MAIN_SEPARATOR) || path_str.ends_with('/')
};
let original = if original.is_absolute() { let original = if original.is_absolute() {
original.to_path_buf() original.to_path_buf()
} else { } else {
@ -383,6 +389,24 @@ pub fn canonicalize<P: AsRef<Path>>(
_ => {} _ => {}
} }
} }
// raise Not a directory if required
match miss_mode {
MissingHandling::Existing => {
if has_to_be_directory {
read_dir(&result)?;
}
}
MissingHandling::Normal => {
if result.exists() {
if has_to_be_directory {
read_dir(&result)?;
}
} else if let Some(parent) = result.parent() {
read_dir(parent)?;
}
}
_ => {}
}
Ok(result) Ok(result)
} }