ctb_formats_utilities/
cli_document.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 document input and output argument structures with format and transformation selection.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::cli_io::{CliInputSourceArgs, CliOutputDestArgs};
30use crate::format_info::format_categorized_help_table;
31use anyhow::Result;
32use std::path::Path;
33
34/// Parses a CLI `--from` value into [`SupportedDcInputFormat`], accepting
35/// short nicknames, Rust `FormatId` names, or `f<N>` shorthands case-insensitively.
36/// On failure, returns a categorized, sorted list of supported formats with descriptions.
37pub fn parse_supported_dc_input_format(
38    s: &str,
39) -> std::result::Result<SupportedDcInputFormat, String> {
40    if let Ok(fmt) = s.parse::<SupportedDcInputFormat>() {
41        return Ok(fmt);
42    }
43    Err(format_categorized_help_table(
44        &format!("Invalid input format '{s}'. Specify --from with one of:"),
45        SupportedDcInputFormat::ALL_FORMAT_IDS,
46    ))
47}
48
49/// Parses a CLI `--to` value into [`SupportedDcOutputFormat`], accepting
50/// short nicknames, Rust `FormatId` names, or `f<N>` shorthands case-insensitively.
51/// On failure, returns a categorized, sorted list of supported formats with descriptions.
52pub fn parse_supported_dc_output_format(
53    s: &str,
54) -> std::result::Result<SupportedDcOutputFormat, String> {
55    if let Ok(fmt) = s.parse::<SupportedDcOutputFormat>() {
56        return Ok(fmt);
57    }
58    Err(format_categorized_help_table(
59        &format!("Invalid output format '{s}'. Specify --to with one of:"),
60        SupportedDcOutputFormat::ALL_FORMAT_IDS,
61    ))
62}
63
64/// Parses a CLI `--transform` value into [`SupportedDcTransformation`], accepting
65/// short nicknames, Rust `FormatId` names, or `f<N>` shorthands case-insensitively.
66/// On failure, returns a categorized, sorted list of supported transformations with descriptions.
67pub fn parse_supported_dc_transformation(
68    s: &str,
69) -> std::result::Result<SupportedDcTransformation, String> {
70    if let Ok(tr) = s.parse::<SupportedDcTransformation>() {
71        return Ok(tr);
72    }
73    Err(format_categorized_help_table(
74        &format!(
75            "Invalid document transformation '{s}'. Specify --transform with one of:"
76        ),
77        SupportedDcTransformation::ALL_FORMAT_IDS,
78    ))
79}
80
81/// CLI document input arguments defaulting to UTF-8 input format.
82#[derive(clap::Args, Debug, Clone, PartialEq, Eq)]
83pub struct CliDocumentInputArgs {
84    /// Input source (positional string or `--file` path)
85    #[command(flatten)]
86    pub source: CliInputSourceArgs,
87
88    /// Input serialization format
89    #[arg(
90        long = "from",
91        value_parser = parse_supported_dc_input_format,
92        default_value = "utf8"
93    )]
94    pub from: SupportedDcInputFormat,
95
96    /// Parse document in permissive/forgiving mode (recovering from invalid headers, characters, or checksums with warnings)
97    #[arg(long = "permissive")]
98    pub permissive: bool,
99}
100
101impl Default for CliDocumentInputArgs {
102    fn default() -> Self {
103        Self {
104            source: CliInputSourceArgs::default(),
105            from: SupportedDcInputFormat::Utf8,
106            permissive: false,
107        }
108    }
109}
110
111impl CliDocumentInputArgs {
112    /// Reads input bytes from the underlying input source.
113    pub fn read_bytes<FRead>(&self, read_data: FRead) -> Result<Vec<u8>>
114    where
115        FRead: Fn(&Path) -> Result<Vec<u8>>,
116    {
117        self.source.read_bytes(read_data)
118    }
119}
120
121/// CLI document input arguments supporting automatic format detection when
122/// `--from` is omitted.
123#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
124pub struct CliAutoDocumentInputArgs {
125    /// Input source (positional string or `--file` path)
126    #[command(flatten)]
127    pub source: CliInputSourceArgs,
128
129    /// Input serialization format (autodetected if omitted)
130    #[arg(long = "from", value_parser = parse_supported_dc_input_format)]
131    pub from: Option<SupportedDcInputFormat>,
132
133    /// Parse document in permissive/forgiving mode (recovering from invalid headers, characters, or checksums with warnings)
134    #[arg(long = "permissive")]
135    pub permissive: bool,
136}
137
138impl CliAutoDocumentInputArgs {
139    /// Reads input bytes from the underlying input source.
140    pub fn read_bytes<FRead>(&self, read_data: FRead) -> Result<Vec<u8>>
141    where
142        FRead: Fn(&Path) -> Result<Vec<u8>>,
143    {
144        self.source.read_bytes(read_data)
145    }
146}
147
148/// CLI document output arguments with target format and transformation options.
149#[derive(clap::Args, Debug, Clone, PartialEq, Eq)]
150pub struct CliDocumentOutputArgs {
151    /// Output destination (`--output` path and `--force` overwrite flag)
152    #[command(flatten)]
153    pub dest: CliOutputDestArgs,
154
155    /// Output serialization format (accepts nickname, `FormatId` name, or f<N> shorthand)
156    #[arg(
157        short = 't',
158        long = "to",
159        value_parser = parse_supported_dc_output_format,
160        default_value = "utf8"
161    )]
162    pub to: SupportedDcOutputFormat,
163
164    /// Document transformation(s) to apply before exporting (accepts nickname, `FormatId` name, or f<N> shorthand)
165    #[arg(
166        long = "transform",
167        value_parser = parse_supported_dc_transformation
168    )]
169    pub transform: Vec<SupportedDcTransformation>,
170}
171
172impl Default for CliDocumentOutputArgs {
173    fn default() -> Self {
174        Self {
175            dest: CliOutputDestArgs::default(),
176            to: SupportedDcOutputFormat::Utf8,
177            transform: Vec::new(),
178        }
179    }
180}
181
182impl CliDocumentOutputArgs {
183    /// Emits output bytes to either stdout or the destination file.
184    pub fn write_or_stdout(&self, data: Vec<u8>) -> Result<Option<Vec<u8>>> {
185        self.dest.write_or_stdout(data)
186    }
187}
188
189#[cfg(test)]
190#[allow(
191    clippy::panic,
192    clippy::expect_used,
193    clippy::unwrap_used,
194    clippy::unwrap_in_result,
195    clippy::panic_in_result_fn,
196    clippy::indexing_slicing,
197    clippy::arithmetic_side_effects,
198    reason = "Standard repository test boilerplate"
199)]
200mod tests {
201    use super::*;
202
203    #[crate::ctb_test]
204    fn test_cli_document_input_args_defaults() {
205        let args = CliDocumentInputArgs::default();
206        assert_eq!(args.from, SupportedDcInputFormat::Utf8);
207        assert!(args.source.is_empty());
208    }
209
210    #[crate::ctb_test]
211    fn test_cli_auto_document_input_args_defaults() {
212        let args = CliAutoDocumentInputArgs::default();
213        assert_eq!(args.from, None);
214        assert!(args.source.is_empty());
215    }
216
217    #[crate::ctb_test]
218    fn test_cli_document_output_args_and_transformation_parser() {
219        let out_args = CliDocumentOutputArgs::default();
220        assert_eq!(out_args.to, SupportedDcOutputFormat::Utf8);
221        assert!(out_args.transform.is_empty());
222        assert!(out_args.dest.is_stdout());
223
224        for name in [
225            "unicode_to_short_dc",
226            "UnicodeToShortDc",
227            "unicodetoshortdc",
228            "f654",
229        ] {
230            assert_eq!(
231                parse_supported_dc_transformation(name).unwrap(),
232                SupportedDcTransformation::UnicodeToShortDc
233            );
234        }
235
236        let err =
237            parse_supported_dc_transformation("not_a_transformation").unwrap_err();
238        assert!(err.contains("Document transformations:"));
239        assert!(err.contains(
240            "unicode_to_short_dc (UnicodeToShortDc): Unicode characters to equivalent short Dcs"
241        ));
242    }
243}