Skip to content

Commit

Permalink
Improve error message for failed replacements (#186)
Browse files Browse the repository at this point in the history
  • Loading branch information
CosmicHorrorDev authored May 11, 2023
1 parent b6ea084 commit 27c217a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 9 deletions.
27 changes: 26 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
use std::{
fmt::{self, Write},
path::PathBuf,
};

#[derive(thiserror::Error)]
pub enum Error {
#[error("invalid regex {0}")]
Expand All @@ -7,7 +12,27 @@ pub enum Error {
#[error("failed to move file: {0}")]
TempfilePersist(#[from] tempfile::PersistError),
#[error("file doesn't have parent path: {0}")]
InvalidPath(std::path::PathBuf),
InvalidPath(PathBuf),
#[error("failed processing files:\n{0}")]
FailedProcessing(FailedJobs),
}

pub struct FailedJobs(Vec<(PathBuf, Error)>);

impl From<Vec<(PathBuf, Error)>> for FailedJobs {
fn from(vec: Vec<(PathBuf, Error)>) -> Self {
Self(vec)
}
}

impl fmt::Display for FailedJobs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("\tFailedJobs(\n")?;
for (path, err) in &self.0 {
f.write_str(&format!("\t{:?}: {}\n", path, err))?;
}
f.write_char(')')
}
}

// pretty-print the error
Expand Down
26 changes: 18 additions & 8 deletions src/input.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Replacer, Result};
use crate::{Error, Replacer, Result};
use std::{fs::File, io::prelude::*, path::PathBuf};

#[derive(Debug)]
Expand Down Expand Up @@ -57,14 +57,24 @@ impl App {
(Source::Files(paths), false) => {
use rayon::prelude::*;

#[allow(unused_must_use)]
paths.par_iter().for_each(|p| {
self.replacer.replace_file(p).map_err(|e| {
eprintln!("Error processing {}: {}", p.display(), e)
});
});
let failed_jobs: Vec<_> = paths
.par_iter()
.filter_map(|p| {
if let Err(e) = self.replacer.replace_file(p) {
Some((p.to_owned(), e))
} else {
None
}
})
.collect();

Ok(())
if failed_jobs.is_empty() {
Ok(())
} else {
let failed_jobs =
crate::error::FailedJobs::from(failed_jobs);
Err(Error::FailedProcessing(failed_jobs))
}
}
(Source::Files(paths), true) => {
let stdout = std::io::stdout();
Expand Down

0 comments on commit 27c217a

Please sign in to comment.