Skip to content
Myr

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

3 files+262 added−139 removed

added:src/exec/input.rs+250 added
1use std::path::MAIN_SEPARATOR;2use std::borrow::Cow;34#[cfg(windows)]5const ESCAPE: char = '^';67#[cfg(not(windows))]8const ESCAPE: char = '\\';910/// 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.15pub struct Input<'a> {16 data: &'a str,17}1819impl<'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 }2526 /// 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 }3435 if index != 0 {36 self.data = &self.data[index + 1..]37 }3839 self40 }4142 /// 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;4647 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 }5556 // Account for hidden files and directories57 if ext_index != 0 && dir_index + 2 <= ext_index {58 self.data = &self.data[0..ext_index];59 }6061 self62 }6364 /// 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 }7273 self.data = if index == 0 {74 "."75 } else {76 &self.data[0..index]77 };7879 self80 }8182 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 };108109 // 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 };115116 // 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);121122 // 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..];125126 // 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 }134135 // Finally, we return our newly-allocated input string.136 owned.push_str(slice);137 Cow::Owned(owned)138 }139}140141#[cfg(test)]142mod tests {143 use super::{MAIN_SEPARATOR, Input};144145 fn correct(input: &str) -> String {146 let mut sep = String::new();147 sep.push(MAIN_SEPARATOR);148 input.replace('/', &sep)149 }150151 #[test]152 fn path_remove_ext_simple() {153 assert_eq!(&Input::new("foo.txt").remove_extension().get(), "foo");154 }155156 #[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 }163164 #[test]165 fn path_hidden() {166 assert_eq!(&Input::new(".foo").remove_extension().get(), ".foo")167 }168169 #[test]170 fn path_remove_ext_utf8() {171 assert_eq!(&Input::new("💖.txt").remove_extension().get(), "💖");172 }173174 #[test]175 fn path_remove_ext_empty() {176 assert_eq!(&Input::new("").remove_extension().get(), "");177 }178179 #[test]180 fn path_basename_simple() {181 assert_eq!(&Input::new("foo.txt").basename().get(), "foo.txt");182 }183184 #[test]185 fn path_basename_dir() {186 assert_eq!(187 &Input::new(&correct("dir/foo.txt")).basename().get(),188 "foo.txt"189 );190 }191192 #[test]193 fn path_basename_empty() {194 assert_eq!(&Input::new("").basename().get(), "");195 }196197 #[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 }208209 #[test]210 fn path_dirname_simple() {211 assert_eq!(&Input::new("foo.txt").dirname().get(), ".");212 }213214 #[test]215 fn path_dirname_dir() {216 assert_eq!(&Input::new(&correct("dir/foo.txt")).dirname().get(), "dir");217 }218219 #[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 }227228 #[test]229 fn path_dirname_empty() {230 assert_eq!(&Input::new("").dirname().get(), ".");231 }232233 #[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 }241242 #[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.2mod ticket;3mod token;4mod job;5mod paths;5mod input;67use std::path::Path;8use std::sync::{Arc, Mutex};910use self::paths::{basename, dirname, remove_extension};10// use self::paths::{basename, dirname, remove_extension};11use self::input::Input;12use self::ticket::CommandTicket;13use self::token::Token;14pub use self::job::job;15
93 unmodified lines
109 command: &'a mut String,110 input: &Path,111 out_perm: Arc<Mutex<()>>,112 ) -> CommandTicket<'a> {112 let input = input.strip_prefix(".").unwrap_or(input);113113 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 }127128 CommandTicket::new(command, out_perm)
38 unmodified lines
deleted:src/exec/paths.rs-128 removed
1use std::path::MAIN_SEPARATOR;23pub 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}1617/// Removes the extension of a given input18pub fn remove_extension(input: &str) -> &str {19 let mut dir_index = 0;20 let mut ext_index = 0;2122 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 }3031 // 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}3839pub 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}4849#[cfg(test)]50mod tests {51 use super::*;5253 fn correct(input: &str) -> String {54 let mut sep = String::new();55 sep.push(MAIN_SEPARATOR);56 input.replace('/', &sep)57 }5859 #[test]60 fn path_remove_ext_simple() {61 assert_eq!(remove_extension("foo.txt"), "foo");62 }6364 #[test]65 fn path_remove_ext_dir() {66 assert_eq!(67 remove_extension(&correct("dir/foo.txt")),68 &correct("dir/foo")69 );70 }7172 #[test]73 fn path_hidden() {74 assert_eq!(remove_extension(".foo"), ".foo")75 }7677 #[test]78 fn path_remove_ext_utf8() {79 assert_eq!(remove_extension("💖.txt"), "💖");80 }8182 #[test]83 fn path_remove_ext_empty() {84 assert_eq!(remove_extension(""), "");85 }8687 #[test]88 fn path_basename_simple() {89 assert_eq!(basename("foo.txt"), "foo.txt");90 }9192 #[test]93 fn path_basename_dir() {94 assert_eq!(basename(&correct("dir/foo.txt")), "foo.txt");95 }9697 #[test]98 fn path_basename_empty() {99 assert_eq!(basename(""), "");100 }101102 #[test]103 fn path_basename_utf8() {104 assert_eq!(basename(&correct("💖/foo.txt")), "foo.txt");105 assert_eq!(basename(&correct("dir/💖.txt")), "💖.txt");106 }107108 #[test]109 fn path_dirname_simple() {110 assert_eq!(dirname("foo.txt"), ".");111 }112113 #[test]114 fn path_dirname_dir() {115 assert_eq!(dirname(&correct("dir/foo.txt")), "dir");116 }117118 #[test]119 fn path_dirname_utf8() {120 assert_eq!(dirname(&correct("💖/foo.txt")), "💖");121 assert_eq!(dirname(&correct("dir/💖.txt")), "dir");122 }123124 #[test]125 fn path_dirname_empty() {126 assert_eq!(dirname(""), ".");127 }128}