Remove CommandTicket to avoid Vec allocation
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Matthias Reitinger · committed by David Peter · parent bc88b8f · Browse files · 4 files·+114 added−142 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+114 added−142 removed
- other:+114 added−142 removed
Provenance
- Commit
c18caaa- Tree
28fe1d7- Author
Matthias Reitinger <reima@edenprime.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
bc88b8f
4 files changed+114 added−142 removed
added:src/exec/command.rs+98 added
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.8+9+use std::process::Command;10+use std::sync::{Arc, Mutex};11+use std::io;12+13+/// Executes a command.14+#[cfg(not(unix))]15+pub fn execute_command(mut cmd: Command, out_perm: Arc<Mutex<()>>) {16+ use std::process::Stdio;17+ use std::io::Write;18+19+ // Spawn the supplied command.20+ let output = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output();21+22+ // Then wait for the command to exit, if it was spawned.23+ match output {24+ Ok(output) => {25+ // While this lock is active, this thread will be the only thread allowed26+ // to write it's outputs.27+ let _lock = out_perm.lock().unwrap();28+29+ let stdout = io::stdout();30+ let stderr = io::stderr();31+32+ let _ = stdout.lock().write_all(&output.stdout);33+ let _ = stderr.lock().write_all(&output.stderr);34+ }35+ Err(why) => eprintln!("fd: exec error: {}", why),36+ }37+}38+39+/// Executes a command.40+#[cfg(all(unix))]41+pub fn execute_command(mut cmd: Command, out_perm: Arc<Mutex<()>>) {42+ use libc::{close, dup2, pipe, STDERR_FILENO, STDOUT_FILENO};43+ use std::fs::File;44+ use std::os::unix::process::CommandExt;45+ use std::os::unix::io::FromRawFd;46+47+ // Initial a pair of pipes that will be used to48+ // pipe the std{out,err} of the spawned process.49+ let mut stdout_fds = [0; 2];50+ let mut stderr_fds = [0; 2];51+52+ unsafe {53+ pipe(stdout_fds.as_mut_ptr());54+ pipe(stderr_fds.as_mut_ptr());55+ }56+57+ // Configure the pipes accordingly in the child.58+ let child = cmd.before_exec(move || unsafe {59+ // Redirect the child's std{out,err} to the write ends of our pipe.60+ dup2(stdout_fds[1], STDOUT_FILENO);61+ dup2(stderr_fds[1], STDERR_FILENO);62+63+ // Close all the fds we created here, so EOF will be sent when the program exits.64+ close(stdout_fds[0]);65+ close(stdout_fds[1]);66+ close(stderr_fds[0]);67+ close(stderr_fds[1]);68+ Ok(())69+ }).spawn();70+71+ // Open the read end of the pipes as `File`s.72+ let (mut pout, mut perr) = unsafe {73+ // Close the write ends of the pipes in the parent74+ close(stdout_fds[1]);75+ close(stderr_fds[1]);76+ (77+ // But create files from the read ends.78+ File::from_raw_fd(stdout_fds[0]),79+ File::from_raw_fd(stderr_fds[0]),80+ )81+ };82+83+ match child {84+ Ok(mut child) => {85+ let _ = child.wait();86+87+ // Create a lock to ensure that this thread has exclusive access to writing.88+ let _lock = self.out_perm.lock().unwrap();89+90+ // And then write the outputs of the process until EOF is sent to each file.91+ let stdout = io::stdout();92+ let stderr = io::stderr();93+ let _ = io::copy(&mut pout, &mut stdout.lock());94+ let _ = io::copy(&mut perr, &mut stderr.lock());95+ }96+ Err(why) => eprintln!("fd: exec error: {}", why),97+ }98+}modified:src/exec/job.rs+1 added-1 removed
32 unmodified lines33 34 // Drop the lock so that other threads can read from the the receiver.35 drop(lock);36 // Generate a command and execute it.37- cmd.generate(&value, Arc::clone(&out_perm)).then_execute();37+ cmd.generate_and_execute(&value, Arc::clone(&out_perm));38 }39 }modified:src/exec/mod.rs+15 added-15 removed
5 unmodified lines6 // notice may not be copied, modified, or distributed except7 // according to those terms.8 9 // TODO: Possible optimization could avoid pushing characters on a buffer.10-mod ticket;10+mod command;11 mod token;12 mod job;13 mod input;14 15 use std::borrow::Cow;16 use std::path::Path;17+use std::process::Command;18 use std::sync::{Arc, Mutex};19 20 use regex::Regex;21 22 use self::input::{basename, dirname, remove_extension};22-use self::ticket::CommandTicket;23+use self::command::execute_command;24 use self::token::Token;25 pub use self::job::job;26 27 /// Contains a collection of `TokenizedArgument`s that are utilized to generate command strings.28 ///29 /// The arguments are a representation of the supplied command template, and are meant to be coupled29-/// with an input in order to generate a command. The `generate()` method will be used to generate30-/// a command and obtain a ticket for executing that command.30+/// with an input in order to generate a command. The `generate_and_execute()` method will be used31+/// to generate a command and execute it.32 #[derive(Debug, Clone, PartialEq)]33 pub struct TokenizedCommand {34 args: Vec<TokenizedArgument>,35 }38 unmodified lines74 I: IntoIterator<Item = S>,75 S: AsRef<str>,76 {77 lazy_static! {77- static ref PLACEHOLDER: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();78+ static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();79 }80 81 let mut args = Vec::new();82 let mut has_placeholder = false;3 unmodified lines86 87 let mut tokens = Vec::new();88 let mut start = 0;89 89- for placeholder in PLACEHOLDER.find_iter(arg) {90+ for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {91 // Leading text before the placeholder.92 if placeholder.start() > start {93 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));94 }33 unmodified lines128 129 TokenizedCommand { args: args }130 }131 131- /// Generates a ticket that is required to execute the generated command.132+ /// Generates and executes a command.133 ///133- /// Using the internal `args` field, and a supplied `input` variable, arguments will be134- /// collected in a Vec. Once all arguments have been processed, the Vec will be wrapped135- /// within a `CommandTicket`, which will be responsible for executing the command.136- pub fn generate(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> CommandTicket {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.136+ pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) {137 let input = input138 .strip_prefix(".")139 .unwrap_or(input)140 .to_string_lossy()141 .into_owned();142 143- let mut args = Vec::with_capacity(self.args.len());144- for arg in &self.args {145- args.push(arg.generate(&input));143+ let mut cmd = Command::new(self.args[0].generate(&input).as_ref());144+ for arg in &self.args[1..] {145+ cmd.arg(arg.generate(&input).as_ref());146 }147 148- CommandTicket::new(args, out_perm)148+ execute_command(cmd, out_perm)149 }150 }151 152 #[cfg(test)]26 unmodified linesdeleted:src/exec/ticket.rs-126 removed
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.8-9-use std::process::Command;10-use std::sync::{Arc, Mutex};11-use std::io;12-13-/// A state that offers access to executing a generated command.14-///15-/// The ticket holds the collection of arguments of a command to be executed.16-pub struct CommandTicket {17- args: Vec<String>,18- out_perm: Arc<Mutex<()>>,19-}20-21-impl CommandTicket {22- pub fn new<I, S>(args: I, out_perm: Arc<Mutex<()>>) -> CommandTicket23- where24- I: IntoIterator<Item = S>,25- S: AsRef<str>,26- {27- CommandTicket {28- args: args.into_iter().map(|x| x.as_ref().to_owned()).collect(),29- out_perm: out_perm,30- }31- }32-33- /// Executes the command stored within the ticket.34- #[cfg(not(unix))]35- pub fn then_execute(self) {36- use std::process::Stdio;37- use std::io::Write;38-39- // Spawn the supplied command.40- let cmd = Command::new(&self.args[0])41- .args(&self.args[1..])42- .stdout(Stdio::piped())43- .stderr(Stdio::piped())44- .output();45-46- // Then wait for the command to exit, if it was spawned.47- match cmd {48- Ok(output) => {49- // While this lock is active, this thread will be the only thread allowed50- // to write it's outputs.51- let _lock = self.out_perm.lock().unwrap();52-53- let stdout = io::stdout();54- let stderr = io::stderr();55-56- let _ = stdout.lock().write_all(&output.stdout);57- let _ = stderr.lock().write_all(&output.stderr);58- }59- Err(why) => eprintln!("fd: exec error: {}", why),60- }61- }62-63- #[cfg(all(unix))]64- pub fn then_execute(self) {65- use libc::{close, dup2, pipe, STDERR_FILENO, STDOUT_FILENO};66- use std::fs::File;67- use std::os::unix::process::CommandExt;68- use std::os::unix::io::FromRawFd;69-70- // Initial a pair of pipes that will be used to71- // pipe the std{out,err} of the spawned process.72- let mut stdout_fds = [0; 2];73- let mut stderr_fds = [0; 2];74-75- unsafe {76- pipe(stdout_fds.as_mut_ptr());77- pipe(stderr_fds.as_mut_ptr());78- }79-80- // Spawn the supplied command.81- let cmd = Command::new(&self.args[0])82- .args(&self.args[1..])83- // Configure the pipes accordingly in the child.84- .before_exec(move || unsafe {85- // Redirect the child's std{out,err} to the write ends of our pipe.86- dup2(stdout_fds[1], STDOUT_FILENO);87- dup2(stderr_fds[1], STDERR_FILENO);88-89- // Close all the fds we created here, so EOF will be sent when the program exits.90- close(stdout_fds[0]);91- close(stdout_fds[1]);92- close(stderr_fds[0]);93- close(stderr_fds[1]);94- Ok(())95- })96- .spawn();97-98- // Open the read end of the pipes as `File`s.99- let (mut pout, mut perr) = unsafe {100- // Close the write ends of the pipes in the parent101- close(stdout_fds[1]);102- close(stderr_fds[1]);103- (104- // But create files from the read ends.105- File::from_raw_fd(stdout_fds[0]),106- File::from_raw_fd(stderr_fds[0]),107- )108- };109-110- match cmd {111- Ok(mut child) => {112- let _ = child.wait();113-114- // Create a lock to ensure that this thread has exclusive access to writing.115- let _lock = self.out_perm.lock().unwrap();116-117- // And then write the outputs of the process until EOF is sent to each file.118- let stdout = io::stdout();119- let stderr = io::stderr();120- let _ = io::copy(&mut pout, &mut stdout.lock());121- let _ = io::copy(&mut perr, &mut stderr.lock());122- }123- Err(why) => eprintln!("fd: exec error: {}", why),124- }125- }126-}