ctb_formats_utilities/
cli_io.rs1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Context, Result, bail};
30use std::path::{Path, PathBuf};
31
32#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
35pub struct CliInputSourceArgs {
36 #[arg(value_name = "INPUT")]
38 pub input: Option<String>,
39
40 #[arg(short = 'f', long = "file", value_name = "FILE")]
42 pub file: Option<PathBuf>,
43}
44
45impl CliInputSourceArgs {
46 #[must_use]
48 pub fn from_input_string(s: impl Into<String>) -> Self {
49 Self {
50 input: Some(s.into()),
51 file: None,
52 }
53 }
54
55 #[must_use]
57 pub fn from_file_path(path: impl Into<PathBuf>) -> Self {
58 Self {
59 input: None,
60 file: Some(path.into()),
61 }
62 }
63
64 #[must_use]
66 pub fn is_empty(&self) -> bool {
67 self.input.is_none() && self.file.is_none()
68 }
69
70 #[must_use]
72 pub fn file_path(&self) -> Option<&Path> {
73 self.file.as_deref()
74 }
75
76 pub fn read_bytes<FRead>(&self, read_data: FRead) -> Result<Vec<u8>>
83 where
84 FRead: Fn(&Path) -> Result<Vec<u8>>,
85 {
86 if let Some(ref path) = self.file {
87 read_data(path)
88 } else if let Some(ref val) = self.input {
89 Ok(val.as_bytes().to_vec())
90 } else {
91 read_data(Path::new("-"))
92 }
93 }
94}
95
96#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
98pub struct CliOutputDestArgs {
99 #[arg(short = 'o', long = "output", value_name = "OUTPUT")]
101 pub output: Option<PathBuf>,
102
103 #[arg(short = 'F', long = "force")]
105 pub force: bool,
106}
107
108impl CliOutputDestArgs {
109 #[must_use]
111 pub fn to_stdout() -> Self {
112 Self {
113 output: None,
114 force: false,
115 }
116 }
117
118 #[must_use]
120 pub fn to_file(path: impl Into<PathBuf>, force: bool) -> Self {
121 Self {
122 output: Some(path.into()),
123 force,
124 }
125 }
126
127 #[must_use]
129 pub fn is_stdout(&self) -> bool {
130 match &self.output {
131 None => true,
132 Some(path) => path.as_os_str() == "-",
133 }
134 }
135
136 #[must_use]
138 pub fn output_path(&self) -> Option<&Path> {
139 if self.is_stdout() {
140 None
141 } else {
142 self.output.as_deref()
143 }
144 }
145
146 pub fn write_or_stdout(&self, data: Vec<u8>) -> Result<Option<Vec<u8>>> {
153 if self.is_stdout() {
154 Ok(Some(data))
155 } else {
156 let path = self
157 .output
158 .as_ref()
159 .context("Output destination path is missing")?;
160 if path.exists() && !self.force {
161 bail!(
162 "Output file '{}' already exists. Use -F / --force to overwrite.",
163 path.display()
164 );
165 }
166 std::fs::write(path, &data).with_context(|| {
167 format!(
168 "Failed to write output file: {path_display}",
169 path_display = path.display()
170 )
171 })?;
172 Ok(None)
173 }
174 }
175}
176
177#[cfg(test)]
178#[allow(
179 clippy::panic,
180 clippy::expect_used,
181 clippy::unwrap_used,
182 clippy::unwrap_in_result,
183 clippy::panic_in_result_fn,
184 clippy::indexing_slicing,
185 clippy::arithmetic_side_effects,
186 reason = "Standard repository test boilerplate"
187)]
188mod tests {
189 use super::*;
190
191 #[crate::ctb_test]
192 fn test_cli_input_source_args() {
193 let positional = CliInputSourceArgs::from_input_string("hello");
194 assert_eq!(
195 positional.read_bytes(|_| Ok(Vec::new())).unwrap(),
196 b"hello"
197 );
198
199 let file_arg = CliInputSourceArgs::from_file_path("test.txt");
200 assert_eq!(file_arg.file_path(), Some(Path::new("test.txt")));
201 assert_eq!(
202 file_arg
203 .read_bytes(|p| {
204 assert_eq!(p, Path::new("test.txt"));
205 Ok(b"file content".to_vec())
206 })
207 .unwrap(),
208 b"file content"
209 );
210
211 let stdin_arg = CliInputSourceArgs::default();
212 assert!(stdin_arg.is_empty());
213 assert_eq!(
214 stdin_arg
215 .read_bytes(|p| {
216 assert_eq!(p, Path::new("-"));
217 Ok(b"stdin content".to_vec())
218 })
219 .unwrap(),
220 b"stdin content"
221 );
222 }
223
224 #[crate::ctb_test]
225 fn test_cli_output_dest_args() {
226 let stdout_dest = CliOutputDestArgs::to_stdout();
227 assert!(stdout_dest.is_stdout());
228 assert_eq!(stdout_dest.output_path(), None);
229 assert_eq!(
230 stdout_dest.write_or_stdout(b"test".to_vec()).unwrap(),
231 Some(b"test".to_vec())
232 );
233
234 let dash_dest = CliOutputDestArgs {
235 output: Some(PathBuf::from("-")),
236 force: false,
237 };
238 assert!(dash_dest.is_stdout());
239 assert_eq!(
240 dash_dest.write_or_stdout(b"dash".to_vec()).unwrap(),
241 Some(b"dash".to_vec())
242 );
243
244 let temp_dir = std::env::temp_dir();
246 let target_path = temp_dir.join("test_cli_output_dest_args.tmp");
247 if target_path.exists() {
248 let _ = std::fs::remove_file(&target_path);
249 }
250
251 let file_dest = CliOutputDestArgs::to_file(&target_path, false);
252 assert!(!file_dest.is_stdout());
253 assert_eq!(file_dest.output_path(), Some(target_path.as_path()));
254 assert_eq!(file_dest.write_or_stdout(b"first".to_vec()).unwrap(), None);
255 assert_eq!(std::fs::read(&target_path).unwrap(), b"first");
256
257 file_dest.write_or_stdout(b"second".to_vec()).unwrap_err();
259
260 let file_dest_force = CliOutputDestArgs::to_file(&target_path, true);
262 assert_eq!(
263 file_dest_force.write_or_stdout(b"second".to_vec()).unwrap(),
264 None
265 );
266 assert_eq!(std::fs::read(&target_path).unwrap(), b"second");
267
268 let _ = std::fs::remove_file(&target_path);
269 }
270}