Skip to content
Myr

job.rs

This file

Path

src/exec/job.rs

62 lines · 2.0 KiB · Rust

Last changed by

Proper error handling within walk.rssharkdpbefore adoption4590ae8

History of this file

Take 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) -> ExitCode {20    let mut results: Vec<ExitCode> = Vec::new();21    loop {22        // Create a lock on the shared receiver for this thread.23        let lock = rx.lock().unwrap();2425        // Obtain the next result from the receiver, else if the channel26        // has closed, exit from the loop27        let value: PathBuf = match lock.recv() {28            Ok(WorkerResult::Entry(val)) => val,29            Ok(WorkerResult::Error(err)) => {30                if show_filesystem_errors {31                    print_error(err.to_string());32                }33                continue;34            }35            Err(_) => break,36        };3738        // Drop the lock so that other threads can read from the receiver.39        drop(lock);40        // Generate a command, execute it and store its exit code.41        results.push(cmd.generate_and_execute(&value, Arc::clone(&out_perm)))42    }43    // Returns error in case of any error.44    merge_exitcodes(&results)45}4647pub fn batch(48    rx: Receiver<WorkerResult>,49    cmd: &CommandTemplate,50    show_filesystem_errors: bool,51) -> ExitCode {52    let paths = rx.iter().filter_map(|value| match value {53        WorkerResult::Entry(val) => Some(val),54        WorkerResult::Error(err) => {55            if show_filesystem_errors {56                print_error(err.to_string());57            }58            None59        }60    });61    cmd.generate_and_execute_batch(paths)62}