ctb_formats_utilities/
format_info.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//! Metadata lookup and formatting for registered document and stream formats.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::Result;
30use std::collections::HashMap;
31use std::path::{Path, PathBuf};
32use std::sync::LazyLock;
33
34/// Detailed metadata record for a format from format category CSV files.
35#[derive(Debug, Clone, PartialEq, Eq, Default)]
36pub struct FormatInfo {
37    pub dc_id: u128,
38    pub id: usize,
39    pub ident: String,
40    pub label: String,
41    pub category: String,
42    pub implies: String,
43    pub based_on: String,
44    pub extensions: String,
45    pub mime: String,
46    pub uti: String,
47    pub apple_type: String,
48    pub nicknames: String,
49    pub import_support: String,
50    pub export_support: String,
51    pub tests: String,
52    pub variant_types: String,
53    pub comments: String,
54    pub references: String,
55}
56
57static FORMATS_BY_ID: LazyLock<HashMap<usize, FormatInfo>> =
58    LazyLock::new(|| {
59        let mut map = HashMap::new();
60        for defn in ctb_formats_dcdata::get_all_format_defns() {
61            let Some(id) = defn.short_id else {
62                continue;
63            };
64            let Some(fmt) = &defn.format else {
65                continue;
66            };
67            // Reason for fallback: script strings without the ".Formats:" prefix are already bare category names.
68            let category = defn
69                .script
70                .strip_prefix(".Formats:")
71                .unwrap_or(&defn.script)
72                .to_string();
73            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
74            let ident = defn.ident.clone().unwrap_or_default();
75            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
76            let implies = fmt.implies.clone().unwrap_or_default();
77            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
78            let based_on = fmt.based_on.clone().unwrap_or_default();
79            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
80            let extensions = fmt.extensions.clone().unwrap_or_default();
81            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
82            let mime = fmt.mime.clone().unwrap_or_default();
83            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
84            let uti = fmt.uti.clone().unwrap_or_default();
85            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
86            let apple_type = fmt.apple_type.clone().unwrap_or_default();
87            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
88            let nicknames = fmt.nicknames.clone().unwrap_or_default();
89            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
90            let import_support = fmt.import_support.clone().unwrap_or_default();
91            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
92            let export_support = fmt.export_support.clone().unwrap_or_default();
93            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
94            let tests = fmt.tests.clone().unwrap_or_default();
95            // Reason for fallback: optional format metadata fields are represented as empty strings in FormatInfo when absent.
96            let variant_types = fmt.variant_types.clone().unwrap_or_default();
97
98            map.insert(
99                id,
100                FormatInfo {
101                    dc_id: defn.dc_id,
102                    id,
103                    ident,
104                    label: defn.name.clone(),
105                    category,
106                    implies,
107                    based_on,
108                    extensions,
109                    mime,
110                    uti,
111                    apple_type,
112                    nicknames,
113                    import_support,
114                    export_support,
115                    tests,
116                    variant_types,
117                    comments: defn.description.clone(),
118                    references: defn.cross_references.join(", "),
119                },
120            );
121        }
122        map
123    });
124
125impl FormatInfo {
126    /// Returns the nicknames as a sorted list of strings: shortest first, then
127    /// alphabetically for ties.
128    #[must_use]
129    pub fn sorted_nicknames(&self) -> Vec<String> {
130        if self.nicknames.is_empty() {
131            return Vec::new();
132        }
133        let mut nicks: Vec<String> = self
134            .nicknames
135            .split(',')
136            .map(|s| s.trim().to_string())
137            .filter(|s| !s.is_empty())
138            .collect();
139        nicks.sort_by(|a, b| a.len().cmp(&b.len()).then_with(|| a.cmp(b)));
140        nicks
141    }
142
143    /// Returns the primary file extension (without leading dot or case prefix).
144    #[must_use]
145    pub fn primary_extension(&self) -> Option<&str> {
146        self.get_primary_extension()
147    }
148
149    /// Returns the primary file extension (without leading dot or case prefix).
150    #[must_use]
151    pub fn get_primary_extension(&self) -> Option<&str> {
152        if self.extensions.is_empty() {
153            return None;
154        }
155        self.extensions
156            .split(',')
157            .next()
158            .map(|ext| {
159                let trimmed = ext.trim();
160                // Reason for fallback: extensions without "case:" prefix are kept as-is
161                let clean = trimmed.strip_prefix("case:").unwrap_or(trimmed);
162                clean.trim_start_matches('.')
163            })
164            .filter(|s| !s.is_empty())
165    }
166}
167
168/// Extension trait allowing `.get_primary_extension()` on `Option<&'static FormatInfo>`.
169pub trait FormatInfoOptionExt {
170    /// Returns the primary file extension if format info is present.
171    fn get_primary_extension(&self) -> Option<&'static str>;
172}
173
174impl FormatInfoOptionExt for Option<&'static FormatInfo> {
175    fn get_primary_extension(&self) -> Option<&'static str> {
176        self.and_then(FormatInfo::get_primary_extension)
177    }
178}
179
180static FORMATS_BY_FORMAT_ID: LazyLock<
181    HashMap<ctb_utilities::FormatId, FormatInfo>,
182> = LazyLock::new(|| {
183    let mut map = HashMap::new();
184    for info in FORMATS_BY_ID.values() {
185        if let Some(fid) = ctb_utilities::FormatId::from_ident(&info.ident) {
186            map.insert(fid, info.clone());
187        } else if let Some(fid) =
188            ctb_utilities::FormatId::from_shorthand(&format!("f{}", info.id))
189        {
190            map.insert(fid, info.clone());
191        }
192    }
193    map
194});
195
196/// Look up a `FormatInfo` record by short Format ID.
197pub fn get_format_info(fmt_id: usize) -> Option<&'static FormatInfo> {
198    FORMATS_BY_ID.get(&fmt_id)
199}
200
201/// Look up a `FormatInfo` record by `FormatId`.
202pub fn get_format_info_by_id(
203    format_id: ctb_utilities::FormatId,
204) -> Option<&'static FormatInfo> {
205    FORMATS_BY_FORMAT_ID.get(&format_id)
206}
207
208/// Generates a help table of supported formats and their shorthand aliases for
209/// CLI `after_help` text.
210pub fn format_help_table(
211    header: &str,
212    formats: &[ctb_utilities::FormatId],
213) -> String {
214    let mut lines = Vec::new();
215    lines.push(header.to_string());
216    let mut entries: Vec<(String, String)> = Vec::new();
217    for &fid in formats {
218        if let Some(info) = get_format_info_by_id(fid) {
219            let aliases = info.sorted_nicknames();
220            let alias_str = if aliases.is_empty() {
221                info.ident.clone()
222            } else {
223                aliases.join(", ")
224            };
225            let sort_key = alias_str.to_ascii_lowercase();
226            entries
227                .push((sort_key, format!("  {}: {}", alias_str, info.label)));
228        }
229    }
230    entries.sort_by(|a, b| a.0.cmp(&b.0));
231    for (_, line) in entries {
232        lines.push(line);
233    }
234    lines.join("\n")
235}
236
237/// Helper to extract the primary CLI name (the first nickname if present, or lowercase ident).
238fn format_primary_cli_name(info: &FormatInfo) -> String {
239    let nicks: Vec<&str> = info
240        .nicknames
241        .split(',')
242        .map(str::trim)
243        .filter(|s| !s.is_empty())
244        .collect();
245    if let Some(&first) = nicks.first() {
246        first.to_string()
247    } else {
248        info.ident.to_ascii_lowercase()
249    }
250}
251
252/// Helper to detect if `child` is a versioned type of `parent` within the same category,
253/// returning the extracted version number if so.
254fn detect_version_number(
255    child_id: ctb_utilities::FormatId,
256    child_info: &FormatInfo,
257    parent_id: ctb_utilities::FormatId,
258    parent_info: &FormatInfo,
259) -> Option<u32> {
260    if child_id == parent_id {
261        return None;
262    }
263    if !child_info.category.eq_ignore_ascii_case(&parent_info.category) {
264        return None;
265    }
266    if !child_id.implies().contains(&parent_id) {
267        return None;
268    }
269
270    // Check if child identifier starts with parent identifier:
271    if let Some(remainder) = child_info.ident.strip_prefix(&parent_info.ident) {
272        let trimmed =
273            remainder.trim_start_matches(|c| c == '_' || c == 'V' || c == 'v');
274        if !trimmed.is_empty() && trimmed.chars().all(|c| c.is_ascii_digit()) {
275            if let Ok(ver) = trimmed.parse::<u32>() {
276                return Some(ver);
277            }
278        }
279    }
280
281    // Check if child label contains "version <N>"
282    let lower_label = child_info.label.to_ascii_lowercase();
283    if let Some(pos) = lower_label.find("version ") {
284        // Reason for fallback: slice starting after "version "
285        if let Some(sub) =
286            lower_label.get(pos.saturating_add("version ".len())..)
287        {
288            let digits: String =
289                sub.chars().take_while(|c| c.is_ascii_digit()).collect();
290            if !digits.is_empty() {
291                if let Ok(ver) = digits.parse::<u32>() {
292                    return Some(ver);
293                }
294            }
295        }
296    }
297
298    None
299}
300
301/// Generates a categorized, alphabetically sorted help table of supported formats
302/// showing both CLI nicknames and Rust `FormatId` names alongside their descriptions.
303/// Versioned format types are grouped indented under their base format with the default indicated.
304pub fn format_categorized_help_table(
305    header: &str,
306    formats: &[ctb_utilities::FormatId],
307) -> String {
308    let mut lines = Vec::new();
309    if !header.is_empty() {
310        lines.push(header.to_string());
311    }
312
313    let category_order = [
314        ("document", "Document formats:"),
315        ("encoding", "Text encodings:"),
316        ("database", "Database & archive formats:"),
317        ("transformation", "Document transformations:"),
318        ("container", "Container formats:"),
319        ("compression", "Compression formats:"),
320        ("hash", "Hash formats:"),
321    ];
322
323    let mut by_category: std::collections::BTreeMap<
324        String,
325        Vec<(ctb_utilities::FormatId, &'static FormatInfo)>,
326    > = std::collections::BTreeMap::new();
327
328    for &fid in formats {
329        if let Some(info) = get_format_info_by_id(fid) {
330            let cat_key = info.category.trim().to_ascii_lowercase();
331            by_category.entry(cat_key).or_default().push((fid, info));
332        }
333    }
334
335    let mut formatted_categories: std::collections::BTreeMap<
336        String,
337        Vec<(String, Vec<String>)>,
338    > = std::collections::BTreeMap::new();
339
340    for (cat_key, cat_fmts) in by_category {
341        // Find child -> (parent, version) relationships
342        // If multiple parents match, choose the parent with the longest ident
343        let mut child_to_parent: HashMap<
344            ctb_utilities::FormatId,
345            (ctb_utilities::FormatId, u32),
346        > = HashMap::new();
347
348        for &(child_fid, child_info) in &cat_fmts {
349            let mut best_match: Option<(ctb_utilities::FormatId, u32, usize)> =
350                None;
351            for &(parent_fid, parent_info) in &cat_fmts {
352                if let Some(ver) = detect_version_number(
353                    child_fid,
354                    child_info,
355                    parent_fid,
356                    parent_info,
357                ) {
358                    let len = parent_info.ident.len();
359                    if best_match
360                        .as_ref()
361                        .is_none_or(|&(_, _, best_len)| len > best_len)
362                    {
363                        best_match = Some((parent_fid, ver, len));
364                    }
365                }
366            }
367            if let Some((parent_fid, ver, _)) = best_match {
368                child_to_parent.insert(child_fid, (parent_fid, ver));
369            }
370        }
371
372        // Group children by parent
373        let mut parent_children: HashMap<
374            ctb_utilities::FormatId,
375            Vec<(u32, String, String, &'static FormatInfo)>,
376        > = HashMap::new();
377
378        for &(child_fid, child_info) in &cat_fmts {
379            if let Some(&(parent_fid, ver)) = child_to_parent.get(&child_fid) {
380                let nicks: Vec<&str> = child_info
381                    .nicknames
382                    .split(',')
383                    .map(str::trim)
384                    .filter(|s| !s.is_empty())
385                    .collect();
386                // Reason for fallback: formats without short CLI nicknames sort by their lowercased canonical FormatId identifier.
387                let primary_key = nicks.first().map_or_else(
388                    || child_info.ident.to_ascii_lowercase(),
389                    |s| s.to_ascii_lowercase(),
390                );
391                let name_display = if nicks.is_empty() {
392                    format!(
393                        "{} ({})",
394                        child_info.ident.to_ascii_lowercase(),
395                        child_info.ident
396                    )
397                } else {
398                    format!("{} ({})", nicks.join(", "), child_info.ident)
399                };
400                parent_children.entry(parent_fid).or_default().push((
401                    ver,
402                    primary_key,
403                    name_display,
404                    child_info,
405                ));
406            }
407        }
408
409        let mut cat_entries: Vec<(String, Vec<String>)> = Vec::new();
410
411        for &(fid, info) in &cat_fmts {
412            if child_to_parent.contains_key(&fid) {
413                // Skip child at top level: it will be rendered indented under its parent
414                continue;
415            }
416
417            let nicks: Vec<&str> = info
418                .nicknames
419                .split(',')
420                .map(str::trim)
421                .filter(|s| !s.is_empty())
422                .collect();
423            // Reason for fallback: formats without short CLI nicknames sort by their lowercased canonical FormatId identifier.
424            let primary_key = nicks.first().map_or_else(
425                || info.ident.to_ascii_lowercase(),
426                |s| s.to_ascii_lowercase(),
427            );
428            let name_display = if nicks.is_empty() {
429                format!("{} ({})", info.ident.to_ascii_lowercase(), info.ident)
430            } else {
431                format!("{} ({})", nicks.join(", "), info.ident)
432            };
433
434            let mut entry_lines = Vec::new();
435
436            if let Some(mut children) = parent_children.remove(&fid) {
437                // Sort children by version number ascending, then by primary_key
438                children.sort_by(|a, b| {
439                    a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
440                });
441
442                if let Some(default_child) = children.last() {
443                    let default_nick = format_primary_cli_name(default_child.3);
444                    entry_lines.push(format!(
445                        "    {name_display}: {} (default: {default_nick})",
446                        info.label
447                    ));
448                } else {
449                    entry_lines
450                        .push(format!("    {name_display}: {}", info.label));
451                }
452
453                for (_, _, child_name_display, child_info) in children {
454                    entry_lines.push(format!(
455                        "        {child_name_display}: {}",
456                        child_info.label
457                    ));
458                }
459            } else {
460                entry_lines
461                    .push(format!("    {name_display}: {}", info.label));
462            }
463
464            cat_entries.push((primary_key, entry_lines));
465        }
466
467        cat_entries.sort_by(|a, b| a.0.cmp(&b.0));
468        formatted_categories.insert(cat_key, cat_entries);
469    }
470
471    for &(cat_key, cat_title) in &category_order {
472        if let Some(entries) = formatted_categories.remove(cat_key) {
473            lines.push(format!("  {cat_title}"));
474            for (_, entry_lines) in entries {
475                for line in entry_lines {
476                    lines.push(line);
477                }
478            }
479        }
480    }
481
482    for (cat_key, entries) in formatted_categories {
483        lines.push(format!("  {cat_key} formats:"));
484        for (_, entry_lines) in entries {
485            for line in entry_lines {
486                lines.push(line);
487            }
488        }
489    }
490
491    lines.join("\n")
492}
493
494/// Strips an extension belonging to the given `FormatId` from the input path.
495pub fn strip_format_extension(
496    input_path: &Path,
497    format_id: ctb_utilities::FormatId,
498) -> Option<PathBuf> {
499    let path_str = input_path.to_string_lossy();
500    let mut rules =
501        crate::extension_data::extension_rules_for_format(format_id);
502    rules.sort_by(|a, b| b.extension.len().cmp(&a.extension.len()));
503    for rule in rules {
504        if let Some(prefix) = rule.strip_from_filename(&path_str) {
505            return Some(PathBuf::from(prefix));
506        }
507    }
508    None
509}
510
511/// Infers the output file path when decompressing without an explicit output
512/// path. Checks registered extension rules for compression formats (longest
513/// extensions first) and strips the matched extension, or appends
514/// `.decompressed` if none is recognized.
515pub fn infer_decompressed_path(input_path: &Path) -> PathBuf {
516    let path_str = input_path.to_string_lossy();
517    let mut compression_rules: Vec<crate::detection::extension::ExtensionRule> =
518        crate::extension_data::EXTENSION_REGISTRY
519            .iter()
520            .filter(|e| {
521                e.format_id.category()
522                    == ctb_utilities::format_id::FormatCategory::Compression
523            })
524            .map(|e| e.rule)
525            .collect();
526    // Sort longer extensions first so e.g. .old.z or .Z1.0 matches before .z or .Z
527    compression_rules.sort_by(|a, b| b.extension.len().cmp(&a.extension.len()));
528    for rule in compression_rules {
529        if let Some(prefix) = rule.strip_from_filename(&path_str) {
530            return PathBuf::from(prefix);
531        }
532    }
533    PathBuf::from(format!("{}.decompressed", input_path.display()))
534}
535
536fn format_support_level(level: &str) -> String {
537    let trimmed = level.trim();
538    if trimmed.is_empty() {
539        return String::new();
540    }
541    let parts: Vec<&str> = trimmed.split_whitespace().collect();
542    if let [gen_part, dc_part] = parts.as_slice() {
543        let gen_str = format_single_support_level(gen_part);
544        let dc_str = format_single_support_level(dc_part);
545        format!("{gen_str} [Dc: {dc_str}]")
546    } else {
547        format_single_support_level(trimmed)
548    }
549}
550
551fn format_single_support_level(level: &str) -> String {
552    match level.trim() {
553        "-1" => "-1 (N/A)".to_string(),
554        "0" => "0 (none)".to_string(),
555        "1" => "1 (WIP)".to_string(),
556        "2" => "2 (mostly / partial)".to_string(),
557        "3" => "3 (fully implemented)".to_string(),
558        "4" => "4 (lossless / roundtrippable)".to_string(),
559        "5" => "5 (lossless with strict validation)".to_string(),
560        other => other.to_string(),
561    }
562}
563
564/// Formats detailed metadata for a short Format ID.
565///
566/// Output format includes the Global Graph ID (offset by 2,228,224), label, category,
567/// extensions, MIME types, import/export support levels, and comments.
568pub fn describe_format(fmt_id: usize) -> Result<String> {
569    let info = get_format_info(fmt_id)
570        .ok_or_else(|| anyhow::anyhow!("Unknown Format ID: {fmt_id}"))?;
571
572    let gid = if info.dc_id != 0 {
573        info.dc_id
574    } else {
575        2_228_224_u128.saturating_add(u128::try_from(fmt_id)?)
576    };
577    let title = if !info.label.is_empty() {
578        &info.label
579    } else if !info.ident.is_empty() {
580        &info.ident
581    } else {
582        "Unknown Format"
583    };
584
585    let mut lines = Vec::new();
586    lines.push(format!("{gid}"));
587    lines.push(title.to_string());
588    lines.push(String::new());
589
590    if !info.ident.is_empty() && info.ident != info.label {
591        lines.push(format!("Ident: {ident}", ident = info.ident));
592    }
593    if !info.category.is_empty() {
594        lines.push(format!("Category: {cat}", cat = info.category));
595    }
596    if !info.mime.is_empty() {
597        lines.push(format!("MIME: {mime}", mime = info.mime));
598    }
599    if !info.extensions.is_empty() {
600        lines.push(format!("Extensions: {ext}", ext = info.extensions));
601    }
602    if !info.uti.is_empty() {
603        lines.push(format!("Apple UTI: {uti}", uti = info.uti));
604    }
605    if !info.apple_type.is_empty() {
606        lines.push(format!("Apple Type code: {at}", at = info.apple_type));
607    }
608    if !info.nicknames.is_empty() {
609        lines.push(format!("Nicknames: {nick}", nick = info.nicknames));
610    }
611    if !info.implies.is_empty() {
612        lines.push(format!("Implies: {imp}", imp = info.implies));
613    }
614    if !info.based_on.is_empty() {
615        lines.push(format!("Based on: {base}", base = info.based_on));
616    }
617    if !info.import_support.is_empty() {
618        lines.push(format!(
619            "Import support: {imp}",
620            imp = format_support_level(&info.import_support)
621        ));
622    }
623    if !info.export_support.is_empty() {
624        lines.push(format!(
625            "Export support: {exp}",
626            exp = format_support_level(&info.export_support)
627        ));
628    }
629    if !info.tests.is_empty() {
630        lines.push(format!(
631            "Tests: {tst}",
632            tst = format_support_level(&info.tests)
633        ));
634    }
635    if !info.variant_types.is_empty() {
636        lines.push(format!("Variant types: {vt}", vt = info.variant_types));
637    }
638    if !info.comments.is_empty() {
639        lines.push(format!("Comments: {comm}", comm = info.comments));
640    }
641    if !info.references.is_empty() {
642        lines.push(format!("References: {refs}", refs = info.references));
643    }
644
645    Ok(lines.join("\n"))
646}
647
648#[cfg(test)]
649#[allow(
650    clippy::panic,
651    clippy::expect_used,
652    clippy::unwrap_used,
653    clippy::unwrap_in_result,
654    clippy::panic_in_result_fn,
655    clippy::indexing_slicing,
656    clippy::arithmetic_side_effects,
657    reason = "Standard repository test boilerplate"
658)]
659mod tests {
660    use super::*;
661
662    #[crate::ctb_test]
663    fn test_get_format_info_80() {
664        let info = get_format_info(80).expect("Format 80 exists");
665        assert_eq!(info.id, 80);
666        assert_eq!(info.ident, "String");
667        assert_eq!(info.label, "String");
668        assert_eq!(info.category, "semantic");
669    }
670
671    #[crate::ctb_test]
672    fn test_describe_format_80() {
673        let desc = describe_format(80).expect("Describe format 80");
674        assert!(desc.starts_with("2228304\nString\n\nCategory: semantic"));
675    }
676
677    #[crate::ctb_test]
678    fn test_describe_format_0_utf8() {
679        let desc = describe_format(0).expect("Describe format 0");
680        assert!(desc.starts_with("2228224\nUTF-8"));
681        assert!(desc.contains("Ident: Utf8"));
682        assert!(desc.contains("Category: encoding"));
683        assert!(desc.contains("Extensions: .txt, .utf8"));
684        assert!(
685            desc.contains(
686                "Import support: 3 (fully implemented) [Dc: 1 (WIP)]"
687            )
688        );
689        assert!(desc.contains(
690            "Export support: 3 (fully implemented) [Dc: 2 (mostly / partial)]"
691        ));
692        assert!(desc.contains("Tests: 1 (WIP) [Dc: 1 (WIP)]"));
693    }
694
695    #[crate::ctb_test]
696    fn test_implies_and_based_on_loading_and_formatting() {
697        // f546 = QuartzDisplay, implies f271 (RasterDisplay)
698        let quartz = get_format_info(546).expect("Format 546 exists");
699        assert_eq!(quartz.ident, "QuartzDisplay");
700        assert_eq!(quartz.implies, "f271");
701        assert!(quartz.based_on.is_empty());
702        let quartz_desc = describe_format(546).expect("Describe 546");
703        assert!(quartz_desc.contains("Implies: f271"));
704
705        // f561 = Guix, based on f580 (Nix)
706        let guix = get_format_info(561).expect("Format 561 exists");
707        assert_eq!(guix.ident, "Guix");
708        assert_eq!(guix.based_on, "f580");
709        assert!(guix.implies.is_empty());
710        let guix_desc = describe_format(561).expect("Describe 561");
711        assert!(guix_desc.contains("Based on: f580"));
712
713        // f572 = Ubuntu, based on f571 (Debian) and implies f398 (GnuLinux)
714        let ubuntu = get_format_info(572).expect("Format 572 exists");
715        assert_eq!(ubuntu.ident, "Ubuntu");
716        assert_eq!(ubuntu.based_on, "f571");
717        assert_eq!(ubuntu.implies, "f398");
718        let ubuntu_desc = describe_format(572).expect("Describe 572");
719        assert!(ubuntu_desc.contains("Based on: f571"));
720        assert!(ubuntu_desc.contains("Implies: f398"));
721    }
722
723    #[crate::ctb_test]
724    fn test_format_help_table_and_nicknames() {
725        let table = format_help_table(
726            "Supported compression formats:",
727            &[FormatId::Brotli, FormatId::Gzip, FormatId::Xz],
728        );
729        assert!(table.contains("Supported compression formats:"));
730        assert!(table.contains("br, brotli: Brotli compressed stream"));
731        assert!(table.contains("gz, gzip: GNU gzip format"));
732        assert!(table.contains("xz: XZ compression"));
733        assert!(!table.contains("xzip"));
734    }
735
736    #[crate::ctb_test]
737    fn test_format_categorized_help_table_version_grouping() {
738        let table = format_categorized_help_table(
739            "Supported formats:",
740            &[
741                FormatId::DcMixed,
742                FormatId::DcMixed1,
743                FormatId::DcMixed2,
744                FormatId::CtbNodeBundle,
745                FormatId::CtbNodeBundle1,
746                FormatId::CtbNodeBundle2,
747                FormatId::CscArchive,
748                FormatId::CscArchive1,
749                FormatId::CscArchive2,
750            ],
751        );
752        let expected_dcmm = "\
753    dcmm, dcmstr (DcMixed): Dc mixed mode (default: dcmm2)
754        dcmm1 (DcMixed1): Dc mixed mode, version 1 (DcUtf)
755        dcmm2 (DcMixed2): Dc mixed mode, version 2 (DcTF)";
756        assert!(
757            table.contains(expected_dcmm),
758            "table was:\n{table}\nexpected to contain:\n{expected_dcmm}"
759        );
760
761        let expected_ctbnbdl = "\
762    ctbnbdl (CtbNodeBundle): Collective Toolbox Node Bundle (default: ctbnbdl2)
763        ctbnbdl1 (CtbNodeBundle1): Collective Toolbox Node Bundle, version 1
764        ctbnbdl2 (CtbNodeBundle2): Collective Toolbox Node Bundle, version 2";
765        assert!(
766            table.contains(expected_ctbnbdl),
767            "table was:\n{table}\nexpected to contain:\n{expected_ctbnbdl}"
768        );
769
770        let expected_cscarchive = "\
771    cscarchive (CscArchive): Collective Toolbox csc archive (default: cscarchive2)
772        cscarchive1 (CscArchive1): Collective Toolbox csc archive, version 1
773        cscarchive2 (CscArchive2): Collective Toolbox csc archive, version 2";
774        assert!(
775            table.contains(expected_cscarchive),
776            "table was:\n{table}\nexpected to contain:\n{expected_cscarchive}"
777        );
778    }
779
780    #[crate::ctb_test]
781    fn test_infer_decompressed_path_shared() {
782        assert_eq!(
783            infer_decompressed_path(Path::new("file.txt.gz")),
784            PathBuf::from("file.txt")
785        );
786        assert_eq!(
787            infer_decompressed_path(Path::new("archive.tar.Z")),
788            PathBuf::from("archive.tar")
789        );
790        assert_eq!(
791            infer_decompressed_path(Path::new("document.z")),
792            PathBuf::from("document")
793        );
794        assert_eq!(
795            infer_decompressed_path(Path::new("document.C")),
796            PathBuf::from("document")
797        );
798        assert_eq!(
799            infer_decompressed_path(Path::new("data.tar.xz")),
800            PathBuf::from("data.tar")
801        );
802        // .xzip is NOT .xz, should not strip as xz
803        assert_eq!(
804            infer_decompressed_path(Path::new("data.tar.xzip")),
805            PathBuf::from("data.tar.xzip.decompressed")
806        );
807        assert_eq!(
808            infer_decompressed_path(Path::new("unknown.bin")),
809            PathBuf::from("unknown.bin.decompressed")
810        );
811    }
812}