Skip to content

Commit

Permalink
Merge pull request #91 from str4d/54-pipe-errors
Browse files Browse the repository at this point in the history
Give a more useful error when encryption fails with BrokenPipe
  • Loading branch information
str4d authored Mar 21, 2020
2 parents 7b2b055 + e059421 commit cb2b6ae
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
12 changes: 12 additions & 0 deletions rage/src/bin/rage/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::fmt;
use std::io;

pub(crate) enum EncryptError {
BrokenPipe { is_stdout: bool, source: io::Error },
IdentityFlag,
InvalidRecipient(String),
Io(io::Error),
Expand All @@ -28,6 +29,17 @@ impl From<minreq::Error> for EncryptError {
impl fmt::Display for EncryptError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
EncryptError::BrokenPipe { is_stdout, source } => {
if *is_stdout {
writeln!(f, "Could not write to stdout: {}", source)?;
write!(
f,
"Are you piping to a program that isn't reading from stdin?"
)
} else {
write!(f, "Could not write to file: {}", source)
}
}
EncryptError::IdentityFlag => {
writeln!(f, "-i/--identity can't be used in encryption mode.")?;
write!(f, "Did you forget to specify -d/--decrypt?")
Expand Down
25 changes: 19 additions & 6 deletions rage/src/bin/rage/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,13 +256,26 @@ fn encrypt(opts: AgeOptions) -> Result<(), error::EncryptError> {
(Format::Binary, file_io::OutputFormat::Binary)
};

let mut output = encryptor.wrap_output(
file_io::OutputWriter::new(opts.output, output_format, 0o666)?,
format,
)?;
// Create an output to the user-requested location.
let output = file_io::OutputWriter::new(opts.output, output_format, 0o666)?;
let is_stdout = match output {
file_io::OutputWriter::File(..) => false,
file_io::OutputWriter::Stdout(..) => true,
};

io::copy(&mut input, &mut output)?;
output.finish()?;
let mut output = encryptor.wrap_output(output, format)?;

// Give more useful errors specifically when writing to the output.
let map_io_errors = |e: io::Error| match e.kind() {
io::ErrorKind::BrokenPipe => error::EncryptError::BrokenPipe {
is_stdout,
source: e,
},
_ => e.into(),
};

io::copy(&mut input, &mut output).map_err(map_io_errors)?;
output.finish().map_err(map_io_errors)?;

Ok(())
}
Expand Down

0 comments on commit cb2b6ae

Please sign in to comment.