job.rs
This file
Path
src/exec/job.rs
77 lines · 2.5 KiB · Rust
Last changed by
Implement `--batch-size` (#866)Devon Hollowoodbefore adoption17dd2a6
History of this fileTake it
1use std::path::PathBuf;2use std::sync::mpsc::Receiver;3use std::sync::{Arc, Mutex};45use crate::error::print_error;6use crate::exit_codes::{merge_exitcodes, ExitCode};7use crate::walk::WorkerResult;89use super::CommandTemplate;1011/// An event loop that listens for inputs from the `rx` receiver. Each received input will12/// generate a command with the supplied command template. The generated command will then13/// be executed, and this process will continue until the receiver's sender has closed.14pub fn job(15 rx: Arc<Mutex<Receiver<WorkerResult>>>,16 cmd: Arc<CommandTemplate>,17 out_perm: Arc<Mutex<()>>,18 show_filesystem_errors: bool,19 buffer_output: bool,20) -> ExitCode {21 let mut results: Vec<ExitCode> = Vec::new();22 loop {23 // Create a lock on the shared receiver for this thread.24 let lock = rx.lock().unwrap();2526 // Obtain the next result from the receiver, else if the channel27 // has closed, exit from the loop28 let value: PathBuf = match lock.recv() {29 Ok(WorkerResult::Entry(val)) => val,30 Ok(WorkerResult::Error(err)) => {31 if show_filesystem_errors {32 print_error(err.to_string());33 }34 continue;35 }36 Err(_) => break,37 };3839 // Drop the lock so that other threads can read from the receiver.40 drop(lock);41 // Generate a command, execute it and store its exit code.42 results.push(cmd.generate_and_execute(&value, Arc::clone(&out_perm), buffer_output))43 }44 // Returns error in case of any error.45 merge_exitcodes(results)46}4748pub fn batch(49 rx: Receiver<WorkerResult>,50 cmd: &CommandTemplate,51 show_filesystem_errors: bool,52 buffer_output: bool,53 limit: usize,54) -> ExitCode {55 let paths = rx.iter().filter_map(|value| match value {56 WorkerResult::Entry(val) => Some(val),57 WorkerResult::Error(err) => {58 if show_filesystem_errors {59 print_error(err.to_string());60 }61 None62 }63 });64 if limit == 0 {65 // no limit66 return cmd.generate_and_execute_batch(paths, buffer_output);67 }6869 let mut exit_codes = Vec::new();70 let mut peekable = paths.peekable();71 while peekable.peek().is_some() {72 let limited = peekable.by_ref().take(limit);73 let exit_code = cmd.generate_and_execute_batch(limited, buffer_output);74 exit_codes.push(exit_code);75 }76 merge_exitcodes(exit_codes)77}