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

Give a more useful error when encryption fails with BrokenPipe #91

Merged
merged 1 commit into from
Mar 21, 2020
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
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