1use std::fmt;
9use std::io;
10use std::path::PathBuf;
11
12pub type Result<T, E = DimaError> = std::result::Result<T, E>;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub enum ExitClass {
18 Internal,
20 Usage,
22 Io,
25 InvalidInput,
27 Cancelled,
29}
30
31impl ExitClass {
32 #[must_use]
34 pub const fn code(self) -> u8 {
35 match self {
36 Self::Internal => 1,
37 Self::Usage => 2,
38 Self::Io => 3,
39 Self::InvalidInput => 4,
40 Self::Cancelled => 130,
41 }
42 }
43}
44
45#[derive(Clone, Debug, Default, PartialEq, Eq)]
48pub struct Location {
49 pub source: String,
51 pub record: Option<u64>,
53 pub line: Option<u64>,
55 pub column: Option<u64>,
57 pub byte: Option<u64>,
59}
60
61impl Location {
62 #[must_use]
64 pub fn new(source: impl Into<String>) -> Self {
65 Self {
66 source: source.into(),
67 ..Self::default()
68 }
69 }
70
71 #[must_use]
73 pub fn record(mut self, record: u64) -> Self {
74 self.record = Some(record);
75 self
76 }
77
78 #[must_use]
80 pub fn line(mut self, line: u64) -> Self {
81 self.line = Some(line);
82 self
83 }
84
85 #[must_use]
87 pub fn column(mut self, column: u64) -> Self {
88 self.column = Some(column);
89 self
90 }
91
92 #[must_use]
94 pub fn byte(mut self, byte: u64) -> Self {
95 self.byte = Some(byte);
96 self
97 }
98}
99
100fn shown_name(name: &str) -> std::borrow::Cow<'_, str> {
103 if !name.chars().any(char::is_control) {
104 return name.into();
105 }
106 let mut out = String::with_capacity(name.len() + 8);
107 for c in name.chars() {
108 if c.is_control() {
109 out.extend(c.escape_unicode());
110 } else {
111 out.push(c);
112 }
113 }
114 out.into()
115}
116
117impl fmt::Display for Location {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 f.write_str(&shown_name(&self.source))?;
121 let mut details = Vec::with_capacity(3);
122 if let Some(l) = self.line {
123 details.push(format!("line {l}"));
124 }
125 if let Some(c) = self.column {
126 details.push(format!("column {c}"));
127 }
128 if let Some(b) = self.byte {
129 details.push(format!("byte {b}"));
130 }
131 match (self.record, details.is_empty()) {
132 (Some(r), true) => write!(f, ": record {r}"),
133 (Some(r), false) => write!(f, ": record {r} ({})", details.join(", ")),
134 (None, false) => write!(f, ": {}", details.join(", ")),
135 (None, true) => Ok(()),
136 }
137 }
138}
139
140#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
142pub enum IoAction {
143 Open,
145 Read,
147 Create,
149 Write,
151 Sync,
153 Replace,
155 Remove,
157 CreateDir,
159 Inspect,
161}
162
163impl IoAction {
164 const fn verb(self) -> &'static str {
165 match self {
166 Self::Open => "open",
167 Self::Read => "read",
168 Self::Create => "create",
169 Self::Write => "write",
170 Self::Sync => "flush",
171 Self::Replace => "replace",
172 Self::Remove => "remove",
173 Self::CreateDir => "create directory",
174 Self::Inspect => "inspect",
175 }
176 }
177}
178
179#[derive(Clone, Debug, PartialEq, Eq)]
181pub enum IoTarget {
182 Path(PathBuf),
184 Stdin,
186 Stdout,
188}
189
190impl fmt::Display for IoTarget {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 match self {
193 Self::Path(p) => write!(f, "'{}'", shown_name(&p.display().to_string())),
194 Self::Stdin => f.write_str("standard input"),
195 Self::Stdout => f.write_str("standard output"),
196 }
197 }
198}
199
200pub const THREAD_LIMIT_HINT: &str = if cfg!(target_os = "macos") {
204 "use fewer threads; macOS limits the number of threads of each process"
207} else if cfg!(windows) {
208 "use fewer threads, or close other programs: every thread needs memory"
209} else {
210 "use fewer threads, or raise the system's limit on processes and threads (`ulimit -u`, or \
211 the container's pids limit)"
212};
213
214#[derive(Debug, thiserror::Error)]
216#[non_exhaustive]
217pub enum DimaError {
218 #[error("{message}")]
220 Usage {
221 message: String,
223 hint: Option<String>,
225 },
226 #[error("{location}: {message}")]
229 InputFormat {
230 location: Box<Location>,
232 message: String,
234 hint: Option<String>,
236 },
237 #[error("{}{message}", location.as_ref().map(|l| format!("{l}: ")).unwrap_or_default())]
239 InputData {
240 location: Option<Box<Location>>,
242 message: String,
244 hint: Option<String>,
246 },
247 #[error("cannot {} {target}", action.verb())]
249 Io {
250 action: IoAction,
252 target: IoTarget,
254 #[source]
256 source: io::Error,
257 },
258 #[error("cannot start {what}")]
261 System {
262 what: String,
264 #[source]
266 source: io::Error,
267 },
268 #[error("'{source_name}' changed after it was checked")]
272 InputChanged {
273 source_name: String,
275 },
276 #[error("cancelled")]
278 Cancelled,
279 #[error("{what} exceeds the 64-bit counter range")]
281 Overflow {
282 what: &'static str,
284 },
285 #[error("internal error: {message}")]
287 Internal {
288 message: String,
290 },
291}
292
293impl DimaError {
294 #[must_use]
296 pub fn usage(message: impl Into<String>) -> Self {
297 Self::Usage {
298 message: message.into(),
299 hint: None,
300 }
301 }
302
303 #[must_use]
305 pub fn input_format(location: Location, message: impl Into<String>) -> Self {
306 Self::InputFormat {
307 location: Box::new(location),
308 message: message.into(),
309 hint: None,
310 }
311 }
312
313 #[must_use]
315 pub fn input_data(location: Option<Location>, message: impl Into<String>) -> Self {
316 Self::InputData {
317 location: location.map(Box::new),
318 message: message.into(),
319 hint: None,
320 }
321 }
322
323 #[must_use]
325 pub fn io(action: IoAction, target: IoTarget, source: io::Error) -> Self {
326 Self::Io {
327 action,
328 target,
329 source,
330 }
331 }
332
333 #[must_use]
335 pub fn system(what: impl Into<String>, source: io::Error) -> Self {
336 Self::System {
337 what: what.into(),
338 source,
339 }
340 }
341
342 #[must_use]
344 pub fn internal(message: impl Into<String>) -> Self {
345 Self::Internal {
346 message: message.into(),
347 }
348 }
349
350 #[must_use]
352 pub(crate) fn in_source(mut self, name: &str) -> Self {
353 if let Self::InputData {
354 location: location @ None,
355 ..
356 } = &mut self
357 {
358 *location = Some(Box::new(Location::new(name.to_owned())));
359 }
360 self
361 }
362
363 #[must_use]
365 pub fn with_hint(mut self, new_hint: impl Into<String>) -> Self {
366 match &mut self {
367 Self::Usage { hint, .. }
368 | Self::InputFormat { hint, .. }
369 | Self::InputData { hint, .. } => *hint = Some(new_hint.into()),
370 Self::Io { .. }
371 | Self::System { .. }
372 | Self::InputChanged { .. }
373 | Self::Cancelled
374 | Self::Overflow { .. }
375 | Self::Internal { .. } => {}
376 }
377 self
378 }
379
380 #[must_use]
382 pub fn hint(&self) -> Option<&str> {
383 match self {
384 Self::Usage { hint, .. }
385 | Self::InputFormat { hint, .. }
386 | Self::InputData { hint, .. } => hint.as_deref(),
387 Self::Io { source, .. } => match source.kind() {
388 io::ErrorKind::NotFound => Some("check the path and the current directory"),
389 io::ErrorKind::PermissionDenied => Some(
390 "check the permissions of the file and its directory (an output is written \
391 to a temporary file in its directory first, so the directory must be \
392 writable)",
393 ),
394 io::ErrorKind::StorageFull => Some("free some disk space and try again"),
395 io::ErrorKind::QuotaExceeded => {
396 Some("the disk quota is used up; free some space or write elsewhere")
397 }
398 io::ErrorKind::FileTooLarge => Some(
399 "a file-size limit was reached (see `ulimit -f`); raise it or compress the output",
400 ),
401 io::ErrorKind::ReadOnlyFilesystem => {
402 Some("the file system is read-only; write the output elsewhere")
403 }
404 _ => None,
405 },
406 Self::InputChanged { .. } => {
407 Some("check the file again, review the settings and start again")
408 }
409 Self::System { .. } => Some(THREAD_LIMIT_HINT),
410 Self::Overflow { .. } => {
411 Some("split the input into smaller alignments and analyse them separately")
412 }
413 Self::Internal { .. } => Some(concat!(
414 "this is a bug in DiMA; please report it at ",
415 env!("CARGO_PKG_REPOSITORY"),
416 "/issues with the command line and, if possible, the input"
417 )),
418 Self::Cancelled => None,
419 }
420 }
421
422 #[must_use]
424 pub const fn class(&self) -> ExitClass {
425 match self {
426 Self::Usage { .. } => ExitClass::Usage,
427 Self::InputFormat { .. } | Self::InputData { .. } | Self::Overflow { .. } => {
428 ExitClass::InvalidInput
429 }
430 Self::Io { .. } | Self::System { .. } | Self::InputChanged { .. } => ExitClass::Io,
431 Self::Cancelled => ExitClass::Cancelled,
432 Self::Internal { .. } => ExitClass::Internal,
433 }
434 }
435
436 #[must_use]
439 pub fn is_broken_pipe(&self) -> bool {
440 let stdout = |t: &IoTarget| match t {
441 IoTarget::Stdout => true,
442 IoTarget::Path(p) => {
444 cfg!(unix)
445 && ["/dev/stdout", "/dev/fd/1", "/proc/self/fd/1"]
446 .iter()
447 .any(|alias| p == std::path::Path::new(alias))
448 }
449 IoTarget::Stdin => false,
450 };
451 matches!(
452 self,
453 Self::Io { target, source, .. }
454 if stdout(target) && source.kind() == io::ErrorKind::BrokenPipe
455 )
456 }
457
458 #[must_use]
461 pub fn report(&self) -> String {
462 let mut out = self.to_string();
463 let mut cause = std::error::Error::source(self);
464 while let Some(c) = cause {
465 out.push_str("\ncaused by: ");
466 out.push_str(&c.to_string());
467 cause = c.source();
468 }
469 if let Some(h) = self.hint() {
470 out.push_str("\nhint: ");
471 out.push_str(h);
472 }
473 out
474 }
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480
481 #[test]
482 fn error_stays_small() {
483 assert!(
484 std::mem::size_of::<DimaError>() <= 64,
485 "{}",
486 std::mem::size_of::<DimaError>()
487 );
488 }
489
490 #[test]
491 fn refused_threads_are_not_bugs() {
492 let e = DimaError::system(
493 "8 worker threads",
494 io::Error::from_raw_os_error(11), );
496 assert_eq!(e.to_string(), "cannot start 8 worker threads");
497 assert_eq!(e.class(), ExitClass::Io);
498 assert!(e.hint().unwrap().contains("fewer threads"));
499 assert!(std::error::Error::source(&e).is_some());
500 }
501
502 #[test]
503 fn control_characters_in_names_are_escaped() {
504 let l = Location::new("bad\nname.fa").line(3);
505 assert_eq!(l.to_string(), "bad\\u{a}name.fa: line 3");
506 let t = IoTarget::Path("a\rb.fa".into());
507 assert_eq!(t.to_string(), "'a\\u{d}b.fa'");
508 assert_eq!(shown_name("Zürich spike.fa"), "Zürich spike.fa");
509 }
510
511 #[test]
512 fn location_display() {
513 let l = Location::new("a.fasta")
514 .record(12)
515 .line(45)
516 .column(7)
517 .byte(1234);
518 assert_eq!(
519 l.to_string(),
520 "a.fasta: record 12 (line 45, column 7, byte 1234)"
521 );
522 assert_eq!(
523 Location::new("a.fasta").record(3).to_string(),
524 "a.fasta: record 3"
525 );
526 assert_eq!(
527 Location::new("standard input").line(1).byte(0).to_string(),
528 "standard input: line 1, byte 0"
529 );
530 assert_eq!(Location::new("x").to_string(), "x");
531 }
532
533 #[test]
534 fn classes_and_codes() {
535 let io = DimaError::io(
536 IoAction::Open,
537 IoTarget::Path("missing.fa".into()),
538 io::Error::from(io::ErrorKind::NotFound),
539 );
540 assert_eq!(io.class(), ExitClass::Io);
541 assert_eq!(io.class().code(), 3);
542 assert_eq!(io.to_string(), "cannot open 'missing.fa'");
543 assert_eq!(io.hint(), Some("check the path and the current directory"));
544 assert!(
545 io.report()
546 .starts_with("cannot open 'missing.fa'\ncaused by: ")
547 );
548 assert_eq!(DimaError::usage("bad").class().code(), 2);
549 assert_eq!(
550 DimaError::input_format(Location::new("a"), "x")
551 .class()
552 .code(),
553 4
554 );
555 assert_eq!(DimaError::input_data(None, "x").class().code(), 4);
556 assert_eq!(DimaError::Overflow { what: "support" }.class().code(), 4);
557 assert_eq!(DimaError::internal("x").class().code(), 1);
558 assert_eq!(DimaError::Cancelled.class().code(), 130);
559 }
560
561 #[test]
562 fn hints_and_reports() {
563 let e = DimaError::input_format(Location::new("a.fa").record(2).line(3), "unexpected NUL")
564 .with_hint("convert the file to plain text");
565 assert_eq!(e.to_string(), "a.fa: record 2 (line 3): unexpected NUL");
566 assert_eq!(
567 e.report(),
568 "a.fa: record 2 (line 3): unexpected NUL\nhint: convert the file to plain text"
569 );
570 let d = DimaError::input_data(None, "no positions");
571 assert_eq!(d.to_string(), "no positions");
572 assert!(DimaError::Cancelled.with_hint("x").hint().is_none());
574 }
575
576 #[test]
577 fn broken_pipe_detection() {
578 let e = DimaError::io(
579 IoAction::Write,
580 IoTarget::Stdout,
581 io::Error::from(io::ErrorKind::BrokenPipe),
582 );
583 assert!(e.is_broken_pipe());
584 assert_eq!(e.to_string(), "cannot write standard output");
585 let f = DimaError::io(
586 IoAction::Write,
587 IoTarget::Path("o".into()),
588 io::Error::from(io::ErrorKind::BrokenPipe),
589 );
590 assert!(!f.is_broken_pipe());
591 }
592}