Skip to content

Commit

Permalink
excel: simplify password-protected Excel file error handling
Browse files Browse the repository at this point in the history
Just propagate calamine errors
  • Loading branch information
jqnatividad committed Dec 13, 2023
1 parent 3652ddb commit d9625b2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 18 deletions.
22 changes: 8 additions & 14 deletions src/cmd/excel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ use serde::{Deserialize, Serialize};

use crate::{
config::{Config, Delimiter},
util, CliResult,
util, CliError, CliResult,
};

// number of rows to process in each core/thread
Expand Down Expand Up @@ -150,6 +150,12 @@ struct SheetMetadata {
duplicate_headers_count: usize,
}

impl From<calamine::Error> for CliError {
fn from(e: calamine::Error) -> Self {
CliError::Other(format!("{e}"))
}
}

#[derive(Serialize, Deserialize)]
struct MetadataStruct {
filename: String,
Expand Down Expand Up @@ -239,19 +245,7 @@ pub fn run(argv: &[&str]) -> CliResult<()> {

let requested_range = args.flag_range.to_lowercase();

let mut workbook = match open_workbook_auto(path) {
Ok(workbook) => workbook,
Err(e) => {
let es = e.to_string();
// password protected errors come in different flavors for Excel
if es.starts_with("Xls error: Cfb error")
|| es.starts_with("Xlsx error: Zip error: invalid Zip archive")
{
return fail_clierror!("{path} may be a password-protected workbook: {e}.");
}
return fail_clierror!("Cannot open workbook: {e}.");
},
};
let mut workbook = open_workbook_auto(path)?;

let sheet_names = workbook.sheet_names();
if sheet_names.is_empty() {
Expand Down
5 changes: 1 addition & 4 deletions tests/test_excel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ fn excel_open_xlsx_readpassword() {
cmd.arg(xlsx_file);

let got = wrk.output_stderr(&mut cmd);
assert!(got
.matches("Cannot open workbook: Xlsx error: Workbook is password protected.")
.min()
.is_some());
assert_eq!(got, "Xlsx error: Workbook is password protected\n");
wrk.assert_err(&mut cmd);
}

Expand Down

0 comments on commit d9625b2

Please sign in to comment.