ctb_formats_compression_cli/
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 compression and decompression.
21
22use anyhow::anyhow;
23pub use ctb_formats_compression::*;
24use ctb_formats_detection::{
25    FormatCategory, detect_file_format, detect_format_id,
26};
27use ctb_formats_utilities::extension_data::lookup_format_by_extension;
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace crate prelude"
32)]
33pub(crate) use ctb_utilities::*;
34use std::path::{Path, PathBuf};
35
36/// Detects the compression format given a `FileEntity` and `PayloadSource`.
37pub fn detect_entity(
38    entity: &ctb_io_file::FileEntity,
39    payload: &mut dyn ctb_io_file::PayloadSource,
40) -> Option<FormatId> {
41    detect_file_format(entity, payload, Some(FormatCategory::Compression))
42        .filter(|&id| is_supported(id))
43}
44
45/// Detects the compression format for a given file path (or "-" for stdin).
46pub fn detect_path(path: &Path) -> Result<Option<FormatId>> {
47    if path == Path::new("-") {
48        let entity = ctb_io_file::FileEntity::from_stream(Some("-"));
49        let mut payload =
50            ctb_io_file::ReaderPayloadSource::new(std::io::stdin());
51        Ok(detect_entity(&entity, &mut payload))
52    } else {
53        let entity = ctb_io_file::FileEntity::from_filesystem(path, None)?;
54        let mut payload = ctb_io_file::DiskPayloadSource::open(path)?;
55        Ok(detect_entity(&entity, &mut payload))
56    }
57}
58
59/// Performs multi-signal detection using both header bytes and file extension.
60pub fn detect(
61    data: Option<&[u8]>,
62    filename_or_ext: Option<&str>,
63) -> Option<FormatId> {
64    detect_format_id(data, filename_or_ext, Some(FormatCategory::Compression))
65        .filter(|&id| is_supported(id))
66        .or_else(|| {
67            filename_or_ext.and_then(|name| {
68                let clean = name.trim().trim_start_matches('.');
69                lookup_format_by_extension(clean)
70                    .into_iter()
71                    .find(|&fid| is_supported(fid))
72            })
73        })
74}
75
76/// Execution options for compressing a file via the CLI.
77#[derive(clap::Args, Debug, Clone, PartialEq, Eq)]
78pub struct CliCompressArgs {
79    /// Compression format (e.g. `br`, `gz`, `deflate`, `zlib`). See table below for allowed values.
80    #[arg(value_parser = crate::parse_compression_format)]
81    pub format: SupportedCompressionFormat,
82    /// Input file path (or - for stdin)
83    #[arg(default_value = "-")]
84    pub file: PathBuf,
85    /// Output file path or - for stdout. Defaults to stdout when input is stdin, or appends the format extension (`<file>.<ext>`) for file input.
86    #[arg(short = 'o', long = "output", alias = "file", value_name = "OUTPUT")]
87    pub output: Option<PathBuf>,
88    /// Force overwrite existing destination file without confirmation.
89    #[arg(long = "force")]
90    pub force: bool,
91    /// Verify compressed output by decompressing it
92    #[arg(long = "verify", conflicts_with = "no_verify")]
93    pub verify: bool,
94    /// Skip verification of compressed output
95    #[arg(long = "no-verify", conflicts_with = "verify")]
96    pub no_verify: bool,
97}
98
99impl CliCompressArgs {
100    /// Returns whether verification should be enabled for this invocation.
101    pub fn verify_enabled(&self, format: SupportedCompressionFormat) -> bool {
102        if self.verify {
103            true
104        } else if self.no_verify {
105            false
106        } else {
107            format.default_verify()
108        }
109    }
110}
111
112/// Execution options for decompressing a file via the CLI.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct CliDecompressArgs {
115    /// Optional format identifier or positional format string.
116    pub format: Option<String>,
117    /// Path to input file or "-" for stdin.
118    pub input_path: PathBuf,
119    /// Optional output file path or "-" for stdout. Defaults to stdout when
120    /// input is stdin, or strips the compression extension (or appends
121    /// `.decompressed` if none recognized) when decompressing a file.
122    pub output_path: Option<PathBuf>,
123    /// Force overwrite existing destination file without confirmation.
124    pub force: bool,
125}
126
127/// Result of executing a CLI compression/decompression command.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum CliCompressionOutput {
130    /// Output data to be written to standard output.
131    Stdout(Vec<u8>),
132    /// Operation completed and output was written to the specified file path.
133    FileWritten(PathBuf),
134    /// Operation cancelled by user during overwrite prompt.
135    Cancelled,
136}
137
138/// Infer output filename when decompressing without an explicit output path.
139pub fn infer_decompressed_filename(input_path: &Path) -> PathBuf {
140    ctb_formats_utilities::infer_decompressed_path(input_path)
141}
142
143/// Executes compression logic for CLI invocations.
144pub fn execute_cli_compress<FRead, FOverwrite>(
145    args: CliCompressArgs,
146    read_data: FRead,
147    check_overwrite: FOverwrite,
148) -> Result<CliCompressionOutput>
149where
150    FRead: Fn(&Path) -> Result<Vec<u8>>,
151    FOverwrite: Fn(&Path, bool) -> Result<bool>,
152{
153    let compression_format = args.format;
154    let data = read_data(args.file.as_path())?;
155    let verify = args.verify_enabled(compression_format);
156    let compressed =
157        crate::compress_with_verify(&data, compression_format, verify)?;
158
159    let target_path = match args.output {
160        Some(out_path) => out_path,
161        None => {
162            if args.file.as_path() == Path::new("-") {
163                PathBuf::from("-")
164            } else {
165                PathBuf::from(format!(
166                    "{}.{}",
167                    args.file.display(),
168                    compression_format.extension()
169                ))
170            }
171        }
172    };
173
174    if target_path.as_path() == Path::new("-") {
175        Ok(CliCompressionOutput::Stdout(compressed))
176    } else {
177        if !check_overwrite(&target_path, args.force)? {
178            return Ok(CliCompressionOutput::Cancelled);
179        }
180        std::fs::write(&target_path, &compressed).with_context(|| {
181            format!("Failed to write to {}", target_path.display())
182        })?;
183        Ok(CliCompressionOutput::FileWritten(target_path))
184    }
185}
186
187/// Executes decompression logic for CLI invocations.
188pub fn execute_cli_decompress<FRead, FOverwrite>(
189    args: CliDecompressArgs,
190    read_data: FRead,
191    check_overwrite: FOverwrite,
192) -> Result<CliCompressionOutput>
193where
194    FRead: Fn(&Path) -> Result<Vec<u8>>,
195    FOverwrite: Fn(&Path, bool) -> Result<bool>,
196{
197    let (resolved_input_path, explicit_format) = match args.format {
198        Some(ref fmt_str) => {
199            if let Ok(parsed_fmt) =
200                crate::parse_decompression_format(fmt_str.as_str())
201            {
202                (args.input_path.clone(), Some(parsed_fmt))
203            } else if args.input_path.as_path() == Path::new("-") {
204                let in_path = PathBuf::from(fmt_str);
205                (in_path, None)
206            } else {
207                return Err(anyhow!(
208                    "Unknown decompression format: '{fmt_str}'"
209                ));
210            }
211        }
212        None => (args.input_path.clone(), None),
213    };
214
215    let data = read_data(resolved_input_path.as_path())?;
216
217    let compression_format = if let Some(fmt) = explicit_format {
218        fmt
219    } else {
220        let detected_id = crate::detect_path(&resolved_input_path)
221            .ok()
222            .flatten()
223            .or_else(|| {
224                crate::detect(Some(&data), resolved_input_path.to_str())
225            })
226            .ok_or_else(|| {
227                anyhow!(
228                    "Could not determine compression format for '{}'",
229                    resolved_input_path.display()
230                )
231            })?;
232        detected_id.to_supported_decompression_format()?
233    };
234
235    let decompressed = crate::decompress(&data, compression_format)?;
236
237    let target_path = match args.output_path {
238        Some(out_path) => out_path,
239        None => {
240            if resolved_input_path.as_path() == Path::new("-") {
241                PathBuf::from("-")
242            } else {
243                infer_decompressed_filename(&resolved_input_path)
244            }
245        }
246    };
247
248    if target_path.as_path() == Path::new("-") {
249        Ok(CliCompressionOutput::Stdout(decompressed))
250    } else {
251        if !check_overwrite(&target_path, args.force)? {
252            return Ok(CliCompressionOutput::Cancelled);
253        }
254        std::fs::write(&target_path, &decompressed).with_context(|| {
255            format!("Failed to write to {}", target_path.display())
256        })?;
257        Ok(CliCompressionOutput::FileWritten(target_path))
258    }
259}
260pub fn run_compress<FRead, FOverwrite>(
261    args: CliCompressArgs,
262    read_file_or_stdin: FRead,
263    check_overwrite_prompt: FOverwrite,
264) -> Result<ToolResult>
265where
266    FRead: Fn(&Path) -> Result<Vec<u8>>,
267    FOverwrite: Fn(&Path, bool) -> Result<bool>,
268{
269    let cli_output =
270        execute_cli_compress(args, read_file_or_stdin, check_overwrite_prompt)?;
271    match cli_output {
272        CliCompressionOutput::Stdout(bytes) => {
273            Ok(ToolResult::immediate_ok(bytes))
274        }
275        CliCompressionOutput::FileWritten(_) => {
276            Ok(ToolResult::immediate_ok(Vec::new()))
277        }
278        CliCompressionOutput::Cancelled => Ok(ToolResult::immediate_err(
279            "Operation cancelled.\n".as_bytes().to_vec(),
280            1,
281        )),
282    }
283}
284
285pub fn run_decompress<FRead, FOverwrite>(
286    format: Option<String>,
287    file: PathBuf,
288    output: Option<PathBuf>,
289    force: bool,
290    read_file_or_stdin: FRead,
291    check_overwrite_prompt: FOverwrite,
292) -> Result<ToolResult>
293where
294    FRead: Fn(&Path) -> Result<Vec<u8>>,
295    FOverwrite: Fn(&Path, bool) -> Result<bool>,
296{
297    let cli_output = execute_cli_decompress(
298        CliDecompressArgs {
299            format,
300            input_path: file,
301            output_path: output,
302            force,
303        },
304        read_file_or_stdin,
305        check_overwrite_prompt,
306    )?;
307    match cli_output {
308        CliCompressionOutput::Stdout(bytes) => {
309            Ok(ToolResult::immediate_ok(bytes))
310        }
311        CliCompressionOutput::FileWritten(_) => {
312            Ok(ToolResult::immediate_ok(Vec::new()))
313        }
314        CliCompressionOutput::Cancelled => Ok(ToolResult::immediate_err(
315            "Operation cancelled.\n".as_bytes().to_vec(),
316            1,
317        )),
318    }
319}
320
321#[cfg(test)]
322#[allow(
323    clippy::panic,
324    clippy::expect_used,
325    clippy::unwrap_used,
326    clippy::unwrap_in_result,
327    clippy::panic_in_result_fn,
328    clippy::indexing_slicing,
329    clippy::arithmetic_side_effects,
330    reason = "Standard repository test boilerplate"
331)]
332mod tests {
333    use super::*;
334
335    #[ctb_test]
336    fn test_infer_decompressed_filename() {
337        assert_eq!(
338            infer_decompressed_filename(Path::new("file.txt.gz")),
339            PathBuf::from("file.txt")
340        );
341        assert_eq!(
342            infer_decompressed_filename(Path::new("archive.tar.Z")),
343            PathBuf::from("archive.tar")
344        );
345        assert_eq!(
346            infer_decompressed_filename(Path::new("document.z")),
347            PathBuf::from("document")
348        );
349        assert_eq!(
350            infer_decompressed_filename(Path::new("document.C")),
351            PathBuf::from("document")
352        );
353        assert_eq!(
354            infer_decompressed_filename(Path::new("data.tar.lz4")),
355            PathBuf::from("data.tar")
356        );
357        assert_eq!(
358            infer_decompressed_filename(Path::new("data.tar.lzma")),
359            PathBuf::from("data.tar")
360        );
361        assert_eq!(
362            infer_decompressed_filename(Path::new("data.tar.lzma2")),
363            PathBuf::from("data.tar")
364        );
365        assert_eq!(
366            infer_decompressed_filename(Path::new("data.tar.lz")),
367            PathBuf::from("data.tar")
368        );
369        assert_eq!(
370            infer_decompressed_filename(Path::new("data.tar.lzip")),
371            PathBuf::from("data.tar")
372        );
373        assert_eq!(
374            infer_decompressed_filename(Path::new("data.tar.xz")),
375            PathBuf::from("data.tar")
376        );
377        assert_eq!(
378            infer_decompressed_filename(Path::new("data.tar.zst")),
379            PathBuf::from("data.tar")
380        );
381        assert_eq!(
382            infer_decompressed_filename(Path::new("data.tar.zstd")),
383            PathBuf::from("data.tar")
384        );
385        assert_eq!(
386            infer_decompressed_filename(Path::new("data.tar.lzo")),
387            PathBuf::from("data.tar")
388        );
389        assert_eq!(
390            infer_decompressed_filename(Path::new("unknown.bin")),
391            PathBuf::from("unknown.bin.decompressed")
392        );
393        assert_eq!(
394            infer_decompressed_filename(Path::new("data.tar.xzip")),
395            PathBuf::from("data.tar.xzip.decompressed")
396        );
397    }
398
399    #[ctb_test]
400    fn test_cli_compress_verify_flags() {
401        let in_repo_fmt = SupportedCompressionFormat::CompressLzw;
402        let crate_fmt = SupportedCompressionFormat::Gzip;
403
404        let default_args = CliCompressArgs {
405            format: SupportedCompressionFormat::CompressLzw,
406            file: PathBuf::from("-"),
407            output: None,
408            force: false,
409            verify: false,
410            no_verify: false,
411        };
412        assert!(default_args.verify_enabled(in_repo_fmt));
413        assert!(!default_args.verify_enabled(crate_fmt));
414
415        let verify_args = CliCompressArgs {
416            format: SupportedCompressionFormat::Gzip,
417            file: PathBuf::from("-"),
418            output: None,
419            force: false,
420            verify: true,
421            no_verify: false,
422        };
423        assert!(verify_args.verify_enabled(in_repo_fmt));
424        assert!(verify_args.verify_enabled(crate_fmt));
425
426        let no_verify_args = CliCompressArgs {
427            format: SupportedCompressionFormat::CompressLzw,
428            file: PathBuf::from("-"),
429            output: None,
430            force: false,
431            verify: false,
432            no_verify: true,
433        };
434        assert!(!no_verify_args.verify_enabled(in_repo_fmt));
435        assert!(!no_verify_args.verify_enabled(crate_fmt));
436    }
437
438    #[ctb_test]
439    fn test_cli_compress_execution() {
440        let sample_data =
441            b"Hello, world! This is a test for CLI compression.".to_vec();
442        let read_mock = |_path: &Path| Ok(sample_data.clone());
443        let overwrite_mock = |_path: &Path, _force: bool| Ok(true);
444
445        // Compress with --no-verify
446        let args = CliCompressArgs {
447            format: SupportedCompressionFormat::CompressLzw,
448            file: PathBuf::from("-"),
449            output: Some(PathBuf::from("-")),
450            force: false,
451            verify: false,
452            no_verify: true,
453        };
454        let out =
455            execute_cli_compress(args, read_mock, overwrite_mock).unwrap();
456        match out {
457            CliCompressionOutput::Stdout(compressed) => {
458                let decompressed = crate::decompress(
459                    &compressed,
460                    SupportedDecompressionFormat::CompressLzw,
461                )
462                .unwrap();
463                assert_eq!(decompressed, sample_data);
464            }
465            _ => panic!("Expected Stdout output"),
466        }
467
468        // Compress with --verify
469        let args = CliCompressArgs {
470            format: SupportedCompressionFormat::Gzip,
471            file: PathBuf::from("-"),
472            output: Some(PathBuf::from("-")),
473            force: false,
474            verify: true,
475            no_verify: false,
476        };
477        let out =
478            execute_cli_compress(args, read_mock, overwrite_mock).unwrap();
479        match out {
480            CliCompressionOutput::Stdout(compressed) => {
481                let decompressed = crate::decompress(
482                    &compressed,
483                    SupportedDecompressionFormat::Gzip,
484                )
485                .unwrap();
486                assert_eq!(decompressed, sample_data);
487            }
488            _ => panic!("Expected Stdout output"),
489        }
490    }
491
492    #[ctb_test]
493    fn test_cli_decompress_execution() {
494        let sample_data =
495            b"Hello, world! Decompression CLI test data.".to_vec();
496        let compressed_gzip =
497            crate::compress(&sample_data, SupportedCompressionFormat::Gzip)
498                .unwrap();
499
500        let compressed_for_read = compressed_gzip.clone();
501        let read_mock = move |_path: &Path| Ok(compressed_for_read.clone());
502        let overwrite_mock = |_path: &Path, _force: bool| Ok(true);
503
504        // Decompress with single positional file path (inferred format)
505        let args = CliDecompressArgs {
506            format: Some("sample.txt.gz".to_string()),
507            input_path: PathBuf::from("-"),
508            output_path: Some(PathBuf::from("-")),
509            force: true,
510        };
511        let out =
512            execute_cli_decompress(args, read_mock.clone(), overwrite_mock)
513                .unwrap();
514        match out {
515            CliCompressionOutput::Stdout(decompressed) => {
516                assert_eq!(decompressed, sample_data);
517            }
518            _ => panic!("Expected Stdout output"),
519        }
520
521        // Decompress with explicit format and input path
522        let args = CliDecompressArgs {
523            format: Some("gzip".to_string()),
524            input_path: PathBuf::from("sample.txt.gz"),
525            output_path: Some(PathBuf::from("-")),
526            force: true,
527        };
528        let out =
529            execute_cli_decompress(args, read_mock, overwrite_mock).unwrap();
530        match out {
531            CliCompressionOutput::Stdout(decompressed) => {
532                assert_eq!(decompressed, sample_data);
533            }
534            _ => panic!("Expected Stdout output"),
535        }
536    }
537
538    #[ctb_test]
539    fn test_reader_payload_source_detection() {
540        let gzip_stream: &[u8] =
541            &[0x1F, 0x8B, 0x08, 0x00, 0x01, 0x02, 0x03, 0x04];
542        let entity = ctb_io_file::FileEntity::from_stream(Some("input.gz"));
543        let mut payload = ctb_io_file::ReaderPayloadSource::new(gzip_stream);
544        let detected = detect_entity(&entity, &mut payload);
545        assert_eq!(detected, Some(FormatId::Gzip));
546    }
547
548    #[ctb_test]
549    fn test_magic_detection() {
550        assert_eq!(
551            detect(Some(&[0x1F, 0xA0]), None),
552            Some(FormatId::ScoCompress)
553        );
554        assert_eq!(
555            detect(Some(&[0x1F, 0x8B, 0x08, 0x00]), None),
556            Some(FormatId::Gzip)
557        );
558        assert_eq!(
559            detect(Some(&[0x42, 0x5A, 0x68]), None),
560            Some(FormatId::Bzip2)
561        );
562        assert_eq!(
563            detect(Some(&[0x42, 0x5A, 0x30]), None),
564            Some(FormatId::Bzip)
565        );
566        assert_eq!(detect(Some(&[0x1F, 0x1E]), None), Some(FormatId::Pack));
567        assert_eq!(detect(Some(&[0x1F, 0x1F]), None), Some(FormatId::OldPack));
568        assert_eq!(
569            detect(Some(&[0x1F, 0x9D, 0x90]), None),
570            Some(FormatId::CompressLzw)
571        );
572        assert_eq!(
573            detect(Some(&[0x1F, 0x9D, 0x10]), None),
574            Some(FormatId::CompressLzw2)
575        );
576        assert_eq!(detect(Some(&[0xFF, 0x1F]), None), Some(FormatId::Compact));
577        assert_eq!(detect(Some(&[0x1F, 0x9F]), None), Some(FormatId::Freeze2));
578        assert_eq!(detect(Some(&[0x1F, 0x9E]), None), Some(FormatId::Freeze1));
579        assert_eq!(
580            detect(Some(&[0x04, 0x22, 0x4D, 0x18]), None),
581            Some(FormatId::Lz4)
582        );
583        assert_eq!(
584            detect(Some(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]), None),
585            Some(FormatId::Xz)
586        );
587        assert_eq!(
588            detect(Some(&[0x4C, 0x5A, 0x49, 0x50]), None),
589            Some(FormatId::Lzip)
590        );
591        assert_eq!(
592            detect(Some(&[0x28, 0xB5, 0x2F, 0xFD]), None),
593            Some(FormatId::Zstd)
594        );
595        assert_eq!(
596            detect(
597                Some(&[0x89, 0x4C, 0x5A, 0x4F, 0x00, 0x0D, 0x0A, 0x1A, 0x0A]),
598                None
599            ),
600            Some(FormatId::Lzo)
601        );
602        assert_eq!(detect(Some(b"RZIP\x02\x01"), None), Some(FormatId::Rzip));
603        assert_eq!(detect(Some(b"SZ\x0a\x04"), None), Some(FormatId::Szip));
604    }
605
606    #[ctb_test]
607    fn test_compress_help_table_content() {
608        let help_str = crate::COMPRESSION_AFTER_HELP.as_str();
609        assert!(help_str.contains("Supported compression formats:"));
610        assert!(help_str.contains("br, brotli: Brotli compressed stream"));
611        assert!(help_str.contains("gz, gzip: GNU gzip format"));
612        assert!(help_str.contains(
613            "compress-h, compress-sco, sco-compress: `compress`: SCO `compress -H` format"
614        ));
615    }
616
617    struct Cli;
618    impl Cli {
619        fn command() -> clap::Command {
620            use clap::Args;
621            let cmd = clap::Command::new("ctoolbox");
622            let compress_sub =
623                CliCompressArgs::augment_args(clap::Command::new("compress"))
624                    .after_help(crate::COMPRESSION_AFTER_HELP.as_str());
625            cmd.subcommand(compress_sub)
626        }
627    }
628
629    #[crate::ctb_test]
630    fn test_compress_command_help() {
631        let mut cmd = Cli::command();
632        let compress_sub = cmd
633            .find_subcommand_mut("compress")
634            .expect("compress subcommand should exist");
635        let mut help_buf = Vec::new();
636        compress_sub
637            .write_help(&mut help_buf)
638            .expect("Should format help");
639        let help_str = String::from_utf8(help_buf).expect("UTF-8 help");
640
641        assert!(help_str.contains("Supported compression formats:"));
642        assert!(help_str.contains("br, brotli: Brotli compressed stream"));
643        assert!(help_str.contains("gz, gzip: GNU gzip format"));
644        assert!(help_str.contains(
645            "compress-h, compress-sco, sco-compress: `compress`: SCO `compress -H` format"
646        ));
647    }
648}