ctb_formats_unicode/
cli.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//! CLI execution helpers for Unicode character descriptions.
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};
30use std::path::{Path, PathBuf};
31
32use crate::character_description::{
33    ControlNameFormat, DescriptionMode, DescriptionOptions, UnicodeVersion,
34};
35
36/// Description format mode for CLI selection.
37#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum CliDescriptionMode {
39    /// Standard enhanced format: concise reserved/PUA/surrogates, multi-alias annotations, Unihan readings.
40    #[default]
41    Standard,
42    /// Exact WUC compatibility format (matches `unicode_untrimmed_descriptions.txt`).
43    WucCompat,
44}
45
46/// Control character name formatting style for CLI selection.
47#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
48pub enum CliControlNameFormat {
49    /// Official UCD `NameAliases` (e.g. ALERT [BEL], END OF LINE [EOL]).
50    #[default]
51    NameAliases,
52    /// Legacy `NamesList` names (e.g. BELL [BEL], LINE FEED [LF], [EOM]).
53    NamesList,
54    /// "What Unicode Character is This" format
55    Wuc,
56}
57
58/// Unicode version for CLI selection.
59#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum CliUnicodeVersion {
61    /// Unicode 17.0 (default)
62    #[default]
63    #[value(name = "17.0", alias = "17")]
64    V17_0,
65    /// Unicode 16.0
66    #[value(name = "16.0", alias = "16")]
67    V16_0,
68    /// Unicode 15.1
69    #[value(name = "15.1", alias = "15.1")]
70    V15_1,
71    /// Unicode 15.0
72    #[value(name = "15.0", alias = "15")]
73    V15_0,
74}
75
76/// Execution arguments for the `character_description` CLI tool.
77#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
78#[command(
79    after_help = "Examples:\n  $ ctoolbox character_description \"Hello\"\n  $ ctoolbox character_description -f input.txt -o output.txt\n  $ ctoolbox character_description --codepoint U+1F602\n  $ ctoolbox character_description --wuc-compat \"Hello\""
80)]
81pub struct CharacterDescriptionArgs {
82    /// Input text containing characters to describe. If not provided, reads from stdin or file.
83    pub input: Option<String>,
84
85    /// Input file path (or - for stdin)
86    #[arg(short = 'f', long = "file")]
87    pub file: Option<PathBuf>,
88
89    /// Output file path (or - for stdout)
90    #[arg(short = 'o', long = "output")]
91    pub output: Option<PathBuf>,
92
93    /// Specific Unicode codepoint (e.g. U+0041, 0x41, 65)
94    #[arg(short = 'c', long = "codepoint")]
95    pub codepoint: Option<String>,
96
97    /// Description format mode (standard or wuc-compat)
98    #[arg(long, value_enum, default_value_t = CliDescriptionMode::Standard)]
99    pub mode: CliDescriptionMode,
100
101    /// Shortcut flag for WUC compatibility mode
102    #[arg(long = "wuc-compat")]
103    pub wuc_compat: bool,
104
105    /// Control character name formatting style
106    #[arg(long = "control-names", value_enum, default_value_t = CliControlNameFormat::NameAliases)]
107    pub control_name_format: CliControlNameFormat,
108
109    /// Unicode version to use for character data (17.0, 16.0, 15.1, 15.0)
110    #[arg(short = 'u', long = "unicode-version", value_enum, default_value_t = CliUnicodeVersion::V17_0)]
111    pub unicode_version: CliUnicodeVersion,
112
113    /// Disable Unihan readings/meanings in standard description output
114    #[arg(long = "no-unihan-readings")]
115    pub no_unihan_readings: bool,
116}
117
118impl From<&CharacterDescriptionArgs> for DescriptionOptions {
119    fn from(args: &CharacterDescriptionArgs) -> Self {
120        let mode =
121            if args.wuc_compat || args.mode == CliDescriptionMode::WucCompat {
122                DescriptionMode::WucCompat
123            } else {
124                DescriptionMode::Standard
125            };
126
127        let control_name_format = if args.wuc_compat {
128            ControlNameFormat::Wuc
129        } else {
130            match args.control_name_format {
131                CliControlNameFormat::NameAliases => {
132                    ControlNameFormat::NameAliases
133                }
134                CliControlNameFormat::NamesList => ControlNameFormat::NamesList,
135                CliControlNameFormat::Wuc => ControlNameFormat::Wuc,
136            }
137        };
138
139        let unicode_version = match args.unicode_version {
140            CliUnicodeVersion::V17_0 => UnicodeVersion::V17_0,
141            CliUnicodeVersion::V16_0 => UnicodeVersion::V16_0,
142            CliUnicodeVersion::V15_1 => UnicodeVersion::V15_1,
143            CliUnicodeVersion::V15_0 => UnicodeVersion::V15_0,
144        };
145
146        let include_unihan_readings = if args.wuc_compat {
147            false
148        } else {
149            !args.no_unihan_readings
150        };
151
152        DescriptionOptions {
153            mode,
154            control_name_format,
155            unicode_version,
156            include_unihan_readings,
157        }
158    }
159}
160
161/// Executes `character_description` CLI command logic.
162///
163/// Returns `Ok(Some(bytes))` if stdout output should be emitted, or
164/// `Ok(None)` if output was written to a destination file.
165pub fn execute_cli_character_description<FRead>(
166    args: CharacterDescriptionArgs,
167    read_data: FRead,
168) -> Result<Option<Vec<u8>>>
169where
170    FRead: Fn(&Path) -> Result<Vec<u8>>,
171{
172    let options = DescriptionOptions::from(&args);
173
174    let result = if let Some(ref cp_str) = args.codepoint {
175        let cp = crate::utilities::string::parse_hex_u32(cp_str)?;
176        let mut out = crate::describe_codepoint_with_options(cp, options);
177        out.push('\n');
178        out
179    } else {
180        let input_text = if let Some(ref file_path) = args.file {
181            let bytes = read_data(file_path)?;
182            String::from_utf8(bytes).context("Input file is not valid UTF-8")?
183        } else if let Some(ref val) = args.input {
184            val.clone()
185        } else {
186            let bytes = read_data(Path::new("-"))?;
187            String::from_utf8(bytes).context("Stdin is not valid UTF-8")?
188        };
189
190        crate::describe_with_options(&input_text, options)
191    };
192
193    if let Some(ref out_path) = args.output {
194        if out_path.as_path() == Path::new("-") {
195            Ok(Some(result.into_bytes()))
196        } else {
197            std::fs::write(out_path, result.as_bytes()).with_context(|| {
198                format!(
199                    "Failed to write output file: {path_display}",
200                    path_display = out_path.display()
201                )
202            })?;
203            Ok(None)
204        }
205    } else {
206        Ok(Some(result.into_bytes()))
207    }
208}
209
210#[cfg(test)]
211#[allow(
212    clippy::panic,
213    clippy::expect_used,
214    clippy::unwrap_used,
215    clippy::unwrap_in_result,
216    clippy::panic_in_result_fn,
217    clippy::indexing_slicing,
218    clippy::arithmetic_side_effects,
219    reason = "Standard repository test boilerplate"
220)]
221mod tests {
222    use super::*;
223    use clap::{Args, Command, FromArgMatches};
224
225    #[crate::ctb_test]
226    fn test_character_description_cli_args_parsing() {
227        let cmd = CharacterDescriptionArgs::augment_args(Command::new(
228            "character_description",
229        ));
230        let matches = cmd
231            .try_get_matches_from(["character_description", "Hello"])
232            .expect("Parse input text");
233        let parsed =
234            CharacterDescriptionArgs::from_arg_matches(&matches).unwrap();
235        assert_eq!(parsed.input, Some("Hello".to_string()));
236        assert_eq!(parsed.file, None);
237        assert_eq!(parsed.output, None);
238        assert_eq!(parsed.codepoint, None);
239
240        let cmd_flags = CharacterDescriptionArgs::augment_args(Command::new(
241            "character_description",
242        ));
243        let matches_flags = cmd_flags
244            .try_get_matches_from([
245                "character_description",
246                "-f",
247                "in.txt",
248                "-o",
249                "out.txt",
250                "--wuc-compat",
251                "--unicode-version",
252                "16.0",
253            ])
254            .expect("Parse with flags");
255        let parsed_flags =
256            CharacterDescriptionArgs::from_arg_matches(&matches_flags).unwrap();
257        assert_eq!(parsed_flags.file, Some(PathBuf::from("in.txt")));
258        assert_eq!(parsed_flags.output, Some(PathBuf::from("out.txt")));
259        assert!(parsed_flags.wuc_compat);
260        assert_eq!(parsed_flags.unicode_version, CliUnicodeVersion::V16_0);
261    }
262
263    #[crate::ctb_test]
264    fn test_parse_codepoints() {
265        assert_eq!(
266            crate::utilities::string::parse_hex_u32("U+0041").unwrap(),
267            0x41
268        );
269        assert_eq!(
270            crate::utilities::string::parse_hex_u32("u+1f602").unwrap(),
271            0x1F602
272        );
273        assert_eq!(
274            crate::utilities::string::parse_hex_u32("0x41").unwrap(),
275            0x41
276        );
277        assert_eq!(
278            crate::utilities::string::parse_hex_u32("0X1F602").unwrap(),
279            0x1F602
280        );
281        assert_eq!(
282            crate::utilities::string::parse_hex_u32("41").unwrap(),
283            0x41
284        );
285    }
286
287    #[crate::ctb_test]
288    fn test_execute_cli_character_description_string() {
289        let args = CharacterDescriptionArgs {
290            input: Some("A".to_string()),
291            ..Default::default()
292        };
293        let out = execute_cli_character_description(args, |_| Ok(Vec::new()))
294            .unwrap();
295        let text = String::from_utf8(out.unwrap()).unwrap();
296        assert_eq!(text, "U+0041 : LATIN CAPITAL LETTER A\n");
297    }
298
299    #[crate::ctb_test]
300    fn test_execute_cli_character_description_codepoint() {
301        let args = CharacterDescriptionArgs {
302            codepoint: Some("U+1F602".to_string()),
303            ..Default::default()
304        };
305        let out = execute_cli_character_description(args, |_| Ok(Vec::new()))
306            .unwrap();
307        let text = String::from_utf8(out.unwrap()).unwrap();
308        assert_eq!(text, "U+1F602 : FACE WITH TEARS OF JOY\n");
309    }
310
311    #[crate::ctb_test]
312    fn test_execute_cli_character_description_file_io() {
313        let temp_dir = tempfile::tempdir().expect("Create temp dir");
314        let in_path = temp_dir.path().join("in.txt");
315        let out_path = temp_dir.path().join("out.txt");
316
317        std::fs::write(&in_path, "A").expect("Write temp file");
318
319        let args = CharacterDescriptionArgs {
320            file: Some(in_path.clone()),
321            output: Some(out_path.clone()),
322            ..Default::default()
323        };
324        let out =
325            execute_cli_character_description(args, |p| Ok(std::fs::read(p)?))
326                .unwrap();
327        assert_eq!(out, None);
328
329        let written = std::fs::read_to_string(out_path).expect("Read output");
330        assert_eq!(written, "U+0041 : LATIN CAPITAL LETTER A\n");
331    }
332
333    #[crate::ctb_test]
334    fn test_execute_cli_character_description_wuc_compat() {
335        let args = CharacterDescriptionArgs {
336            codepoint: Some("U+0000".to_string()),
337            wuc_compat: true,
338            ..Default::default()
339        };
340        let out = execute_cli_character_description(args, |_| Ok(Vec::new()))
341            .unwrap();
342        let text = String::from_utf8(out.unwrap()).unwrap();
343        assert_eq!(text, "U+0000 : <control> NULL [NUL]\n");
344    }
345}