Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

340 lines · 10.0 KiB · Rust

Last changed by

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

History of this file

Take it

The walk stopped after 200 commits: lines older than 8cfdcf4 point at it.

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 1–5why, one step back
1mod command;
2mod input;3mod job;4mod token;5

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 6why, one step back
6use std::ffi::OsString;

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 7–10why, one step back
7use std::path::{Path, PathBuf};
8use std::process::{Command, Stdio};9use std::sync::{Arc, Mutex};10

Proper error handling in main.rssharkdpbefore adoptionbce9527

line 11why, one step back
11use anyhow::{anyhow, Result};

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 12–14why, one step back
12use lazy_static::lazy_static;
13use regex::Regex;14

Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd

line 15why, one step back
15use crate::exit_codes::ExitCode;

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

line 16why, one step back
16use crate::filesystem::strip_current_dir;

Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd

line 17why, one step back
17

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 18–50why, one step back
18use self::command::execute_command;
19use self::input::{basename, dirname, remove_extension};20pub use self::job::{batch, job};21use self::token::Token;2223/// Execution mode of the command24#[derive(Debug, Clone, Copy, PartialEq)]25pub enum ExecutionMode {26 /// Command is executed for each search result27 OneByOne,28 /// Command is run for a batch of results at once29 Batch,30}3132/// Represents a template that is utilized to generate command strings.33///34/// The template is meant to be coupled with an input in order to generate a command. The35/// `generate_and_execute()` method will be used to generate a command and execute it.36#[derive(Debug, Clone, PartialEq)]37pub struct CommandTemplate {38 args: Vec<ArgumentTemplate>,39 mode: ExecutionMode,40}4142impl CommandTemplate {43 pub fn new<I, S>(input: I) -> CommandTemplate44 where45 I: IntoIterator<Item = S>,46 S: AsRef<str>,47 {48 Self::build(input, ExecutionMode::OneByOne)49 }50

Proper error handling in main.rssharkdpbefore adoptionbce9527

line 51why, one step back
51 pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate>

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 52–57why, one step back
52 where
53 I: IntoIterator<Item = S>,54 S: AsRef<str>,55 {56 let cmd = Self::build(input, ExecutionMode::Batch);57 if cmd.number_of_tokens() > 1 {

Proper error handling in main.rssharkdpbefore adoptionbce9527

line 58why, one step back
58 return Err(anyhow!("Only one placeholder allowed for batch commands"));

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 59–60why, one step back
59 }
60 if cmd.args[0].has_tokens() {

Proper error handling in main.rssharkdpbefore adoptionbce9527

lines 61–63why, one step back
61 return Err(anyhow!(
62 "First argument of exec-batch is expected to be a fixed executable"63 ));

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 64–99why, one step back
64 }
65 Ok(cmd)66 }6768 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate69 where70 I: IntoIterator<Item = S>,71 S: AsRef<str>,72 {73 lazy_static! {74 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();75 }7677 let mut args = Vec::new();78 let mut has_placeholder = false;7980 for arg in input {81 let arg = arg.as_ref();8283 let mut tokens = Vec::new();84 let mut start = 0;8586 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {87 // Leading text before the placeholder.88 if placeholder.start() > start {89 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));90 }9192 start = placeholder.end();9394 match placeholder.as_str() {95 "{}" => tokens.push(Token::Placeholder),96 "{.}" => tokens.push(Token::NoExt),97 "{/}" => tokens.push(Token::Basename),98 "{//}" => tokens.push(Token::Parent),99 "{/.}" => tokens.push(Token::BasenameNoExt),

panic => unreachablesharkdpbefore adoption439548c

line 100why, one step back
100 _ => unreachable!("Unhandled placeholder"),

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 101–135why, one step back
101 }
102103 has_placeholder = true;104 }105106 // Without a placeholder, the argument is just fixed text.107 if tokens.is_empty() {108 args.push(ArgumentTemplate::Text(arg.to_owned()));109 continue;110 }111112 if start < arg.len() {113 // Trailing text after last placeholder.114 tokens.push(Token::Text(arg[start..].to_owned()));115 }116117 args.push(ArgumentTemplate::Tokens(tokens));118 }119120 // If a placeholder token was not supplied, append one at the end of the command.121 if !has_placeholder {122 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));123 }124125 CommandTemplate { args, mode }126 }127128 fn number_of_tokens(&self) -> usize {129 self.args.iter().filter(|arg| arg.has_tokens()).count()130 }131132 /// Generates and executes a command.133 ///134 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be135 /// build. Once all arguments have been processed, the command is executed.

Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492

line 136why, one step back
136 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> ExitCode {

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

line 137why, one step back
137 let input = strip_current_dir(input);

Lock stdout only oncesharkdpbefore adoption8cfdcf4

line 138why, one step back
138

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 139why, one step back
139 let mut cmd = Command::new(self.args[0].generate(&input));

Lock stdout only oncesharkdpbefore adoption8cfdcf4

line 140why, one step back
140 for arg in &self.args[1..] {

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 141why, one step back
141 cmd.arg(arg.generate(&input));

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 142–143why, one step back
142 }
143

Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492

line 144why, one step back
144 execute_command(cmd, &out_perm)

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 145–150why, one step back
145 }
146147 pub fn in_batch_mode(&self) -> bool {148 self.mode == ExecutionMode::Batch149 }150

Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd

line 151why, one step back
151 pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCode

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 152–154why, one step back
152 where
153 I: Iterator<Item = PathBuf>,154 {

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 155why, one step back
155 let mut cmd = Command::new(self.args[0].generate(""));

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 156–159why, one step back
156 cmd.stdin(Stdio::inherit());
157 cmd.stdout(Stdio::inherit());158 cmd.stderr(Stdio::inherit());159

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

line 160why, one step back
160 let mut paths: Vec<_> = paths.collect();

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 161–164why, one step back
161 let mut has_path = false;
162163 for arg in &self.args[1..] {164 if arg.has_tokens() {

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

lines 165–166why, one step back
165 paths.sort();
166

Lock stdout only oncesharkdpbefore adoption8cfdcf4

line 167why, one step back
167 // A single `Tokens` is expected

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

line 168why, one step back
168 // So we can directly consume the iterator once and for all

Lock stdout only oncesharkdpbefore adoption8cfdcf4

line 169why, one step back
169 for path in &mut paths {

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 170why, one step back
170 cmd.arg(arg.generate(strip_current_dir(path)));

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 171–173why, one step back
171 has_path = true;
172 }173 } else {

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 174why, one step back
174 cmd.arg(arg.generate(""));

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 175–178why, one step back
175 }
176 }177178 if has_path {

Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd

lines 179–181why, one step back
179 execute_command(cmd, &Mutex::new(()))
180 } else {181 ExitCode::Success

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 182–203why, one step back
182 }
183 }184}185186/// Represents a template for a single command argument.187///188/// The argument is either a collection of `Token`s including at least one placeholder variant, or189/// a fixed text.190#[derive(Clone, Debug, PartialEq)]191enum ArgumentTemplate {192 Tokens(Vec<Token>),193 Text(String),194}195196impl ArgumentTemplate {197 pub fn has_tokens(&self) -> bool {198 match self {199 ArgumentTemplate::Tokens(_) => true,200 _ => false,201 }202 }203

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

