1use crate::common::*;
2
3#[derive(PartialEq, Debug, Clone)]
4pub(crate) enum OutputTarget {
5 Path(PathBuf),
6 Stdout,
7}
8
9impl OutputTarget {
10 pub(crate) fn resolve(&self, env: &Env) -> Result<Self> {
11 match self {
12 Self::Path(path) => Ok(Self::Path(env.resolve(path)?)),
13 Self::Stdout => Ok(Self::Stdout),
14 }
15 }
16
17 pub(crate) fn try_from_os_str(text: &OsStr) -> Result<Self, OsString> {
18 text
19 .try_into()
20 .map_err(|err: Error| OsString::from(err.to_string()))
21 }
22}
23
24impl TryFrom<&OsStr> for OutputTarget {
25 type Error = Error;
26
27 fn try_from(text: &OsStr) -> Result<Self, Self::Error> {
28 if text.is_empty() {
29 return Err(Error::OutputTargetEmpty);
30 };
31
32 if text == OsStr::new("-") {
33 Ok(Self::Stdout)
34 } else {
35 Ok(Self::Path(text.into()))
36 }
37 }
38}
39
40impl Display for OutputTarget {
41 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
42 match self {
43 Self::Stdout => write!(f, "standard output"),
44 Self::Path(path) => write!(f, "`{}`", path.display()),
45 }
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn file() {
55 assert_eq!(
56 OutputTarget::try_from(OsStr::new("foo")).unwrap(),
57 OutputTarget::Path("foo".into())
58 );
59 }
60
61 #[test]
62 fn stdio() {
63 assert_eq!(
64 OutputTarget::try_from(OsStr::new("-")).unwrap(),
65 OutputTarget::Stdout
66 );
67 }
68
69 #[test]
70 fn display_file() {
71 let path = PathBuf::from("./path");
72 let have = OutputTarget::Path(path).to_string();
73 let want = "`./path`";
74 assert_eq!(have, want);
75 }
76
77 #[test]
78 fn display_stdio() {
79 let have = OutputTarget::Stdout.to_string();
80 let want = "standard output";
81 assert_eq!(have, want);
82 }
83}