job.rs
This file
Path
src/exec/job.rs
78 lines · 2.5 KiB · Rust
Last changed by
send DirEntries to output instead of just pathJonathan Gorenbefore adoption813a802
History of this fileTake it
1use std::sync::{Arc, Mutex};23use crossbeam_channel::Receiver;45use crate::entry::DirEntry;6use crate::error::print_error;7use crate::exit_codes::{merge_exitcodes, ExitCode};8use crate::walk::WorkerResult;910use super::CommandTemplate;1112/// An event loop that listens for inputs from the `rx` receiver. Each received input will13/// generate a command with the supplied command template. The generated command will then14/// be executed, and this process will continue until the receiver's sender has closed.15pub fn job(16 rx: Arc<Mutex<Receiver<WorkerResult>>>,17 cmd: Arc<CommandTemplate>,18 out_perm: Arc<Mutex<()>>,19 show_filesystem_errors: bool,20 buffer_output: bool,21) -> ExitCode {22 let mut results: Vec<ExitCode> = Vec::new();23 loop {24 // Create a lock on the shared receiver for this thread.25 let lock = rx.lock().unwrap();2627 // Obtain the next result from the receiver, else if the channel28 // has closed, exit from the loop29 let value: DirEntry = match lock.recv() {30 Ok(WorkerResult::Entry(val)) => val,31 Ok(WorkerResult::Error(err)) => {32 if show_filesystem_errors {33 print_error(err.to_string());34 }35 continue;36 }37 Err(_) => break,38 };3940 // Drop the lock so that other threads can read from the receiver.41 drop(lock);42 // Generate a command, execute it and store its exit code.43 results.push(cmd.generate_and_execute(value.path(), Arc::clone(&out_perm), buffer_output))44 }45 // Returns error in case of any error.46 merge_exitcodes(results)47}4849pub fn batch(50 rx: Receiver<WorkerResult>,51 cmd: &CommandTemplate,52 show_filesystem_errors: bool,53 buffer_output: bool,54 limit: usize,55) -> ExitCode {56 let paths = rx.iter().filter_map(|value| match value {57 WorkerResult::Entry(val) => Some(val.path().to_owned()),58 WorkerResult::Error(err) => {59 if show_filesystem_errors {60 print_error(err.to_string());61 }62 None63 }64 });65 if limit == 0 {66 // no limit67 return cmd.generate_and_execute_batch(paths, buffer_output);68 }6970 let mut exit_codes = Vec::new();71 let mut peekable = paths.peekable();72 while peekable.peek().is_some() {73 let limited = peekable.by_ref().take(limit);74 let exit_code = cmd.generate_and_execute_batch(limited, buffer_output);75 exit_codes.push(exit_code);76 }77 merge_exitcodes(exit_codes)78}