line 204why, one step back
204 pub fn generate(&self, path: impl AsRef<Path>) -> OsString {

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 205–208why, one step back
205 use self::Token::*;
206207 match *self {208 ArgumentTemplate::Tokens(ref tokens) => {

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 209why, one step back
209 let mut s = OsString::new();

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 210–211why, one step back
210 for token in tokens {
211 match *token {

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

lines 212–219why, one step back
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),

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 220–221why, one step back
220 }
221 }

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 222why, one step back
222 s

Lock stdout only oncesharkdpbefore adoption8cfdcf4

line 223why, one step back
223 }

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 224why, one step back
224 ArgumentTemplate::Text(ref text) => OsString::from(text),

Lock stdout only oncesharkdpbefore adoption8cfdcf4

lines 225–340why, one step back
225 }
226 }227}228229#[cfg(test)]230mod tests {231 use super::*;232233 #[test]234 fn tokens_with_placeholder() {235 assert_eq!(236 CommandTemplate::new(&[&"echo", &"${SHELL}:"]),237 CommandTemplate {238 args: vec![239 ArgumentTemplate::Text("echo".into()),240 ArgumentTemplate::Text("${SHELL}:".into()),241 ArgumentTemplate::Tokens(vec![Token::Placeholder]),242 ],243 mode: ExecutionMode::OneByOne,244 }245 );246 }247248 #[test]249 fn tokens_with_no_extension() {250 assert_eq!(251 CommandTemplate::new(&["echo", "{.}"]),252 CommandTemplate {253 args: vec![254 ArgumentTemplate::Text("echo".into()),255 ArgumentTemplate::Tokens(vec![Token::NoExt]),256 ],257 mode: ExecutionMode::OneByOne,258 }259 );260 }261262 #[test]263 fn tokens_with_basename() {264 assert_eq!(265 CommandTemplate::new(&["echo", "{/}"]),266 CommandTemplate {267 args: vec![268 ArgumentTemplate::Text("echo".into()),269 ArgumentTemplate::Tokens(vec![Token::Basename]),270 ],271 mode: ExecutionMode::OneByOne,272 }273 );274 }275276 #[test]277 fn tokens_with_parent() {278 assert_eq!(279 CommandTemplate::new(&["echo", "{//}"]),280 CommandTemplate {281 args: vec![282 ArgumentTemplate::Text("echo".into()),283 ArgumentTemplate::Tokens(vec![Token::Parent]),284 ],285 mode: ExecutionMode::OneByOne,286 }287 );288 }289290 #[test]291 fn tokens_with_basename_no_extension() {292 assert_eq!(293 CommandTemplate::new(&["echo", "{/.}"]),294 CommandTemplate {295 args: vec![296 ArgumentTemplate::Text("echo".into()),297 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),298 ],299 mode: ExecutionMode::OneByOne,300 }301 );302 }303304 #[test]305 fn tokens_multiple() {306 assert_eq!(307 CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),308 CommandTemplate {309 args: vec![310 ArgumentTemplate::Text("cp".into()),311 ArgumentTemplate::Tokens(vec![Token::Placeholder]),312 ArgumentTemplate::Tokens(vec![313 Token::BasenameNoExt,314 Token::Text(".ext".into())315 ]),316 ],317 mode: ExecutionMode::OneByOne,318 }319 );320 }321322 #[test]323 fn tokens_single_batch() {324 assert_eq!(325 CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),326 CommandTemplate {327 args: vec![328 ArgumentTemplate::Text("echo".into()),329 ArgumentTemplate::Tokens(vec![Token::NoExt]),330 ],331 mode: ExecutionMode::Batch,332 }333 );334 }335336 #[test]337 fn tokens_multiple_batch() {338 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());339 }340}