ctb_formats_utilities/
cli_io.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Reusable CLI input and output argument structures for command-line tools.
21
22#[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/// Reusable CLI argument block for commands that accept input from a positional
33/// string argument, a `-f`/`--file` path, or standard input (`-`).
34#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
35pub struct CliInputSourceArgs {
36    /// Input data string. If not provided, reads from stdin or --file.
37    #[arg(value_name = "INPUT")]
38    pub input: Option<String>,
39
40    /// Input file path (or - for stdin)
41    #[arg(short = 'f', long = "file", value_name = "FILE")]
42    pub file: Option<PathBuf>,
43}
44
45impl CliInputSourceArgs {
46    /// Creates a new `CliInputSourceArgs` from a positional input string.
47    #[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    /// Creates a new `CliInputSourceArgs` from a file path.
56    #[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    /// Returns `true` if neither a positional string nor a file path was given.
65    #[must_use]
66    pub fn is_empty(&self) -> bool {
67        self.input.is_none() && self.file.is_none()
68    }
69
70    /// Returns the input file path if `-f`/`--file` was provided.
71    #[must_use]
72    pub fn file_path(&self) -> Option<&Path> {
73        self.file.as_deref()
74    }
75
76    /// Reads input bytes from the specified source.
77    ///
78    /// Resolution order:
79    /// 1. If `--file` is provided, calls `read_data(path)`.
80    /// 2. If a positional `input` string is provided, returns its UTF-8 bytes.
81    /// 3. Otherwise, calls `read_data(Path::new("-"))` to read from stdin.
82    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/// Reusable CLI argument block for commands that write output to a file or stdout.
97#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
98pub struct CliOutputDestArgs {
99    /// Output file path (or - for stdout)
100    #[arg(short = 'o', long = "output", value_name = "OUTPUT")]
101    pub output: Option<PathBuf>,
102
103    /// Overwrite existing output file without prompt
104    #[arg(short = 'F', long = "force")]
105    pub force: bool,
106}
107
108impl CliOutputDestArgs {
109    /// Creates a new `CliOutputDestArgs` writing to stdout.
110    #[must_use]
111    pub fn to_stdout() -> Self {
112        Self {
113            output: None,
114            force: false,
115        }
116    }
117
118    /// Creates a new `CliOutputDestArgs` writing to the specified file path.
119    #[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    /// Returns `true` if output is directed to stdout (`None` or `"-"`).
128    #[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    /// Returns the target destination file path if not writing to stdout.
137    #[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    /// Emits output bytes to either stdout or the destination file.
147    ///
148    /// If output is stdout, returns `Ok(Some(data))` for the caller/runner to emit.
149    /// If output is a file path:
150    /// - If the file exists and `!self.force`, returns an error.
151    /// - Otherwise, writes the data to the file and returns `Ok(None)`.
152    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        // File output with force overwrite
245        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        // Second write without force should fail
258        file_dest.write_or_stdout(b"second".to_vec()).unwrap_err();
259
260        // Write with force should succeed
261        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}