ctb_formats_conversion/
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 unified character descriptions across all supported document formats.
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
32use crate::convert_api::{
33    DcConversionOptions, DcExportOptions, DcNormalizationMode, FormatSpec,
34    convert_bytes_to_dcmstring, convert_dcmstring_to_bytes,
35};
36use crate::convert_bytes::{
37    format_supported_input_formats_table, format_supported_output_formats_table,
38    format_supported_transformations_table,
39};
40use ctb_formats_dcstring::character_description::{
41    ControlNameFormat, DescriptionMode, DescriptionOptions, UnicodeVersion,
42    describe_dclist, describe_graph_id,
43};
44pub use ctb_formats_unicode::cli::{
45    CliControlNameFormat, CliDescriptionMode, CliUnicodeVersion,
46};
47use ctb_formats_utilities::{
48    CliAutoDocumentInputArgs, CliDocumentOutputArgs, CliInputSourceArgs,
49    CliOutputDestArgs, parse_supported_dc_input_format,
50    parse_supported_dc_output_format, parse_supported_dc_transformation,
51};
52pub use ctb_utilities::{
53    SupportedDcInputFormat, SupportedDcOutputFormat, SupportedDcTransformation,
54};
55
56fn parse_codepoint_arg(token: &str) -> Result<u128> {
57    let trimmed = token.trim();
58    if trimmed.is_empty() {
59        bail!("Empty codepoint argument");
60    }
61    ctb_formats_dcstring::cli_identifiers::parse_graph_or_short_id(trimmed)
62}
63
64/// Global static lazy string containing the formatted `character_description` help table and examples.
65pub static CHARACTER_DESCRIPTION_AFTER_HELP: std::sync::LazyLock<String> =
66    std::sync::LazyLock::new(|| {
67        let formats = format_supported_input_formats_table(
68            "Supported input formats (--from):",
69        );
70        format!(
71            "{formats}\n\nExamples:\n  $ ctoolbox character_description \"Hello\"\n  $ ctoolbox character_description --codepoint U+1F602\n  $ ctoolbox character_description --wuc-compat \"Hello\"\n  $ ctoolbox character_description --from dcal \"65 1114408 2228304\"\n  $ ctoolbox character_description --codepoint dc:296\n  $ ctoolbox character_description --from dcmm --permissive -f input.bin\n  $ ctoolbox character_description -f input.txt -o output.txt"
72        )
73    });
74
75/// Global static lazy string containing the formatted `convert` help table and examples.
76pub static CONVERT_AFTER_HELP: std::sync::LazyLock<String> =
77    std::sync::LazyLock::new(|| {
78        let in_formats = format_supported_input_formats_table(
79            "Supported input formats (--from):",
80        );
81        let out_formats = format_supported_output_formats_table(
82            "Supported output formats (--to):",
83        );
84        let transformations = format_supported_transformations_table(
85            "Supported transformations (--transform):",
86        );
87        format!(
88            "{in_formats}\n\n{out_formats}\n\n{transformations}\n\nExamples:\n  $ ctoolbox convert --from dcal --to dctext \"65 1114408 2228304\"\n  $ ctoolbox convert -f input.dcal -o output.txt --to utf8\n  $ ctoolbox convert --to dcts \"hello world\"\n  $ ctoolbox convert --from ascii --to sems --transform unicode_to_short_dc \"hello\"\n  $ ctoolbox convert -f input.cscjournal -o output.dcal --to dcal\n  $ ctoolbox convert --from dcmm --permissive -f input.bin --to dctext"
89        )
90    });
91
92/// Supported input serialization formats for character descriptions.
93pub type CharacterDescriptionInputFormat = SupportedDcInputFormat;
94
95/// Execution arguments for the `character_description` CLI tool.
96#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
97pub struct CharacterDescriptionArgs {
98    /// Input text containing characters/IDs to describe. If not provided, reads from stdin or file.
99    pub input: Option<String>,
100
101    /// Input format (autodetected if omitted; accepts nickname, `FormatId` name, or f<N> shorthand)
102    #[arg(long = "from", value_parser = parse_supported_dc_input_format)]
103    pub from: Option<SupportedDcInputFormat>,
104
105    /// Parse and export document in permissive/forgiving mode (recovering from invalid headers, characters, or checksums with warnings)
106    #[arg(long = "permissive")]
107    pub permissive: bool,
108
109    /// Parse and export document in strict mode (rejecting invalid headers, characters, or non-canonical sequences)
110    #[arg(long = "strict", conflicts_with = "permissive")]
111    pub strict: bool,
112
113    /// Input file path (or - for stdin)
114    #[arg(short = 'f', long = "file")]
115    pub file: Option<PathBuf>,
116
117    /// Output file path (or - for stdout)
118    #[arg(short = 'o', long = "output")]
119    pub output: Option<PathBuf>,
120
121    /// Overwrite existing output file without prompt
122    #[arg(short = 'F', long = "force")]
123    pub force: bool,
124
125    /// Specific character, Dc ID, or Global Graph ID (e.g. U+0041, dc:296, 1114408, fmt:80)
126    #[arg(short = 'c', long = "codepoint")]
127    pub codepoint: Option<String>,
128
129    /// Description format mode (standard or wuc-compat)
130    #[arg(long, value_enum, default_value_t = CliDescriptionMode::Standard)]
131    pub mode: CliDescriptionMode,
132
133    /// Shortcut flag for WUC compatibility mode
134    #[arg(long = "wuc-compat")]
135    pub wuc_compat: bool,
136
137    /// Control character name formatting style
138    #[arg(long = "control-names", value_enum, default_value_t = CliControlNameFormat::NameAliases)]
139    pub control_name_format: CliControlNameFormat,
140
141    /// Unicode version to use for character data (17.0, 16.0, 15.1, 15.0)
142    #[arg(short = 'u', long = "unicode-version", value_enum, default_value_t = CliUnicodeVersion::V17_0)]
143    pub unicode_version: CliUnicodeVersion,
144
145    /// Disable Unihan readings/meanings in standard description output
146    #[arg(long = "no-unihan-readings")]
147    pub no_unihan_readings: bool,
148
149    /// Document transformation(s) to apply before describing characters (accepts nickname, `FormatId` name, or f<N> shorthand)
150    #[arg(
151        long = "transform",
152        value_parser = parse_supported_dc_transformation
153    )]
154    pub transform: Vec<SupportedDcTransformation>,
155}
156
157impl CharacterDescriptionArgs {
158    /// Adapts the CLI input fields into [`CliInputSourceArgs`].
159    #[must_use]
160    pub fn input_source(&self) -> CliInputSourceArgs {
161        CliInputSourceArgs {
162            input: self.input.clone(),
163            file: self.file.clone(),
164        }
165    }
166
167    /// Adapts the CLI document input fields into [`CliAutoDocumentInputArgs`].
168    #[must_use]
169    pub fn document_input(&self) -> CliAutoDocumentInputArgs {
170        CliAutoDocumentInputArgs {
171            source: self.input_source(),
172            from: self.from,
173            permissive: self.permissive,
174        }
175    }
176
177    /// Adapts the CLI output fields into [`CliOutputDestArgs`].
178    #[must_use]
179    pub fn output_dest(&self) -> CliOutputDestArgs {
180        CliOutputDestArgs {
181            output: self.output.clone(),
182            force: self.force,
183        }
184    }
185}
186
187impl From<&CharacterDescriptionArgs> for DescriptionOptions {
188    fn from(args: &CharacterDescriptionArgs) -> Self {
189        let mode =
190            if args.wuc_compat || args.mode == CliDescriptionMode::WucCompat {
191                DescriptionMode::WucCompat
192            } else {
193                DescriptionMode::Standard
194            };
195
196        let control_name_format = if args.wuc_compat {
197            ControlNameFormat::Wuc
198        } else {
199            match args.control_name_format {
200                CliControlNameFormat::NameAliases => {
201                    ControlNameFormat::NameAliases
202                }
203                CliControlNameFormat::NamesList => ControlNameFormat::NamesList,
204                CliControlNameFormat::Wuc => ControlNameFormat::Wuc,
205            }
206        };
207
208        let unicode_version = match args.unicode_version {
209            CliUnicodeVersion::V17_0 => UnicodeVersion::V17_0,
210            CliUnicodeVersion::V16_0 => UnicodeVersion::V16_0,
211            CliUnicodeVersion::V15_1 => UnicodeVersion::V15_1,
212            CliUnicodeVersion::V15_0 => UnicodeVersion::V15_0,
213        };
214
215        let include_unihan_readings = if args.wuc_compat {
216            false
217        } else {
218            !args.no_unihan_readings
219        };
220
221        DescriptionOptions {
222            mode,
223            control_name_format,
224            unicode_version,
225            include_unihan_readings,
226        }
227    }
228}
229
230/// Executes `character_description` CLI command logic.
231///
232/// Uses the unified single-function [`convert_bytes_to_dcmstring`] conversion API to
233/// parse any supported input format directly into a `DcMstring`.
234///
235/// Returns `Ok(Some(bytes))` if stdout output should be emitted, or
236/// `Ok(None)` if output was written to a destination file.
237pub fn execute_cli_character_description<FRead>(
238    args: CharacterDescriptionArgs,
239    read_data: FRead,
240) -> Result<Option<Vec<u8>>>
241where
242    FRead: Fn(&Path) -> Result<Vec<u8>>,
243{
244    let options = DescriptionOptions::from(&args);
245
246    let result = if let Some(ref cp_str) = args.codepoint {
247        let id = parse_codepoint_arg(cp_str)?;
248        let mut out = describe_graph_id(id, options);
249        out.push('\n');
250        out
251    } else {
252        let input_bytes = args.input_source().read_bytes(&read_data)?;
253        let filename_hint = args.file.as_deref().and_then(|p| {
254            if p == Path::new("-") {
255                None
256            } else {
257                p.file_name().and_then(|n| n.to_str())
258            }
259        });
260        let conversion = convert_bytes_to_dcmstring(
261            &input_bytes,
262            filename_hint,
263            &DcConversionOptions {
264                // Reason for fallback: When no source format is explicitly specified via CLI, auto-detection is used.
265                format: args.from.map_or(FormatSpec::Auto, FormatSpec::Format),
266                allow_binary_encapsulation: false,
267                permissive: args.permissive,
268            },
269        )?;
270        let mut log = conversion.log;
271        let doc = if args.transform.is_empty() {
272            conversion.document
273        } else {
274            let (tr_doc, tr_log) = ctb_formats_dcstring::apply_dc_transformations(
275                &conversion.document,
276                &args.transform,
277            )?;
278            log.merge(&tr_log);
279            tr_doc
280        };
281        log.auto_log();
282        if log.has_errors() {
283            eprintln!("{}", log.format_errors().trim_end());
284        }
285        if log.has_warnings() {
286            eprintln!("{}", log.format_warnings().trim_end());
287        }
288        let policy = if args.permissive {
289            ctb_formats_dcstring::DcProjectionPolicy::forgiving()
290        } else {
291            ctb_formats_dcstring::DcProjectionPolicy::strict()
292        };
293        let dc_string = doc.to_dc_string_with_policy(&policy)?;
294        let dclist = dc_string.to_dclist();
295        describe_dclist(&dclist, options)
296    };
297
298    args.output_dest().write_or_stdout(result.into_bytes())
299}
300
301/// Execution arguments for the `convert` CLI tool.
302#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
303pub struct ConvertArgs {
304    /// Input data string. If not provided, reads from stdin or --file.
305    pub input: Option<String>,
306
307    /// Input format (autodetected if omitted; accepts nickname, `FormatId` name, or f<N> shorthand)
308    #[arg(long = "from", value_parser = parse_supported_dc_input_format)]
309    pub from: Option<SupportedDcInputFormat>,
310
311    /// Parse and export document in permissive/forgiving mode (recovering from invalid headers, characters, or checksums with warnings)
312    #[arg(long = "permissive")]
313    pub permissive: bool,
314
315    /// Parse and export document in strict mode (rejecting invalid headers, characters, or non-canonical sequences)
316    #[arg(long = "strict", conflicts_with = "permissive")]
317    pub strict: bool,
318
319    /// Character and Unicode normalization policy (none, as-needed, all)
320    #[arg(long = "normalize", value_enum)]
321    pub normalize: Option<DcNormalizationMode>,
322
323    /// Output format (accepts nickname, `FormatId` name, or f<N> shorthand)
324    #[arg(short = 't', long = "to", value_parser = parse_supported_dc_output_format, default_value = "utf8")]
325    pub to: SupportedDcOutputFormat,
326
327    /// Document transformation(s) to apply before exporting (accepts nickname, `FormatId` name, or f<N> shorthand)
328    #[arg(
329        long = "transform",
330        value_parser = parse_supported_dc_transformation
331    )]
332    pub transform: Vec<SupportedDcTransformation>,
333
334    /// Input file path (or - for stdin)
335    #[arg(short = 'f', long = "file")]
336    pub file: Option<PathBuf>,
337
338    /// Output file path (or - for stdout)
339    #[arg(short = 'o', long = "output")]
340    pub output: Option<PathBuf>,
341
342    /// Overwrite existing output file without prompt
343    #[arg(short = 'F', long = "force")]
344    pub force: bool,
345
346    /// Allow encapsulating arbitrary binary bytes into `DcMixed` mode if input format cannot be decoded
347    #[arg(long = "allow-binary-encapsulation")]
348    pub allow_binary_encapsulation: bool,
349}
350
351impl ConvertArgs {
352    /// Adapts the CLI input fields into [`CliInputSourceArgs`].
353    #[must_use]
354    pub fn input_source(&self) -> CliInputSourceArgs {
355        CliInputSourceArgs {
356            input: self.input.clone(),
357            file: self.file.clone(),
358        }
359    }
360
361    /// Adapts the CLI document input fields into [`CliAutoDocumentInputArgs`].
362    #[must_use]
363    pub fn document_input(&self) -> CliAutoDocumentInputArgs {
364        CliAutoDocumentInputArgs {
365            source: self.input_source(),
366            from: self.from,
367            permissive: self.permissive,
368        }
369    }
370
371    /// Adapts the CLI output fields into [`CliOutputDestArgs`].
372    #[must_use]
373    pub fn output_dest(&self) -> CliOutputDestArgs {
374        CliOutputDestArgs {
375            output: self.output.clone(),
376            force: self.force,
377        }
378    }
379
380    /// Adapts the CLI document output fields into [`CliDocumentOutputArgs`].
381    #[must_use]
382    pub fn document_output(&self) -> CliDocumentOutputArgs {
383        CliDocumentOutputArgs {
384            dest: self.output_dest(),
385            to: self.to,
386            transform: self.transform.clone(),
387        }
388    }
389}
390
391/// Executes `convert` CLI command logic.
392///
393/// Converts documents between supported formats using [`convert_bytes_to_dcmstring`]
394/// and [`convert_dcmstring_to_bytes`].
395///
396/// Returns `Ok(Some(bytes))` if stdout output should be emitted, or
397/// `Ok(None)` if output was written to a destination file.
398pub fn execute_cli_convert<FRead>(
399    args: ConvertArgs,
400    read_data: FRead,
401) -> Result<Option<Vec<u8>>>
402where
403    FRead: Fn(&Path) -> Result<Vec<u8>>,
404{
405    let input_bytes = args.input_source().read_bytes(&read_data)?;
406    let filename_hint = args.file.as_deref().and_then(|p| {
407        if p == Path::new("-") {
408            None
409        } else {
410            p.file_name().and_then(|n| n.to_str())
411        }
412    });
413
414    let permissive = args.permissive && !args.strict;
415
416    let conversion_options = DcConversionOptions {
417        format: match args.from {
418            Some(fmt) => FormatSpec::Format(fmt),
419            None => FormatSpec::Auto,
420        },
421        allow_binary_encapsulation: args.allow_binary_encapsulation,
422        permissive,
423    };
424
425    let conversion = convert_bytes_to_dcmstring(
426        &input_bytes,
427        filename_hint,
428        &conversion_options,
429    )?;
430
431    let export_options = DcExportOptions {
432        format: args.to,
433        permissive,
434        normalization: args.normalize,
435        transformations: args.transform.clone(),
436    };
437
438    let export = convert_dcmstring_to_bytes(
439        &conversion.document,
440        args.to,
441        &export_options,
442    )?;
443
444    let mut log = conversion.log;
445    log.merge(&export.log);
446    log.auto_log();
447    if log.has_errors() {
448        eprintln!("{}", log.format_errors().trim_end());
449    }
450    if log.has_warnings() {
451        eprintln!("{}", log.format_warnings().trim_end());
452    }
453
454    args.output_dest().write_or_stdout(export.bytes)
455}
456
457#[cfg(test)]
458#[allow(
459    clippy::panic,
460    clippy::expect_used,
461    clippy::unwrap_used,
462    clippy::unwrap_in_result,
463    clippy::panic_in_result_fn,
464    clippy::indexing_slicing,
465    clippy::arithmetic_side_effects,
466    reason = "Standard repository test boilerplate"
467)]
468mod tests {
469    use super::*;
470
471    #[crate::ctb_test]
472    fn test_execute_cli_utf8_default() {
473        let args = CharacterDescriptionArgs {
474            input: Some("A".to_string()),
475            ..Default::default()
476        };
477        let out = execute_cli_character_description(args, |_| Ok(Vec::new()))
478            .unwrap()
479            .unwrap();
480        assert_eq!(
481            String::from_utf8(out).unwrap(),
482            "U+0041 : LATIN CAPITAL LETTER A\n"
483        );
484    }
485
486    #[crate::ctb_test]
487    fn test_execute_cli_dcal_format() {
488        let args = CharacterDescriptionArgs {
489            input: Some("65 1114408 2228304".to_string()),
490            from: Some(CharacterDescriptionInputFormat::Dcal),
491            ..Default::default()
492        };
493        let out = execute_cli_character_description(args, |_| Ok(Vec::new()))
494            .unwrap()
495            .unwrap();
496        let text = String::from_utf8(out).unwrap();
497        let lines: Vec<&str> = text.lines().collect();
498        assert_eq!(lines.len(), 3);
499        assert_eq!(lines[0], "U+0041 : LATIN CAPITAL LETTER A");
500        assert!(lines[1].starts_with(
501            "1114408 : <Dc> Next number is a Dc-equivalent reference"
502        ));
503        assert!(lines[2].starts_with("2228304 : String"));
504    }
505
506    #[crate::ctb_test]
507    fn test_execute_cli_dcil_format() {
508        let args = CharacterDescriptionArgs {
509            input: Some("296 21".to_string()),
510            from: Some(CharacterDescriptionInputFormat::Dcil),
511            ..Default::default()
512        };
513        let out = execute_cli_character_description(args, |_| Ok(Vec::new()))
514            .unwrap()
515            .unwrap();
516        let text = String::from_utf8(out).unwrap();
517        let lines: Vec<&str> = text.lines().collect();
518        assert_eq!(lines.len(), 2);
519        assert!(lines[0].starts_with(
520            "1114408 : <Dc> Next number is a Dc-equivalent reference"
521        ));
522        assert!(lines[1].starts_with("1114133 : <Dc> Number sign"));
523    }
524
525    #[crate::ctb_test]
526    fn test_execute_cli_codepoint_dc() {
527        let args = CharacterDescriptionArgs {
528            codepoint: Some("dc:296".to_string()),
529            ..Default::default()
530        };
531        let out = execute_cli_character_description(args, |_| Ok(Vec::new()))
532            .unwrap()
533            .unwrap();
534        let text = String::from_utf8(out).unwrap();
535        assert!(text.starts_with(
536            "1114408 : <Dc> Next number is a Dc-equivalent reference"
537        ));
538    }
539
540    #[crate::ctb_test]
541    fn test_execute_cli_utf8_invalid_error_hint() {
542        let invalid_utf8_bytes = vec![0x68, 0x69, 0xff, 0x84];
543        let args = CharacterDescriptionArgs {
544            from: Some(CharacterDescriptionInputFormat::Utf8),
545            ..Default::default()
546        };
547        let err = execute_cli_character_description(args, |_| {
548            Ok(invalid_utf8_bytes.clone())
549        })
550        .unwrap_err();
551        let err_msg = format!("{err:?}");
552        assert!(err_msg.contains("NOTE: Parsing as UTF-8. If you want DcText, pass `--from dctext` on the command line."));
553    }
554
555    #[crate::ctb_test]
556    fn test_execute_cli_dctext_binary_dcutf_input() {
557        let text = "hi @64@ @L42@";
558        let raw_bytes =
559            ctb_formats_dcstring::converters::dctext::dctext_to_dcutf(
560                text.as_bytes().to_vec(),
561            )
562            .expect("convert dctext to dcutf");
563        let args = CharacterDescriptionArgs {
564            from: Some(CharacterDescriptionInputFormat::DcText),
565            ..Default::default()
566        };
567        let out =
568            execute_cli_character_description(args, |_| Ok(raw_bytes.clone()))
569                .unwrap()
570                .unwrap();
571        let desc = String::from_utf8(out).unwrap();
572        assert!(desc.contains("U+0068 : LATIN SMALL LETTER H"));
573        assert!(desc.contains(
574            "1114408 : <Dc> Next number is a Dc-equivalent reference"
575        ));
576        assert!(desc.contains("1114118 : <Dc> Begin number"));
577        assert!(desc.contains("2228423"));
578        assert!(desc.contains("1114119 : <Dc> End number"));
579    }
580
581    #[crate::ctb_test]
582    fn test_execute_cli_user_hex_input() {
583        let raw_bytes: Vec<u8> = vec![
584            0x68, 0x69, 0x20, 0x40, 0x20, 0x40, 0x20, 0x41, 0x20, 0xc2, 0x80,
585            0x20, 0x74, 0x68, 0x65, 0x72, 0x65, 0x20, 0xf0, 0x9f, 0xa5, 0xb4,
586            0x20, 0xff, 0x84, 0x84, 0x90, 0x84, 0xa8, 0xff, 0x84, 0x84, 0x90,
587            0x80, 0x86, 0xff, 0x84, 0x88, 0xa0, 0x83, 0x87, 0xff, 0x84, 0x84,
588            0x90, 0x82, 0xa9, 0xff, 0x84, 0x84, 0x90, 0x80, 0x87, 0x20, 0x6e,
589            0x6f, 0x6e, 0x63, 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72,
590            0x20, 0xf4, 0x8f, 0xbf, 0xbf, 0x20, 0x73, 0x75, 0x72, 0x72, 0x6f,
591            0x67, 0x61, 0x74, 0x65, 0x20, 0xed, 0xad, 0xbf, 0x20, 0x75, 0x6e,
592            0x69, 0x63, 0x6f, 0x64, 0x65, 0x20, 0x6e, 0x75, 0x6c, 0x6c, 0x20,
593            0x00, 0x20, 0x64, 0x63, 0x20, 0x6e, 0x75, 0x6c, 0x6c, 0x20, 0xff,
594            0x84, 0x84, 0x90, 0x80, 0x80, 0x20, 0xff, 0x86, 0x82, 0x80, 0x80,
595            0x80, 0x80, 0x80, 0x20, 0x32, 0x5e, 0x31, 0x32, 0x38, 0x2d, 0x31,
596            0x20, 0xff, 0x96, 0x83, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf,
597            0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf,
598            0xbf, 0xbf, 0xbf,
599        ];
600        let args = CharacterDescriptionArgs {
601            from: Some(CharacterDescriptionInputFormat::DcText),
602            ..Default::default()
603        };
604        let out =
605            execute_cli_character_description(args, |_| Ok(raw_bytes.clone()))
606                .unwrap()
607                .unwrap();
608        let desc = String::from_utf8(out).unwrap();
609        assert!(desc.contains("U+0068 : LATIN SMALL LETTER H"));
610    }
611
612    #[crate::ctb_test]
613    fn test_character_description_command() {
614        let args = CharacterDescriptionArgs {
615            input: Some("A".to_string()),
616            ..Default::default()
617        };
618        let out =
619            execute_cli_character_description(args, |p| Ok(std::fs::read(p)?))
620                .expect("Run character_description")
621                .unwrap_or_default();
622        assert_eq!(
623            String::from_utf8(out).expect("UTF-8 stdout"),
624            "U+0041 : LATIN CAPITAL LETTER A\n"
625        );
626    }
627
628    #[crate::ctb_test]
629    fn test_character_description_dcal_command() {
630        let args_dcal = CharacterDescriptionArgs {
631            input: Some("65 1114408 2228304".to_string()),
632            from: Some(CharacterDescriptionInputFormat::Dcal),
633            ..Default::default()
634        };
635        let out_dcal = execute_cli_character_description(args_dcal, |p| {
636            Ok(std::fs::read(p)?)
637        })
638        .expect("Run character_description --from dcal")
639        .unwrap_or_default();
640        let s = String::from_utf8(out_dcal).expect("UTF-8 stdout");
641        let lines: Vec<&str> = s.lines().collect();
642        assert_eq!(lines.len(), 3);
643        assert_eq!(lines[0], "U+0041 : LATIN CAPITAL LETTER A");
644        assert!(lines[1].starts_with(
645            "1114408 : <Dc> Next number is a Dc-equivalent reference"
646        ));
647        assert!(lines[2].starts_with("2228304 : String"));
648    }
649
650    #[crate::ctb_test]
651    fn test_character_description_from_dcts() {
652        let args = CharacterDescriptionArgs {
653            input: Some("a @123@ @f80@".to_string()),
654            from: Some(CharacterDescriptionInputFormat::Dcts),
655            ..Default::default()
656        };
657        let out =
658            execute_cli_character_description(args, |p| Ok(std::fs::read(p)?))
659                .expect("Run character_description with dcts")
660                .unwrap_or_default();
661        let desc = String::from_utf8(out).expect("UTF-8 stdout");
662        assert!(desc.contains("U+0061 : LATIN SMALL LETTER A"));
663        assert!(desc.contains("1114235"));
664        assert!(desc.contains("2228304"));
665    }
666
667    #[crate::ctb_test]
668    fn test_character_description_from_cscjournal() {
669        let fixture_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
670            .join("../../io/csc/fixtures/journals");
671        let fixtures = [
672            "v1_ctbmeta1-20261011.cscjournal",
673            "v2_ctbmeta2-20261011.cscjournal",
674            "v3_ctbmeta3-20261011.cscjournal",
675            "v4_dcmixed-20261011.cscjournal",
676        ];
677
678        for fixture_name in fixtures {
679            let fixture_path = fixture_dir.join(fixture_name);
680            let journal_bytes =
681                std::fs::read(&fixture_path).expect("read journal fixture");
682
683            let args = CharacterDescriptionArgs {
684                from: Some(CharacterDescriptionInputFormat::CscJournal),
685                file: Some(fixture_path.clone()),
686                ..Default::default()
687            };
688
689            let out = execute_cli_character_description(args, |_| {
690                Ok(journal_bytes.clone())
691            })
692            .expect("Run character_description with cscjournal")
693            .unwrap_or_default();
694
695            let desc =
696                String::from_utf8(out).expect("UTF-8 output from description");
697            assert!(
698                !desc.is_empty(),
699                "Output for {fixture_name} should not be empty"
700            );
701            // Verify that Document Characters are present in description output
702            assert!(
703                desc.contains("1114408") || desc.contains("<Dc>"),
704                "Description for {fixture_name} should contain described Dcs"
705            );
706        }
707    }
708
709    #[crate::ctb_test]
710    fn test_character_description_autodetect_dcmm() {
711        let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR")).join(
712            "../../io/csc/fixtures/journals/v4_dcmixed_only-20261010.dcmm",
713        );
714        let bytes = std::fs::read(&fixture_path).expect("read dcmm fixture");
715        let args = CharacterDescriptionArgs {
716            file: Some(fixture_path),
717            ..Default::default()
718        };
719        let out =
720            execute_cli_character_description(args, |_| Ok(bytes.clone()))
721                .expect("Run character_description with auto-detected dcmm")
722                .unwrap_or_default();
723        let desc =
724            String::from_utf8(out).expect("UTF-8 output from description");
725        assert!(
726            desc.contains("1114659 : <Dc> Begin operation session description")
727        );
728        assert!(desc.contains("1114661 : <Dc> Source path"));
729    }
730
731    #[crate::ctb_test]
732    fn test_execute_cli_convert_utf8_to_dcal() {
733        let args = ConvertArgs {
734            input: Some("Hello".to_string()),
735            from: Some(SupportedDcInputFormat::Utf8),
736            to: SupportedDcOutputFormat::Dcal,
737            ..Default::default()
738        };
739        let out = execute_cli_convert(args, |_| Ok(Vec::new()))
740            .unwrap()
741            .unwrap();
742        assert_eq!(String::from_utf8(out).unwrap(), "72 101 108 108 111 ");
743    }
744
745    #[crate::ctb_test]
746    fn test_execute_cli_convert_dcal_to_utf8() {
747        let args = ConvertArgs {
748            input: Some("72 101 108 108 111 ".to_string()),
749            from: Some(SupportedDcInputFormat::Dcal),
750            to: SupportedDcOutputFormat::Utf8,
751            ..Default::default()
752        };
753        let out = execute_cli_convert(args, |_| Ok(Vec::new()))
754            .unwrap()
755            .unwrap();
756        assert_eq!(String::from_utf8(out).unwrap(), "Hello");
757    }
758
759    #[crate::ctb_test]
760    fn test_execute_cli_convert_dcal_to_dctext() {
761        let args = ConvertArgs {
762            input: Some("65 1114408 2228304".to_string()),
763            from: Some(SupportedDcInputFormat::Dcal),
764            to: SupportedDcOutputFormat::DcText,
765            ..Default::default()
766        };
767        let out = execute_cli_convert(args, |_| Ok(Vec::new()))
768            .unwrap()
769            .unwrap();
770        let s = String::from_utf8(out).unwrap();
771        assert!(s.contains('A'));
772    }
773
774    #[crate::ctb_test]
775    fn test_execute_cli_convert_cscjournal_to_dcal() {
776        let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR")).join(
777            "../../io/csc/fixtures/journals/v1_ctbmeta1-20261011.cscjournal",
778        );
779        let journal_bytes =
780            std::fs::read(&fixture_path).expect("read journal fixture");
781
782        let args = ConvertArgs {
783            file: Some(fixture_path.clone()),
784            from: Some(SupportedDcInputFormat::CscJournal),
785            to: SupportedDcOutputFormat::Dcal,
786            ..Default::default()
787        };
788        let out = execute_cli_convert(args, |_| Ok(journal_bytes.clone()))
789            .expect("Run convert cscjournal to dcal")
790            .unwrap_or_default();
791        let s = String::from_utf8(out).expect("UTF-8 dcal output");
792        assert!(!s.is_empty());
793        assert!(
794            s.split_ascii_whitespace()
795                .all(|token| token.chars().all(|c| c.is_ascii_digit()))
796        );
797    }
798
799    #[crate::ctb_test]
800    fn test_cli_format_parsing_accepts_nicknames_and_rust_names_and_categorizes_errors()
801     {
802        use clap::{Args, Command, FromArgMatches};
803
804        for arg_val in ["dcmm", "DcMixed", "dcmixed", "f484"] {
805            let cmd = CharacterDescriptionArgs::augment_args(Command::new(
806                "character_description",
807            ));
808            let matches = cmd
809                .try_get_matches_from([
810                    "character_description",
811                    "--from",
812                    arg_val,
813                    "hello",
814                ])
815                .expect("parse valid --from format");
816            let parsed =
817                CharacterDescriptionArgs::from_arg_matches(&matches).unwrap();
818            assert_eq!(parsed.from, Some(SupportedDcInputFormat::DcMixed));
819        }
820
821        let cmd = CharacterDescriptionArgs::augment_args(Command::new(
822            "character_description",
823        ));
824        let err = cmd
825            .try_get_matches_from([
826                "character_description",
827                "--from",
828                "not_a_real_format",
829                "hello",
830            ])
831            .unwrap_err();
832        let err_str = err.to_string();
833        assert!(err_str.contains("Document formats:"));
834        assert!(err_str.contains("Text encodings:"));
835        assert!(err_str.contains("Database & archive formats:"));
836        assert!(err_str.contains("dcmm, dcmstr (DcMixed): Dc mixed mode"));
837    }
838
839    #[crate::ctb_test]
840    fn test_cli_character_description_permissive_and_autodetect_error_table() {
841        // 1. Autodetection failure shows categorized, sorted table with both nicknames and Rust names
842        let unknown_bytes = b"CTBRSRC\x00\x04\x00\x00\x00\x00\x00\x00\x00";
843        let err = execute_cli_character_description(
844            CharacterDescriptionArgs {
845                file: Some(PathBuf::from("system_graph_history.rsrc")),
846                ..Default::default()
847            },
848            |_| Ok(unknown_bytes.to_vec()),
849        )
850        .unwrap_err();
851        let err_msg = format!("{err:#}");
852        assert!(err_msg.contains("Unable to autodetect document format for input. Specify --from with one of:"));
853        assert!(err_msg.contains("Document formats:"));
854        assert!(err_msg.contains("dcmm, dcmstr (DcMixed): Dc mixed mode"));
855
856        // 2. Permissive mode with --from dcmm decodes DcMixed2 wrapped in an asset bundle
857        let mut inner_doc = ctb_formats_dcstring::DcMstring::new();
858        inner_doc.push_char(ctb_formats_dcstring::DcChar(1_114_729)); // Dc 617
859        inner_doc.push_str("A");
860        inner_doc.push_char(ctb_formats_dcstring::DcChar(1_114_730)); // Dc 618
861        let mut wrapped = b"CTBRSRC\x00\x04\x00\x00\x00data/graph/system/85899_34942.ctbnbdlCTBNBDL\x02".to_vec();
862        wrapped.extend_from_slice(inner_doc.as_bytes());
863
864        let out = execute_cli_character_description(
865            CharacterDescriptionArgs {
866                file: Some(PathBuf::from("system_graph_history.rsrc")),
867                from: Some(SupportedDcInputFormat::DcMixed),
868                permissive: true,
869                ..Default::default()
870            },
871            |_| Ok(wrapped.clone()),
872        )
873        .expect("permissive character_description")
874        .unwrap();
875        let text = String::from_utf8(out).unwrap();
876        assert!(text.contains("1114729 : <Dc> Begin graph node definition"));
877        assert!(text.contains("1114730 : <Dc> End graph node definition"));
878
879        let damaged_dce =
880            ctb_formats_dceutils::converter::encode_dce_preserving_controls(
881                &[50, 191, 151, 158, 188, 161, 192, 51],
882                "3_01a",
883                &mut ctb_formats_utilities::FormatLog::default(),
884            )
885            .unwrap();
886        for permissive in [false, true] {
887            let mut arguments = vec![
888                "character_description",
889                "--from",
890                "Dce_3_01a",
891                "--file",
892                "damaged.dce",
893            ];
894            if permissive {
895                arguments.push("--permissive");
896            }
897            let command =
898                <CharacterDescriptionArgs as clap::Args>::augment_args(
899                    clap::Command::new("character_description"),
900                );
901            let matches = command.try_get_matches_from(arguments).unwrap();
902            let args = <CharacterDescriptionArgs as clap::FromArgMatches>::from_arg_matches(
903                &matches,
904            ).unwrap();
905            assert_eq!(args.permissive, permissive);
906            let result = execute_cli_character_description(args, |_| {
907                Ok(damaged_dce.to_vec())
908            });
909            if !permissive {
910                assert!(result.is_err());
911                continue;
912            }
913            let text = String::from_utf8(result.unwrap().unwrap()).unwrap();
914            for description in [
915                "U+0061 : LATIN SMALL LETTER A",
916                "U+FFFD : REPLACEMENT CHARACTER",
917                "U+0062 : LATIN SMALL LETTER B",
918            ] {
919                assert!(text.contains(description), "{text}");
920            }
921        }
922    }
923
924    #[crate::ctb_test]
925    fn test_cli_character_description_ctbnbdl_and_dc203_tokens() {
926        let ctbnbdl_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
927            .join("../../../assets/data/graph-bundles/85899_34592.ctbnbdl");
928        let ctbnbdl_bytes = std::fs::read(&ctbnbdl_path)
929            .expect("read assets/data/graph-bundles/85899_34592.ctbnbdl");
930        let out = execute_cli_character_description(
931            CharacterDescriptionArgs {
932                file: Some(PathBuf::from(
933                    "assets/data/graph-bundles/85899_34592.ctbnbdl",
934                )),
935                ..Default::default()
936            },
937            |_| Ok(ctbnbdl_bytes.clone()),
938        )
939        .expect("character_description on 85899_34592.ctbnbdl must succeed")
940        .unwrap();
941        let text = String::from_utf8(out).unwrap();
942        assert!(
943            text.contains("1114315 : <Dc> Begin encapsulated binary data"),
944            "Expected Dc 203 character descriptions in 85899_34592.ctbnbdl output"
945        );
946        assert!(
947            text.contains("1114730 : <Dc> End graph node definition"),
948            "Expected End graph node definition (Dc 618) in 85899_34592.ctbnbdl output"
949        );
950        assert!(
951            text.contains("1116053 : <Dc> Section timestamp: node creation time"),
952            "Expected Section timestamp: node creation time (Dc 1941) in 85899_34592.ctbnbdl output"
953        );
954        assert!(
955            text.contains("1114657 : <Dc> Section digest"),
956            "Expected Section digest (Dc 545) in 85899_34592.ctbnbdl output"
957        );
958        assert!(
959            text.lines().last().is_some_and(|line| line
960                .starts_with("1114316 : <Dc> End encapsulated binary data")),
961            "Expected trailing End encapsulated binary data (Dc 204, closing trailing Dc 545 SHA-256 digest) at end of 85899_34592.ctbnbdl output"
962        );
963
964        let dcsh_out = execute_cli_character_description(
965            CharacterDescriptionArgs {
966                input: Some("203".to_string()),
967                from: Some(SupportedDcInputFormat::Dcsh),
968                ..Default::default()
969            },
970            |_| unreachable!(),
971        )
972        .expect("character_description --from dcsh 203 must succeed")
973        .unwrap();
974        let dcsh_text = String::from_utf8(dcsh_out).unwrap();
975        assert!(
976            dcsh_text
977                .starts_with("1114315 : <Dc> Begin encapsulated binary data"),
978            "Unexpected output: {dcsh_text}"
979        );
980    }
981
982    #[crate::ctb_test]
983    fn test_execute_cli_convert_strict_vs_permissive() {
984        // Short Dc 65 (1114177 in dcal) maps to 'P' under canonicalization
985        let input_dcal = "1114177".to_string();
986
987        // Strict mode (default): should NOT canonicalize equivalent Dcs
988        let strict_out = execute_cli_convert(
989            ConvertArgs {
990                input: Some(input_dcal.clone()),
991                from: Some(SupportedDcInputFormat::Dcal),
992                to: SupportedDcOutputFormat::Utf8,
993                ..Default::default()
994            },
995            |_| unreachable!(),
996        )
997        .expect("convert in default strict mode must succeed")
998        .unwrap();
999        assert_eq!(String::from_utf8(strict_out).unwrap(), "\u{FFFD}");
1000
1001        // Explicit --strict mode: should also NOT canonicalize
1002        let explicit_strict_out = execute_cli_convert(
1003            ConvertArgs {
1004                input: Some(input_dcal.clone()),
1005                from: Some(SupportedDcInputFormat::Dcal),
1006                to: SupportedDcOutputFormat::Utf8,
1007                strict: true,
1008                ..Default::default()
1009            },
1010            |_| unreachable!(),
1011        )
1012        .expect("convert in explicit strict mode must succeed")
1013        .unwrap();
1014        assert_eq!(String::from_utf8(explicit_strict_out).unwrap(), "\u{FFFD}");
1015
1016        // Permissive mode (--permissive): canonicalizes equivalent Dcs to "P"
1017        let perm_out = execute_cli_convert(
1018            ConvertArgs {
1019                input: Some(input_dcal.clone()),
1020                from: Some(SupportedDcInputFormat::Dcal),
1021                to: SupportedDcOutputFormat::Utf8,
1022                permissive: true,
1023                ..Default::default()
1024            },
1025            |_| unreachable!(),
1026        )
1027        .expect("convert in permissive mode must succeed")
1028        .unwrap();
1029        assert_eq!(String::from_utf8(perm_out).unwrap(), "P");
1030
1031        // Permissive mode with --normalize none: replaces unrepresentable Dcs with U+FFFD
1032        let perm_no_norm_out = execute_cli_convert(
1033            ConvertArgs {
1034                input: Some(input_dcal),
1035                from: Some(SupportedDcInputFormat::Dcal),
1036                to: SupportedDcOutputFormat::Utf8,
1037                permissive: true,
1038                normalize: Some(DcNormalizationMode::None),
1039                ..Default::default()
1040            },
1041            |_| unreachable!(),
1042        )
1043        .expect("convert in permissive mode with --normalize none must succeed")
1044        .unwrap();
1045        assert_eq!(String::from_utf8(perm_no_norm_out).unwrap(), "\u{FFFD}");
1046
1047        // --normalize all on Dcal -> Dcal normalizes decomposed Unicode and deprecated Dcs
1048        let norm_all_out = execute_cli_convert(
1049            ConvertArgs {
1050                input: Some("99 97 102 101 769 1114169".to_string()),
1051                from: Some(SupportedDcInputFormat::Dcal),
1052                to: SupportedDcOutputFormat::Dcal,
1053                permissive: true,
1054                normalize: Some(DcNormalizationMode::All),
1055                ..Default::default()
1056            },
1057            |_| unreachable!(),
1058        )
1059        .expect("convert with --normalize all must succeed")
1060        .unwrap();
1061        assert_eq!(
1062            String::from_utf8(norm_all_out).unwrap(),
1063            "99 97 102 233 72 "
1064        );
1065    }
1066
1067    #[crate::ctb_test]
1068    fn test_execute_cli_convert_with_unicode_to_short_dc_transform() {
1069        use clap::{Args, Command, FromArgMatches};
1070
1071        for tr_arg in [
1072            "unicode_to_short_dc",
1073            "UnicodeToShortDc",
1074            "unicodetoshortdc",
1075            "f654",
1076        ] {
1077            let cmd = ConvertArgs::augment_args(Command::new("convert"));
1078            let matches = cmd
1079                .try_get_matches_from([
1080                    "convert",
1081                    "--from",
1082                    "ascii",
1083                    "--to",
1084                    "sems",
1085                    "--transform",
1086                    tr_arg,
1087                    "A",
1088                ])
1089                .expect("parse valid --transform");
1090            let parsed = ConvertArgs::from_arg_matches(&matches).unwrap();
1091            assert_eq!(
1092                parsed.transform,
1093                vec![SupportedDcTransformation::UnicodeToShortDc]
1094            );
1095            let out = execute_cli_convert(parsed, |_| unreachable!())
1096                .unwrap()
1097                .unwrap();
1098            assert_eq!(String::from_utf8(out).unwrap().trim(), "50");
1099        }
1100    }
1101}