Reimplement dirname, basename, remove_extension for OsStr
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by sharkdp · committed by David Peter · parent 439548c · Browse files · 3 files·+64 added−82 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+64 added−82 removed
- other:+64 added−82 removed
Provenance
- Commit
7e3c69c- Tree
23743c1- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
439548c
3 files changed+64 added−82 removed
modified:src/exec/input.rs+34 added-60 removed
1-use std::path::MAIN_SEPARATOR;1+use std::ffi::{OsStr, OsString};2+use std::path::{Path, PathBuf};3 3-/// Removes the parent component of the path4-pub fn basename(path: &str) -> &str {5- let mut index = 0;6- for (id, character) in path.char_indices() {7- if character == MAIN_SEPARATOR {8- index = id;9- }10- }4+use crate::filesystem::strip_current_dir;5 12- // FIXME: On Windows, should return what for C:file.txt D:file.txt and \\server\share ?13- if index != 0 {14- return &path[index + 1..];15- }16-17- path6+/// Removes the parent component of the path7+pub fn basename(path: &Path) -> &OsStr {8+ path.file_name().unwrap_or(path.as_os_str())9 }10 11 /// Removes the extension from the path21-pub fn remove_extension(path: &str) -> &str {22- let mut has_dir = false;23- let mut dir_index = 0;24- let mut ext_index = 0;12+pub fn remove_extension(path: &Path) -> OsString {13+ let dirname = dirname(path);14+ let stem = path.file_stem().unwrap_or(path.as_os_str());15 26- for (id, character) in path.char_indices() {27- if character == MAIN_SEPARATOR {28- has_dir = true;29- dir_index = id;30- }31- if character == '.' {32- ext_index = id;33- }34- }16+ let path = PathBuf::from(dirname).join(stem);17 36- // Account for hidden files and directories37- if ext_index != 0 && (!has_dir || dir_index + 2 <= ext_index) {38- return &path[0..ext_index];39- }40-41- path18+ strip_current_dir(&path).to_owned().into_os_string()19 }20 21 /// Removes the basename from the path.45-pub fn dirname(path: &str) -> &str {46- let mut has_dir = false;47- let mut index = 0;48- for (id, character) in path.char_indices() {49- if character == MAIN_SEPARATOR {50- has_dir = true;51- index = id;52- }53- }54-55- // FIXME: On Windows, return what for C:file.txt D:file.txt and \\server\share ?56- if !has_dir {57- "."58- } else if index == 0 {59- &path[..1]60- } else {61- &path[0..index]62- }22+pub fn dirname(path: &Path) -> OsString {23+ path.parent()24+ .map(|p| {25+ if p == OsStr::new("") {26+ OsString::from(".")27+ } else {28+ p.as_os_str().to_owned()29+ }30+ })31+ .unwrap_or(path.as_os_str().to_owned())32 }33 34 #[cfg(test)]35 mod path_tests {36 use super::*;37+ use std::path::MAIN_SEPARATOR;38 39 fn correct(input: &str) -> String {40 input.replace('/', &MAIN_SEPARATOR.to_string())41 }2 unmodified lines44 ($($name:ident: $func:ident for $input:expr => $output:expr)+) => {45 $(46 #[test]47 fn $name() {78- assert_eq!($func(&correct($input)), correct($output));48+ let input_path = PathBuf::from(&correct($input));49+ let output_string = OsString::from(correct($output));50+ assert_eq!($func(&input_path), output_string);51 }52 )+53 }54 }14 unmodified lines69 dirname_simple: dirname for "foo.txt" => "."70 dirname_dir: dirname for "dir/foo.txt" => "dir"71 dirname_utf8_0: dirname for "💖/foo.txt" => "💖"72 dirname_utf8_1: dirname for "dir/💖.txt" => "dir"101- dirname_empty: dirname for "" => "."73 }74 75 #[test]76+ #[cfg(windows)]77 fn dirname_root() {106- #[cfg(windows)]107- assert_eq!(dirname("C:\\"), "C:");108- #[cfg(windows)]109- assert_eq!(dirname("\\"), "\\");110- #[cfg(not(windows))]111- assert_eq!(dirname("/"), "/");78+ assert_eq!(dirname(&PathBuf::from("C:\\")), OsString::from("C:"));79+ assert_eq!(dirname(&PathBuf::from("\\")), OsString::from("\\"));80 }81+82+ #[test]83+ #[cfg(not(windows))]84+ fn dirname_root() {85+ assert_eq!(dirname(&PathBuf::from("/")), OsString::from("/"));86+ }87 }modified:src/exec/mod.rs+18 added-18 removed
1 unmodified line2 mod input;3 mod job;4 mod token;5 6-use std::borrow::Cow;6+use std::ffi::OsString;7 use std::path::{Path, PathBuf};8 use std::process::{Command, Stdio};9 use std::sync::{Arc, Mutex};10 124 unmodified lines135 /// build. Once all arguments have been processed, the command is executed.136 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> ExitCode {137 let input = strip_current_dir(input);138 139- let mut cmd = Command::new(self.args[0].generate(&input).as_ref());139+ let mut cmd = Command::new(self.args[0].generate(&input));140 for arg in &self.args[1..] {141- cmd.arg(arg.generate(&input).as_ref());141+ cmd.arg(arg.generate(&input));142 }143 144 execute_command(cmd, &out_perm)145 }5 unmodified lines151 pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCode152 where153 I: Iterator<Item = PathBuf>,154 {155- let mut cmd = Command::new(self.args[0].generate("").as_ref());155+ let mut cmd = Command::new(self.args[0].generate(""));156 cmd.stdin(Stdio::inherit());157 cmd.stdout(Stdio::inherit());158 cmd.stderr(Stdio::inherit());159 6 unmodified lines166 167 // A single `Tokens` is expected168 // So we can directly consume the iterator once and for all169 for path in &mut paths {170- cmd.arg(arg.generate(strip_current_dir(path)).as_ref());170+ cmd.arg(arg.generate(strip_current_dir(path)));171 has_path = true;172 }173 } else {174- cmd.arg(arg.generate("").as_ref());174+ cmd.arg(arg.generate(""));175 }176 }177 178 if has_path {21 unmodified lines200 _ => false,201 }202 }203 204- pub fn generate<'a>(&'a self, path: impl AsRef<Path>) -> Cow<'a, str> {204+ pub fn generate<'a>(&'a self, path: impl AsRef<Path>) -> OsString {205 use self::Token::*;206 207- let path = path.as_ref().to_string_lossy(); // TODO208-207 match *self {208 ArgumentTemplate::Tokens(ref tokens) => {211- let mut s = String::new();209+ let mut s = OsString::new();210 for token in tokens {211 match *token {214- Basename => s += basename(&path),215- BasenameNoExt => s += remove_extension(basename(&path)),216- NoExt => s += remove_extension(&path),217- Parent => s += dirname(&path),218- Placeholder => s += &path,219- Text(ref string) => s += string,212+ Basename => s.push(basename(path.as_ref())),213+ BasenameNoExt => {214+ s.push(remove_extension(&PathBuf::from(basename(path.as_ref()))))215+ }216+ NoExt => s.push(remove_extension(path.as_ref())),217+ Parent => s.push(dirname(path.as_ref())),218+ Placeholder => s.push(path.as_ref()),219+ Text(ref string) => s.push(string),220 }221 }222- Cow::Owned(s)222+ s223 }224- ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),224+ ArgumentTemplate::Text(ref text) => OsString::from(text),225 }226 }227 }228 112 unmodified linesmodified:src/main.rs+12 added-4 removed
36 unmodified lines37 fn run() -> Result<ExitCode> {38 let matches = app::build_app().get_matches_from(env::args_os());39 40 // Set the current working directory of the process41- if let Some(base_directory) = matches.value_of("base-directory") {41+ if let Some(base_directory) = matches.value_of_os("base-directory") {42 let base_directory = Path::new(base_directory);43 if !filesystem::is_dir(base_directory) {44 return Err(anyhow!(45 "The '--base-directory' path '{}' is not a directory.",15 unmodified lines61 ));62 }63 64 // Get the search pattern65- let pattern = matches.value_of("pattern").unwrap_or("");65+ let pattern = matches66+ .value_of_os("pattern")67+ .map(|p| {68+ p.to_str().ok_or(anyhow!(69+ "The search pattern includes invalid UTF-8 sequences."70+ ))71+ })72+ .transpose()?73+ .unwrap_or("");74 75 // Get one or more root directories to search.76 let mut dir_vec: Vec<_> = match matches69- .values_of("path")70- .or_else(|| matches.values_of("search-path"))77+ .values_of_os("path")78+ .or_else(|| matches.values_of_os("search-path"))79 {80 Some(paths) => paths81 .map(|path| {82 let path_buffer = PathBuf::from(path);244 unmodified lines