1use std::path::PathBuf;
8
9fn usage_hint(message: &str) -> &'static str {
11 let m = message.to_ascii_lowercase();
12 if m.contains("the output name `") {
13 "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."
14 } else if m.contains("--overwrite") {
15 "Choose another output path, or pass --overwrite to replace that file (the input is never modified)."
16 } else if m.contains(crate::output::OUTPUT_IS_INPUT) {
17 "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."
18 } else if m.contains("out of range: use") {
19 "Use a value inside the range the message gives."
20 } else if m.contains("select") {
21 "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."
22 } else if [
23 "out of range",
24 "does not exist",
25 "past the end",
26 "no such",
27 "not found",
28 ]
29 .iter()
30 .any(|k| m.contains(k))
31 {
32 "Indices are zero-based; `openreadout info FILE --json` lists the images, traces (sweep_count, sample_count), tables (row_count) and spectra the file holds."
33 } else {
34 "Check the arguments with `openreadout help <command>`; `openreadout info FILE --json` shows what the file holds."
35 }
36}
37
38fn other_hint(message: &str) -> &'static str {
40 let m = message.to_ascii_lowercase();
41 if m.contains("read-back") || m.contains("read back") || m.contains("verif") {
42 "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."
43 } else {
44 "Unexpected failure: rerun with --json for the full error, and report it with `openreadout --version` and `openreadout info FILE --json`."
45 }
46}
47
48pub(crate) const EXTENSION_ONLY: &str = "only the file extension matched this format";
50
51pub(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.";
53
54pub const MISSING_MEMBER: &str = "of the data set is missing";
57
58pub(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.";
60
61pub type Result<T> = std::result::Result<T, Error>;
63
64#[derive(Debug, thiserror::Error)]
67#[non_exhaustive]
68pub enum Error {
69 #[error("unrecognized file format: {path}")]
71 UnknownFormat {
72 path: PathBuf,
74 },
75
76 #[error("{format}: unsupported feature: {feature}")]
78 Unsupported {
79 format: &'static str,
81 feature: String,
83 hint: Option<String>,
85 },
86
87 #[error("{format}: corrupt file: {detail}")]
89 Corrupt {
90 format: &'static str,
92 detail: String,
94 offset: Option<u64>,
96 },
97
98 #[error("usage error: {0}")]
100 Usage(String),
101
102 #[error("I/O error on {path}: {source}")]
104 Io {
105 path: PathBuf,
107 #[source]
109 source: std::io::Error,
110 },
111
112 #[error("{0}")]
114 Other(String),
115}
116
117impl Error {
118 pub fn code(&self) -> &'static str {
120 match self {
121 Error::UnknownFormat { .. } => "unknown_format",
122 Error::Unsupported { .. } => "unsupported_feature",
123 Error::Corrupt { .. } => "corrupt_file",
124 Error::Usage(_) => "usage",
125 Error::Io { .. } => "io",
126 Error::Other(_) => "error",
127 }
128 }
129
130 pub fn exit_code(&self) -> i32 {
132 match self {
133 Error::Other(_) => 1,
134 Error::Usage(_) => 2,
135 Error::UnknownFormat { .. } => 3,
136 Error::Corrupt { .. } => 4,
137 Error::Io { .. } => 5,
138 Error::Unsupported { .. } => 6,
139 }
140 }
141
142 pub fn hint(&self) -> Option<String> {
144 match self {
145 Error::UnknownFormat { path } if path.is_dir() => Some(
146 "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(),
147 ),
148 Error::UnknownFormat { path } => {
149 let name = path.file_name().map(|n| n.to_string_lossy());
150 Some(match name.as_deref().and_then(|n| n.strip_prefix("._")) {
151 Some(data) if !data.is_empty() => format!(
152 "This is a macOS AppleDouble file: Finder metadata that macOS writes next to `{data}`, not data. Open `{data}` instead, and skip `._*` files."
153 ),
154 _ => "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(),
155 })
156 }
157 Error::Unsupported { hint, .. } => hint.clone(),
158 Error::Corrupt { detail, .. } if detail.contains(EXTENSION_ONLY) => {
159 Some(EXTENSION_ONLY_HINT.into())
160 }
161 Error::Corrupt { detail, .. } if detail.contains(MISSING_MEMBER) => {
162 Some(MISSING_MEMBER_HINT.into())
163 }
164 Error::Corrupt { .. } => Some(
165 "Run `openreadout check <file>` for a full integrity report. The file may be truncated by an interrupted acquisition or copy."
166 .into(),
167 ),
168 Error::Io { source, .. } if source.kind() == std::io::ErrorKind::IsADirectory => Some(
169 "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(),
170 ),
171 Error::Io { .. } => Some("Check that the path exists and is readable.".into()),
172 Error::Usage(m) => Some(usage_hint(m).into()),
173 Error::Other(m) => Some(other_hint(m).into()),
174 }
175 }
176
177 pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
179 Error::Io {
180 path: path.into(),
181 source,
182 }
183 }
184
185 pub fn corrupt(format: &'static str, detail: impl Into<String>) -> Self {
187 Error::Corrupt {
188 format,
189 detail: detail.into(),
190 offset: None,
191 }
192 }
193
194 pub fn corrupt_at(format: &'static str, offset: u64, detail: impl Into<String>) -> Self {
196 Error::Corrupt {
197 format,
198 detail: detail.into(),
199 offset: Some(offset),
200 }
201 }
202
203 pub fn unsupported(
205 format: &'static str,
206 feature: impl Into<String>,
207 hint: impl Into<String>,
208 ) -> Self {
209 Error::Unsupported {
210 format,
211 feature: feature.into(),
212 hint: Some(hint.into()),
213 }
214 }
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 #[test]
223 fn every_error_has_a_hint() {
224 let errors = [
225 Error::UnknownFormat { path: "x".into() },
226 Error::unsupported("x", "y", "Convert it first."),
227 Error::corrupt("x", "y"),
228 Error::Usage("sweep 9 out of range (trace 0 has 3 sweeps, 0..3)".into()),
229 Error::Usage("out.csv exists; pass --overwrite to replace it".into()),
230 Error::Usage("selection matches no planes".into()),
231 Error::Usage("anything".into()),
232 Error::io("x", std::io::Error::other("y")),
233 Error::Other("Parquet read-back: bad".into()),
234 Error::Other("anything".into()),
235 Error::corrupt(
236 "tiff",
237 format!("file 'a.ndpi' {MISSING_MEMBER} (looked for a.ndpi)"),
238 ),
239 ];
240 for e in &errors {
241 assert!(e.hint().is_some_and(|h| h.len() > 10), "{e}");
242 }
243 let hint = |i: usize| errors[i].hint().unwrap_or_default();
244 assert!(hint(3).contains("info FILE --json"));
245 assert!(hint(4).contains("--overwrite"));
246 assert!(hint(5).contains("c=0"));
247 assert!(hint(8).contains("verification"));
248 assert!(hint(10).contains("whole data set"));
249 }
250
251 #[test]
254 fn value_ranges_and_inputs_get_their_own_hints() {
255 let hint = |m: &str| Error::Usage(m.into()).hint().unwrap_or_default();
256 let h = hint("dpi 5 is out of range: use 36 to 2400 (300 is usual for print)");
257 assert!(!h.contains("zero-based"), "{h}");
258 assert!(hint("scale 9 is out of range: use 0.25 to 8").contains("range the message gives"));
259 assert!(
260 hint("output a.tif is the input file a.tif; raw files are never modified")
261 .contains("not one of the input files")
262 );
263 assert!(hint("image index 4 out of range (0..2)").contains("zero-based"));
264 }
265}