1use std::{
8 fs,
9 io::{self, Read, Write},
10 path::{Path, PathBuf},
11};
12
13use crate::error::CliError;
14
15fn extension_of(path: &Path) -> Option<String> {
17 path.extension()
18 .map(|ext| ext.to_string_lossy().to_ascii_lowercase())
19}
20
21pub enum Source {
23 Stdin,
25 File(PathBuf),
27}
28
29pub enum Sink {
31 Stdout,
33 File(PathBuf),
35}
36
37impl Source {
38 #[must_use]
40 pub fn from_arg(path: &Path) -> Self {
41 if path.as_os_str() == "-" {
42 Self::Stdin
43 } else {
44 Self::File(path.to_path_buf())
45 }
46 }
47
48 #[must_use]
50 pub fn label(&self) -> String {
51 match self {
52 Self::Stdin => "<stdin>".to_owned(),
53 Self::File(path) => path.display().to_string(),
54 }
55 }
56
57 #[must_use]
59 pub fn extension(&self) -> Option<String> {
60 match self {
61 Self::Stdin => None,
62 Self::File(path) => extension_of(path),
63 }
64 }
65
66 pub fn read(&self) -> Result<Vec<u8>, CliError> {
72 match self {
73 Self::Stdin => {
74 let mut buf = Vec::new();
75 io::stdin()
76 .lock()
77 .read_to_end(&mut buf)
78 .map_err(|err| CliError::read_input(self.label(), &err))?;
79 Ok(buf)
80 },
81 Self::File(path) => {
82 fs::read(path).map_err(|err| CliError::read_input(self.label(), &err))
83 },
84 }
85 }
86}
87
88impl Sink {
89 #[must_use]
91 pub fn from_arg(path: &Path) -> Self {
92 if path.as_os_str() == "-" {
93 Self::Stdout
94 } else {
95 Self::File(path.to_path_buf())
96 }
97 }
98
99 #[must_use]
101 pub fn label(&self) -> String {
102 match self {
103 Self::Stdout => "<stdout>".to_owned(),
104 Self::File(path) => path.display().to_string(),
105 }
106 }
107
108 #[must_use]
110 pub fn extension(&self) -> Option<String> {
111 match self {
112 Self::Stdout => None,
113 Self::File(path) => extension_of(path),
114 }
115 }
116
117 pub fn write(&self, bytes: &[u8]) -> Result<(), CliError> {
123 match self {
124 Self::Stdout => io::stdout()
125 .lock()
126 .write_all(bytes)
127 .map_err(|err| CliError::write_output(self.label(), &err)),
128 Self::File(path) => {
129 fs::write(path, bytes).map_err(|err| CliError::write_output(self.label(), &err))
130 },
131 }
132 }
133}