mod.rs
This file
Path
src/exec/mod.rs
220 lines · 6.6 KiB · Rust
Last changed by
Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
History of this fileTake it
1// Copyright (c) 2017 fd developers2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.89// TODO: Possible optimization could avoid pushing characters on a buffer.10mod command;11mod input;12mod job;13mod token;1415use std::borrow::Cow;16use std::path::Path;17use std::process::Command;18use std::sync::{Arc, Mutex};1920use regex::Regex;2122use self::command::execute_command;23use self::input::{basename, dirname, remove_extension};24pub use self::job::job;25use self::token::Token;2627/// Represents a template that is utilized to generate command strings.28///29/// The template is meant to be coupled with an input in order to generate a command. The30/// `generate_and_execute()` method will be used to generate a command and execute it.31#[derive(Debug, Clone, PartialEq)]32pub struct CommandTemplate {33 args: Vec<ArgumentTemplate>,34}3536impl CommandTemplate {37 pub fn new<I, S>(input: I) -> CommandTemplate38 where39 I: IntoIterator<Item = S>,40 S: AsRef<str>,41 {42 lazy_static! {43 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();44 }4546 let mut args = Vec::new();47 let mut has_placeholder = false;4849 for arg in input {50 let arg = arg.as_ref();5152 let mut tokens = Vec::new();53 let mut start = 0;5455 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {56 // Leading text before the placeholder.57 if placeholder.start() > start {58 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));59 }6061 start = placeholder.end();6263 match placeholder.as_str() {64 "{}" => tokens.push(Token::Placeholder),65 "{.}" => tokens.push(Token::NoExt),66 "{/}" => tokens.push(Token::Basename),67 "{//}" => tokens.push(Token::Parent),68 "{/.}" => tokens.push(Token::BasenameNoExt),69 _ => panic!("Unhandled placeholder"),70 }7172 has_placeholder = true;73 }7475 // Without a placeholder, the argument is just fixed text.76 if tokens.is_empty() {77 args.push(ArgumentTemplate::Text(arg.to_owned()));78 continue;79 }8081 if start < arg.len() {82 // Trailing text after last placeholder.83 tokens.push(Token::Text(arg[start..].to_owned()));84 }8586 args.push(ArgumentTemplate::Tokens(tokens));87 }8889 // If a placeholder token was not supplied, append one at the end of the command.90 if !has_placeholder {91 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));92 }9394 CommandTemplate { args: args }95 }9697 /// Generates and executes a command.98 ///99 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be100 /// build. Once all arguments have been processed, the command is executed.101 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) {102 let input = input103 .strip_prefix(".")104 .unwrap_or(input)105 .to_string_lossy()106 .into_owned();107108 let mut cmd = Command::new(self.args[0].generate(&input).as_ref());109 for arg in &self.args[1..] {110 cmd.arg(arg.generate(&input).as_ref());111 }112113 execute_command(cmd, out_perm)114 }115}116117/// Represents a template for a single command argument.118///119/// The argument is either a collection of `Token`s including at least one placeholder variant, or120/// a fixed text.121#[derive(Clone, Debug, PartialEq)]122enum ArgumentTemplate {123 Tokens(Vec<Token>),124 Text(String),125}126127impl ArgumentTemplate {128 pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {129 use self::Token::*;130131 match *self {132 ArgumentTemplate::Tokens(ref tokens) => {133 let mut s = String::new();134 for token in tokens {135 match *token {136 Basename => s += basename(path),137 BasenameNoExt => s += remove_extension(basename(path)),138 NoExt => s += remove_extension(path),139 Parent => s += dirname(path),140 Placeholder => s += path,141 Text(ref string) => s += string,142 }143 }144 Cow::Owned(s)145 }146 ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),147 }148 }149}150151#[cfg(test)]152mod tests {153 use super::*;154155 #[test]156 fn tokens_with_placeholder() {157 assert_eq!(158 CommandTemplate::new(&[&"echo", &"${SHELL}:"]),159 CommandTemplate {160 args: vec![161 ArgumentTemplate::Text("echo".into()),162 ArgumentTemplate::Text("${SHELL}:".into()),163 ArgumentTemplate::Tokens(vec![Token::Placeholder]),164 ],165 }166 );167 }168169 #[test]170 fn tokens_with_no_extension() {171 assert_eq!(172 CommandTemplate::new(&["echo", "{.}"]),173 CommandTemplate {174 args: vec![175 ArgumentTemplate::Text("echo".into()),176 ArgumentTemplate::Tokens(vec![Token::NoExt]),177 ],178 }179 );180 }181182 #[test]183 fn tokens_with_basename() {184 assert_eq!(185 CommandTemplate::new(&["echo", "{/}"]),186 CommandTemplate {187 args: vec![188 ArgumentTemplate::Text("echo".into()),189 ArgumentTemplate::Tokens(vec![Token::Basename]),190 ],191 }192 );193 }194195 #[test]196 fn tokens_with_parent() {197 assert_eq!(198 CommandTemplate::new(&["echo", "{//}"]),199 CommandTemplate {200 args: vec![201 ArgumentTemplate::Text("echo".into()),202 ArgumentTemplate::Tokens(vec![Token::Parent]),203 ],204 }205 );206 }207208 #[test]209 fn tokens_with_basename_no_extension() {210 assert_eq!(211 CommandTemplate::new(&["echo", "{/.}"]),212 CommandTemplate {213 args: vec![214 ArgumentTemplate::Text("echo".into()),215 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),216 ],217 }218 );219 }220}