ctb_formats_pan/
cli.rs

1/* SPDX-License-Identifier: MIT */
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
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! CLI execution helpers for Panorama files.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35use crate as ctb_formats_pan;
36use std::path::{Path, PathBuf};
37
38pub fn pan2csv<FRead>(
39    pan_file: &PathBuf,
40    header: &bool,
41    no_header: &bool,
42    encoding: &String,
43    delimiter: &String,
44    patterns: &bool,
45    keep_multiline: &bool,
46    crlf: &bool,
47    replicate_double_encoding: &bool,
48    run_startup_procedure: &bool,
49    read_file_or_stdin: FRead,
50) -> Result<ToolResult>
51where
52    FRead: Fn(&Path) -> Result<Vec<u8>>,
53{
54    let data = read_file_or_stdin(pan_file.as_path())?;
55    let include_header = if *no_header { false } else { *header };
56    let enc = match encoding.to_ascii_lowercase().as_str() {
57        "mac" | "macroman" | "mac-roman" | "macintosh" => {
58            ctb_formats_pan::output::PanCsvEncoding::MacRoman
59        }
60        "win" | "windows" | "win1252" | "windows-1252" | "panwindows" => {
61            ctb_formats_pan::output::PanCsvEncoding::Windows
62        }
63        "utf8-windows" | "windows-utf8" | "utf8-win" | "win-utf8" => {
64            ctb_formats_pan::output::PanCsvEncoding::Utf8Windows
65        }
66        _ => ctb_formats_pan::output::PanCsvEncoding::Utf8,
67    };
68    let delim = match delimiter.to_ascii_lowercase().replace('_', "-").as_str()
69    {
70        "tab" | "tabs" | "tsv" => {
71            ctb_formats_pan::output::PanExportDelimiter::Tabs
72        }
73        "tab-no-quotes"
74        | "tabs-no-quotes"
75        | "tab-without-quotes"
76        | "tabs-without-quotes"
77        | "tabs-w/o-quotes"
78        | "tsv-no-quotes" => {
79            ctb_formats_pan::output::PanExportDelimiter::TabsWithoutQuotes
80        }
81        "wordperfect" | "wp" => {
82            ctb_formats_pan::output::PanExportDelimiter::WordPerfect
83        }
84        "commas" | "csv" => ctb_formats_pan::output::PanExportDelimiter::Commas,
85        _ => bail!(
86            "Unknown format for --delimiter: {delimiter:?}. Valid options are: commas, tabs, tabs-no-quotes, wordperfect"
87        ),
88    };
89    let opts = ctb_formats_pan::output::PanCsvOptions {
90        output_patterns: *patterns,
91        truncate_multiline: !*keep_multiline,
92        include_header,
93        encoding: enc,
94        delimiter: delim,
95        crlf: *crlf
96            || (delim
97                != ctb_formats_pan::output::PanExportDelimiter::WordPerfect
98                && enc == ctb_formats_pan::output::PanCsvEncoding::Windows),
99        replicate_double_encoding: *replicate_double_encoding,
100        run_startup_procedure: *run_startup_procedure,
101    };
102    let output =
103        ctb_formats_pan::output::pan_to_csv_with_options(&data, &opts)?;
104    Ok(ToolResult::immediate_ok(output))
105}
106
107/// CLI execution helper for exporting procedures from a Panorama file.
108pub fn pan2procedures<FRead>(
109    pan_file: &Path,
110    output_dir: Option<&Path>,
111    extension: Option<&str>,
112    encoding: &str,
113    read_file_or_stdin: FRead,
114) -> Result<ToolResult>
115where
116    FRead: Fn(&Path) -> Result<Vec<u8>>,
117{
118    let data = read_file_or_stdin(pan_file)?;
119    let enc = match encoding.to_ascii_lowercase().as_str() {
120        "mac" | "macroman" | "mac-roman" | "macintosh" => {
121            ctb_formats_pan::output::PanCsvEncoding::MacRoman
122        }
123        "win" | "windows" | "win1252" | "windows-1252" | "panwindows" => {
124            ctb_formats_pan::output::PanCsvEncoding::Windows
125        }
126        "utf8-windows" | "windows-utf8" | "utf8-win" | "win-utf8" => {
127            ctb_formats_pan::output::PanCsvEncoding::Utf8Windows
128        }
129        _ => ctb_formats_pan::output::PanCsvEncoding::Utf8,
130    };
131    let output_msg = ctb_formats_pan::output::export_pan_procedures(
132        pan_file, &data, output_dir, extension, enc,
133    )?;
134    Ok(ToolResult::immediate_ok(output_msg.into_bytes()))
135}
136
137#[cfg(test)]
138#[allow(
139    clippy::panic,
140    clippy::expect_used,
141    clippy::unwrap_used,
142    clippy::unwrap_in_result,
143    clippy::panic_in_result_fn,
144    clippy::indexing_slicing,
145    clippy::arithmetic_side_effects,
146    reason = "Standard repository test boilerplate"
147)]
148mod tests {
149    use super::*;
150
151    #[crate::ctb_test]
152    fn test_pan_cli() {}
153
154    #[crate::ctb_test]
155    fn test_pan2procedures_cli() -> anyhow::Result<()> {
156        let mut pan_bytes = Vec::new();
157        pan_bytes.extend_from_slice(&0u32.to_le_bytes());
158        pan_bytes.push(0x00);
159        pan_bytes.push(4);
160        pan_bytes.extend_from_slice(b"TEST");
161        pan_bytes.push(0);
162        pan_bytes.extend_from_slice(&0u32.to_le_bytes());
163
164        let mut payload = Vec::new();
165        let name_bytes = b"Hello";
166        let code_bytes = b"message \"World\"";
167        let name_len = u8::try_from(name_bytes.len())?;
168        let code_len = u16::try_from(code_bytes.len())?;
169        let rec_size = usize::from(name_len)
170            .saturating_add(usize::from(code_len))
171            .saturating_add(8);
172        let rec_size_u32 = u32::try_from(rec_size)?;
173        payload.extend_from_slice(&rec_size_u32.to_le_bytes());
174        payload.push(0x84);
175        payload.push(name_len);
176        payload.extend_from_slice(name_bytes);
177        payload.extend_from_slice(&code_len.to_le_bytes());
178        payload.extend_from_slice(code_bytes);
179
180        let section_size = payload.len().saturating_add(12);
181        let sec_size_u32 = u32::try_from(section_size)?;
182        pan_bytes.extend_from_slice(&sec_size_u32.to_le_bytes());
183        pan_bytes.push(0x83);
184        pan_bytes.push(6);
185        pan_bytes.extend_from_slice(b"MACROS");
186        pan_bytes.extend_from_slice(&payload);
187
188        let temp = tempfile::tempdir()?;
189        let out_dir = temp.path().join("cli_export");
190
191        let _ = pan2procedures(
192            Path::new("test.pan"),
193            Some(&out_dir),
194            Some("estes"),
195            "utf8",
196            |_| Ok(pan_bytes.clone()),
197        )?;
198
199        ensure!(out_dir.join("Hello.estes").exists());
200        let content = std::fs::read_to_string(out_dir.join("Hello.estes"))?;
201        ensure!(content == "message \"World\"\n");
202
203        Ok(())
204    }
205}