Escape exec Inputs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michael Aaron Murphy · committed by David Peter · parent 200dfaa · Browse files · 3 files·+262 added−139 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+262 added−139 removed
- other:+262 added−139 removed
Provenance
- Commit
6a01faf- Tree
934e580- Author
Michael Aaron Murphy <mmstickman@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
200dfaa
3 files changed+262 added−139 removed
added:src/exec/input.rs+250 added
1+use std::path::MAIN_SEPARATOR;2+use std::borrow::Cow;3+4+#[cfg(windows)]5+const ESCAPE: char = '^';6+7+#[cfg(not(windows))]8+const ESCAPE: char = '\\';9+10+/// A builder for efficiently generating input strings.11+///12+/// After choosing your required specs, the `get()` method will escape special characters found13+/// in the input. Allocations will only occur if special characters are found that need to be14+/// escaped.15+pub struct Input<'a> {16+ data: &'a str,17+}18+19+impl<'a> Input<'a> {20+ /// Creates a new `Input` structure, which provides access to command-building21+ /// primitives, such as `basename()` and `dirname()`.22+ pub fn new(data: &'a str) -> Input<'a> {23+ Input { data }24+ }25+26+ /// Removes the parent component of the path27+ pub fn basename(&'a mut self) -> &'a mut Self {28+ let mut index = 0;29+ for (id, character) in self.data.char_indices() {30+ if character == MAIN_SEPARATOR {31+ index = id;32+ }33+ }34+35+ if index != 0 {36+ self.data = &self.data[index + 1..]37+ }38+39+ self40+ }41+42+ /// Removes the extension from the path43+ pub fn remove_extension(&'a mut self) -> &'a mut Self {44+ let mut dir_index = 0;45+ let mut ext_index = 0;46+47+ for (id, character) in self.data.char_indices() {48+ if character == MAIN_SEPARATOR {49+ dir_index = id;50+ }51+ if character == '.' {52+ ext_index = id;53+ }54+ }55+56+ // Account for hidden files and directories57+ if ext_index != 0 && dir_index + 2 <= ext_index {58+ self.data = &self.data[0..ext_index];59+ }60+61+ self62+ }63+64+ /// Removes the basename from the path.65+ pub fn dirname(&'a mut self) -> &'a mut Self {66+ let mut index = 0;67+ for (id, character) in self.data.char_indices() {68+ if character == MAIN_SEPARATOR {69+ index = id;70+ }71+ }72+73+ self.data = if index == 0 {74+ "."75+ } else {76+ &self.data[0..index]77+ };78+79+ self80+ }81+82+ pub fn get(&'a self) -> Cow<'a, str> {83+ fn char_is_quotable(x: char) -> bool {84+ [85+ ' ',86+ '(',87+ ')',88+ '[',89+ ']',90+ '&',91+ '$',92+ '@',93+ '{',94+ '}',95+ '<',96+ '>',97+ '|',98+ ';',99+ '"',100+ '\'',101+ '#',102+ '*',103+ '%',104+ '?',105+ '`',106+ ].contains(&x)107+ };108+109+ // If a quotable character is found, we will use that position for allocating.110+ let pos = match self.data.find(char_is_quotable) {111+ Some(pos) => pos,112+ // Otherwise, we will return the contents of `data` without allocating.113+ None => return Cow::Borrowed(self.data),114+ };115+116+ // When building the input string, we will start by adding the characters that117+ // we've already verified to be free of special characters.118+ let mut owned = String::with_capacity(self.data.len());119+ owned.push_str(&self.data[..pos]);120+ owned.push(ESCAPE);121+122+ // This slice contains the data that is left to be scanned for special characters.123+ // If multiple characters are found, this slice will be sliced and updated multiple times.124+ let mut slice = &self.data[pos..];125+126+ // Repeatedly search for special characters until all special characters have been found,127+ // appending and inserting the escape character each time, as well as updating our128+ // starting position.129+ while let Some(pos) = slice[1..].find(char_is_quotable) {130+ owned.push_str(&slice[..pos + 1]);131+ owned.push(ESCAPE);132+ slice = &slice[pos + 1..];133+ }134+135+ // Finally, we return our newly-allocated input string.136+ owned.push_str(slice);137+ Cow::Owned(owned)138+ }139+}140+141+#[cfg(test)]142+mod tests {143+ use super::{MAIN_SEPARATOR, Input};144+145+ fn correct(input: &str) -> String {146+ let mut sep = String::new();147+ sep.push(MAIN_SEPARATOR);148+ input.replace('/', &sep)149+ }150+151+ #[test]152+ fn path_remove_ext_simple() {153+ assert_eq!(&Input::new("foo.txt").remove_extension().get(), "foo");154+ }155+156+ #[test]157+ fn path_remove_ext_dir() {158+ assert_eq!(159+ &Input::new(&correct("dir/foo.txt")).remove_extension().get(),160+ &correct("dir/foo")161+ );162+ }163+164+ #[test]165+ fn path_hidden() {166+ assert_eq!(&Input::new(".foo").remove_extension().get(), ".foo")167+ }168+169+ #[test]170+ fn path_remove_ext_utf8() {171+ assert_eq!(&Input::new("💖.txt").remove_extension().get(), "💖");172+ }173+174+ #[test]175+ fn path_remove_ext_empty() {176+ assert_eq!(&Input::new("").remove_extension().get(), "");177+ }178+179+ #[test]180+ fn path_basename_simple() {181+ assert_eq!(&Input::new("foo.txt").basename().get(), "foo.txt");182+ }183+184+ #[test]185+ fn path_basename_dir() {186+ assert_eq!(187+ &Input::new(&correct("dir/foo.txt")).basename().get(),188+ "foo.txt"189+ );190+ }191+192+ #[test]193+ fn path_basename_empty() {194+ assert_eq!(&Input::new("").basename().get(), "");195+ }196+197+ #[test]198+ fn path_basename_utf8() {199+ assert_eq!(200+ &Input::new(&correct("💖/foo.txt")).basename().get(),201+ "foo.txt"202+ );203+ assert_eq!(204+ &Input::new(&correct("dir/💖.txt")).basename().get(),205+ "💖.txt"206+ );207+ }208+209+ #[test]210+ fn path_dirname_simple() {211+ assert_eq!(&Input::new("foo.txt").dirname().get(), ".");212+ }213+214+ #[test]215+ fn path_dirname_dir() {216+ assert_eq!(&Input::new(&correct("dir/foo.txt")).dirname().get(), "dir");217+ }218+219+ #[test]220+ fn path_dirname_utf8() {221+ assert_eq!(222+ &Input::new(&correct("💖/foo.txt")).dirname().get(),223+ "💖"224+ );225+ assert_eq!(&Input::new(&correct("dir/💖.txt")).dirname().get(), "dir");226+ }227+228+ #[test]229+ fn path_dirname_empty() {230+ assert_eq!(&Input::new("").dirname().get(), ".");231+ }232+233+ #[cfg(windows)]234+ #[test]235+ fn path_special_chars() {236+ assert_eq!(237+ &Input::new("A Directory\\And A File").get(),238+ "A^ Directory\\And^ A^ File"239+ );240+ }241+242+ #[cfg(not(windows))]243+ #[test]244+ fn path_special_chars() {245+ assert_eq!(246+ &Input::new("A Directory/And A File").get(),247+ "A\\ Directory/And\\ A\\ File"248+ );249+ }250+}modified:src/exec/mod.rs+12 added-11 removed
1 // TODO: Possible optimization could avoid pushing characters on a buffer.2 mod ticket;3 mod token;4 mod job;5-mod paths;5+mod input;6 7 use std::path::Path;8 use std::sync::{Arc, Mutex};9 10-use self::paths::{basename, dirname, remove_extension};10+// use self::paths::{basename, dirname, remove_extension};11+use self::input::Input;12 use self::ticket::CommandTicket;13 use self::token::Token;14 pub use self::job::job;15 93 unmodified lines109 command: &'a mut String,110 input: &Path,111 out_perm: Arc<Mutex<()>>,112 ) -> CommandTicket<'a> {112- let input = input.strip_prefix(".").unwrap_or(input);113-113+ use self::Token::*;114+ let input = input.strip_prefix(".").unwrap_or(input).to_string_lossy();115 for token in &self.tokens {116 match *token {116- Token::Basename => *command += basename(&input.to_string_lossy()),117- Token::BasenameNoExt => {118- *command += remove_extension(basename(&input.to_string_lossy()))117+ Basename => *command += &Input::new(&input).basename().get(),118+ BasenameNoExt => {119+ *command += &Input::new(&input).basename().remove_extension().get()120 }120- Token::NoExt => *command += remove_extension(&input.to_string_lossy()),121- Token::Parent => *command += dirname(&input.to_string_lossy()),122- Token::Placeholder => *command += &input.to_string_lossy(),123- Token::Text(ref string) => *command += string,121+ NoExt => *command += &Input::new(&input).remove_extension().get(),122+ Parent => *command += &Input::new(&input).dirname().get(),123+ Placeholder => *command += &Input::new(&input).get(),124+ Text(ref string) => *command += string,125 }126 }127 128 CommandTicket::new(command, out_perm)38 unmodified linesdeleted:src/exec/paths.rs-128 removed
1-use std::path::MAIN_SEPARATOR;2-3-pub fn basename(input: &str) -> &str {4- let mut index = 0;5- for (id, character) in input.char_indices() {6- if character == MAIN_SEPARATOR {7- index = id;8- }9- }10- if index == 0 {11- input12- } else {13- &input[index + 1..]14- }15-}16-17-/// Removes the extension of a given input18-pub fn remove_extension(input: &str) -> &str {19- let mut dir_index = 0;20- let mut ext_index = 0;21-22- for (id, character) in input.char_indices() {23- if character == MAIN_SEPARATOR {24- dir_index = id;25- }26- if character == '.' {27- ext_index = id;28- }29- }30-31- // Account for hidden files and directories32- if ext_index == 0 || dir_index + 2 > ext_index {33- input34- } else {35- &input[0..ext_index]36- }37-}38-39-pub fn dirname(input: &str) -> &str {40- let mut index = 0;41- for (id, character) in input.char_indices() {42- if character == MAIN_SEPARATOR {43- index = id;44- }45- }46- if index == 0 { "." } else { &input[0..index] }47-}48-49-#[cfg(test)]50-mod tests {51- use super::*;52-53- fn correct(input: &str) -> String {54- let mut sep = String::new();55- sep.push(MAIN_SEPARATOR);56- input.replace('/', &sep)57- }58-59- #[test]60- fn path_remove_ext_simple() {61- assert_eq!(remove_extension("foo.txt"), "foo");62- }63-64- #[test]65- fn path_remove_ext_dir() {66- assert_eq!(67- remove_extension(&correct("dir/foo.txt")),68- &correct("dir/foo")69- );70- }71-72- #[test]73- fn path_hidden() {74- assert_eq!(remove_extension(".foo"), ".foo")75- }76-77- #[test]78- fn path_remove_ext_utf8() {79- assert_eq!(remove_extension("💖.txt"), "💖");80- }81-82- #[test]83- fn path_remove_ext_empty() {84- assert_eq!(remove_extension(""), "");85- }86-87- #[test]88- fn path_basename_simple() {89- assert_eq!(basename("foo.txt"), "foo.txt");90- }91-92- #[test]93- fn path_basename_dir() {94- assert_eq!(basename(&correct("dir/foo.txt")), "foo.txt");95- }96-97- #[test]98- fn path_basename_empty() {99- assert_eq!(basename(""), "");100- }101-102- #[test]103- fn path_basename_utf8() {104- assert_eq!(basename(&correct("💖/foo.txt")), "foo.txt");105- assert_eq!(basename(&correct("dir/💖.txt")), "💖.txt");106- }107-108- #[test]109- fn path_dirname_simple() {110- assert_eq!(dirname("foo.txt"), ".");111- }112-113- #[test]114- fn path_dirname_dir() {115- assert_eq!(dirname(&correct("dir/foo.txt")), "dir");116- }117-118- #[test]119- fn path_dirname_utf8() {120- assert_eq!(dirname(&correct("💖/foo.txt")), "💖");121- assert_eq!(dirname(&correct("dir/💖.txt")), "dir");122- }123-124- #[test]125- fn path_dirname_empty() {126- assert_eq!(dirname(""), ".");127- }128-}