Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error message for failed replacements #186

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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