use std::path::PathBuf;
fn usage_hint(message: &str) -> &'static str {
let m = message.to_ascii_lowercase();
if m.contains("the output name `") {
"Name the output with the extension of the format you want (.ome.tiff, .ome.zarr, .mzML, .csv, .parquet, .arrow, .nwb, .jdx, .asm.json, .rdml), or set the format explicitly."
} else if m.contains("--overwrite") {
"Choose another output path, or pass --overwrite to replace that file (the input is never modified)."
} else if m.contains(crate::output::OUTPUT_IS_INPUT) {
"Choose an output path that is not one of the input files; OpenReadout writes new files next to the raw data and never replaces it."
} else if m.contains("out of range: use") {
"Use a value inside the range the message gives."
} else if m.contains("select") {
"Selections are zero-based and repeatable: `c=0`, `z=1-3`, `t=0,2`; `openreadout info FILE --json` gives each image's size_c, size_z and size_t."
} else if [
"out of range",
"does not exist",
"past the end",
"no such",
"not found",
]
.iter()
.any(|k| m.contains(k))
{
"Indices are zero-based; `openreadout info FILE --json` lists the images, traces (sweep_count, sample_count), tables (row_count) and spectra the file holds."
} else {
"Check the arguments with `openreadout help <command>`; `openreadout info FILE --json` shows what the file holds."
}
}
fn other_hint(message: &str) -> &'static str {
let m = message.to_ascii_lowercase();
if m.contains("read-back") || m.contains("read back") || m.contains("verif") {
"The output was written to a temporary file that failed verification, so nothing was kept; check free disk space and the output directory, then rerun."
} else {
"Unexpected failure: rerun with --json for the full error, and report it with `openreadout --version` and `openreadout info FILE --json`."
}
}
pub(crate) const EXTENSION_ONLY: &str = "only the file extension matched this format";
pub(crate) const EXTENSION_ONLY_HINT: &str = "The file's first bytes do not look like this format, only its extension does: it may be another kind of file with the same extension, or damaged from the start. `openreadout info --view format FILE` shows what was detected.";
pub const MISSING_MEMBER: &str = "of the data set is missing";
pub(crate) const MISSING_MEMBER_HINT: &str = "A file this data set lists is not next to the file you opened. Copy the whole data set (the file you opened and every file it names) into one folder, keeping the names; `openreadout check FILE` lists what is missing.";
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("unrecognized file format: {path}")]
UnknownFormat {
path: PathBuf,
},
#[error("{format}: unsupported feature: {feature}")]
Unsupported {
format: &'static str,
feature: String,
hint: Option<String>,
},
#[error("{format}: corrupt file: {detail}")]
Corrupt {
format: &'static str,
detail: String,
offset: Option<u64>,
},
#[error("usage error: {0}")]
Usage(String),
#[error("I/O error on {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("{0}")]
Other(String),
}
impl Error {
pub fn code(&self) -> &'static str {
match self {
Error::UnknownFormat { .. } => "unknown_format",
Error::Unsupported { .. } => "unsupported_feature",
Error::Corrupt { .. } => "corrupt_file",
Error::Usage(_) => "usage",
Error::Io { .. } => "io",
Error::Other(_) => "error",
}
}
pub fn exit_code(&self) -> i32 {
match self {
Error::Other(_) => 1,
Error::Usage(_) => 2,
Error::UnknownFormat { .. } => 3,
Error::Corrupt { .. } => 4,
Error::Io { .. } => 5,
Error::Unsupported { .. } => 6,
}
}
pub fn hint(&self) -> Option<String> {
match self {
Error::UnknownFormat { path } if path.is_dir() => Some(
"This folder is not a data set that one reader opens as a whole: name a file in it, or use `openreadout batch` to read every file of the folder.".into(),
),
Error::UnknownFormat { path } => {
let name = path.file_name().map(|n| n.to_string_lossy());
Some(match name.as_deref().and_then(|n| n.strip_prefix("._")) {
Some(data) if !data.is_empty() => format!(
"This is a macOS AppleDouble file: Finder metadata that macOS writes next to `{data}`, not data. Open `{data}` instead, and skip `._*` files."
),
_ => "No reader recognised the file's first bytes, so a matching extension alone is not enough: the file may be another kind of file with the same extension, a format not yet implemented, or a renamed export. `openreadout self formats` lists the supported formats.".into(),
})
}
Error::Unsupported { hint, .. } => hint.clone(),
Error::Corrupt { detail, .. } if detail.contains(EXTENSION_ONLY) => {
Some(EXTENSION_ONLY_HINT.into())
}
Error::Corrupt { detail, .. } if detail.contains(MISSING_MEMBER) => {
Some(MISSING_MEMBER_HINT.into())
}
Error::Corrupt { .. } => Some(
"Run `openreadout check <file>` for a full integrity report. The file may be truncated by an interrupted acquisition or copy."
.into(),
),
Error::Io { source, .. } if source.kind() == std::io::ErrorKind::IsADirectory => Some(
"This is a folder and the command takes one file: name a file in it, or use `openreadout batch` to read every file of the folder.".into(),
),
Error::Io { .. } => Some("Check that the path exists and is readable.".into()),
Error::Usage(m) => Some(usage_hint(m).into()),
Error::Other(m) => Some(other_hint(m).into()),
}
}
pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
Error::Io {
path: path.into(),
source,
}
}
pub fn corrupt(format: &'static str, detail: impl Into<String>) -> Self {
Error::Corrupt {
format,
detail: detail.into(),
offset: None,
}
}
pub fn corrupt_at(format: &'static str, offset: u64, detail: impl Into<String>) -> Self {
Error::Corrupt {
format,
detail: detail.into(),
offset: Some(offset),
}
}
pub fn unsupported(
format: &'static str,
feature: impl Into<String>,
hint: impl Into<String>,
) -> Self {
Error::Unsupported {
format,
feature: feature.into(),
hint: Some(hint.into()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_error_has_a_hint() {
let errors = [
Error::UnknownFormat { path: "x".into() },
Error::unsupported("x", "y", "Convert it first."),
Error::corrupt("x", "y"),
Error::Usage("sweep 9 out of range (trace 0 has 3 sweeps, 0..3)".into()),
Error::Usage("out.csv exists; pass --overwrite to replace it".into()),
Error::Usage("selection matches no planes".into()),
Error::Usage("anything".into()),
Error::io("x", std::io::Error::other("y")),
Error::Other("Parquet read-back: bad".into()),
Error::Other("anything".into()),
Error::corrupt(
"tiff",
format!("file 'a.ndpi' {MISSING_MEMBER} (looked for a.ndpi)"),
),
];
for e in &errors {
assert!(e.hint().is_some_and(|h| h.len() > 10), "{e}");
}
let hint = |i: usize| errors[i].hint().unwrap_or_default();
assert!(hint(3).contains("info FILE --json"));
assert!(hint(4).contains("--overwrite"));
assert!(hint(5).contains("c=0"));
assert!(hint(8).contains("verification"));
assert!(hint(10).contains("whole data set"));
}
#[test]
fn value_ranges_and_inputs_get_their_own_hints() {
let hint = |m: &str| Error::Usage(m.into()).hint().unwrap_or_default();
let h = hint("dpi 5 is out of range: use 36 to 2400 (300 is usual for print)");
assert!(!h.contains("zero-based"), "{h}");
assert!(hint("scale 9 is out of range: use 0.25 to 8").contains("range the message gives"));
assert!(
hint("output a.tif is the input file a.tif; raw files are never modified")
.contains("not one of the input files")
);
assert!(hint("image index 4 out of range (0..2)").contains("zero-based"));
}
}