Skip to content
Myr

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

4 files+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.89use std::process::Command;10use std::sync::{Arc, Mutex};11use std::io;1213/// Executes a command.14#[cfg(not(unix))]15pub fn execute_command(mut cmd: Command, out_perm: Arc<Mutex<()>>) {16 use std::process::Stdio;17 use std::io::Write;1819 // Spawn the supplied command.20 let output = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output();2122 // 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();2829 let stdout = io::stdout();30 let stderr = io::stderr();3132 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}3839/// Executes a command.40#[cfg(all(unix))]41pub 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;4647 // 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];5152 unsafe {53 pipe(stdout_fds.as_mut_ptr());54 pipe(stderr_fds.as_mut_ptr());55 }5657 // 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);6263 // 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();7071 // 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 };8283 match child {84 Ok(mut child) => {85 let _ = child.wait();8687 // Create a lock to ensure that this thread has exclusive access to writing.88 let _lock = self.out_perm.lock().unwrap();8990 // 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 lines
3334 // 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 lines
6// 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 ticket;10mod command;11mod token;12mod job;13mod input;1415use std::borrow::Cow;16use std::path::Path;17use std::process::Command;18use std::sync::{Arc, Mutex};1920use regex::Regex;2122use self::input::{basename, dirname, remove_extension};22use self::ticket::CommandTicket;23use self::command::execute_command;24use self::token::Token;25pub use self::job::job;2627/// 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)]33pub struct TokenizedCommand {34 args: Vec<TokenizedArgument>,35}
38 unmodified lines
74 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 }8081 let mut args = Vec::new();82 let mut has_placeholder = false;
3 unmodified lines
8687 let mut tokens = Vec::new();88 let mut start = 0;8989 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 lines
128129 TokenizedCommand { args: args }130 }131131 /// 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();142143 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 }147148 CommandTicket::new(args, out_perm)148 execute_command(cmd, out_perm)149 }150}151152#[cfg(test)]
26 unmodified lines
deleted: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.89use std::process::Command;10use std::sync::{Arc, Mutex};11use std::io;1213/// 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.16pub struct CommandTicket {17 args: Vec<String>,18 out_perm: Arc<Mutex<()>>,19}2021impl 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 }3233 /// 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;3839 // 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();4546 // 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();5253 let stdout = io::stdout();54 let stderr = io::stderr();5556 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 }6263 #[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;6970 // 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];7475 unsafe {76 pipe(stdout_fds.as_mut_ptr());77 pipe(stderr_fds.as_mut_ptr());78 }7980 // 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);8889 // 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();9798 // 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 };109110 match cmd {111 Ok(mut child) => {112 let _ = child.wait();113114 // Create a lock to ensure that this thread has exclusive access to writing.115 let _lock = self.out_perm.lock().unwrap();116117 // 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}