aboutsummaryrefslogtreecommitdiff
path: root/src/error.rs
blob: e592e50959284a5ec9a78bda34d8e884d5ad757f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::{
	env,
	ffi::OsString,
	fmt::{self, Display, Formatter},
	io,
	path::PathBuf,
};

pub enum Error {
	BadArgs(Option<lexopt::Error>),
	BadDecoding(String),
	BadLengths,
	DuplicateInput(PathBuf),
	DuplicateOutput(PathBuf),
	IO(io::Error),
	Nop,
	SpawnFailed(OsString, io::Error),
}

impl Display for Error {
	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
		let p = env::args().next().unwrap();
		match self {
			Self::BadArgs(o) => {
				if let Some(v) = o {
					writeln!(f, "{p}: {v}")?;
				}
				writeln!(f, "Usage: {p} [-0eiv] command [argument ...]")
			}
			Self::BadDecoding(s) => writeln!(f, "{p}: Decoding the file “{s}” failed!"),
			Self::BadLengths => writeln!(f, "{p}: Files have been added or removed during editing"),
			Self::DuplicateInput(s) => writeln!(
				f,
				"{p}: Input file “{}” specified more than once",
				s.to_string_lossy()
			),
			Self::DuplicateOutput(s) => writeln!(
				f,
				"{p}: Output file “{}” specified more than once",
				s.to_string_lossy()
			),
			Self::IO(e) => writeln!(f, "{p}: {e}"),
			Self::Nop => Ok(()),
			Self::SpawnFailed(ed, e) => writeln!(
				f,
				"{p}: Failed to spawn utility “{}”: {e}",
				ed.to_string_lossy()
			),
		}
	}
}

impl From<io::Error> for Error {
	fn from(e: io::Error) -> Self {
		Self::IO(e)
	}
}

impl From<lexopt::Error> for Error {
	fn from(e: lexopt::Error) -> Self {
		Self::BadArgs(Some(e))
	}
}