crush-cli 0.2.1

Command-line interface for the Crush compression library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use crate::algorithm::{select_algorithm, DEFAULT_PARALLEL_THRESHOLD_BYTES};
use crate::cli::CompressArgs;
use crate::commands::utils;
use crate::error::{CliError, Result};
use crate::output::{self, CompressionResult};
use crush_core::cancel::CancellationToken;
use crush_core::plugin::FileMetadata;
use crush_core::{compress_with_options, CompressionOptions};
use filetime::FileTime;
use indicatif::{ProgressBar, ProgressStyle};
use is_terminal::IsTerminal;
use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{debug, info, instrument, trace, warn};

pub fn run(
    args: &CompressArgs,
    interrupted: Arc<dyn CancellationToken>,
    gpu_enabled: bool,
) -> Result<()> {
    // Check if reading from stdin (no input files provided)
    if args.input.is_empty() {
        compress_stdin(args, interrupted, gpu_enabled)?;
    } else {
        // Process each input file
        for input_path in &args.input {
            compress_file(input_path, args, interrupted.clone(), gpu_enabled)?;
        }
    }
    Ok(())
}

/// Compress data from stdin
#[instrument(skip(args, interrupted))]
fn compress_stdin(
    args: &CompressArgs,
    interrupted: Arc<dyn CancellationToken>,
    gpu_enabled: bool,
) -> Result<()> {
    info!("Compressing from stdin");

    // Check for cancellation before starting
    if interrupted.is_cancelled() {
        return Err(CliError::Interrupted);
    }

    // Validate output path if not writing to stdout
    if !args.stdout && args.output.is_none() {
        return Err(CliError::InvalidInput(
            "When reading from stdin, either --output or --stdout must be specified".to_string(),
        ));
    }

    // Read all data from stdin
    trace!("Reading from stdin");
    let mut input_data = Vec::new();
    io::stdin().read_to_end(&mut input_data)?;
    let input_size = input_data.len() as u64;
    debug!("Read {} bytes from stdin", input_size);

    // Check for cancellation after reading
    if interrupted.is_cancelled() {
        return Err(CliError::Interrupted);
    }

    // Select algorithm: streaming mode (unknown size) → parallel-deflate
    let selected_algo = select_algorithm(
        None,
        args.plugin.as_deref(),
        DEFAULT_PARALLEL_THRESHOLD_BYTES,
        gpu_enabled,
    );
    info!(
        "Selected algorithm: {} (streaming, input size unknown)",
        selected_algo
    );

    // Prepare compression options (no file metadata for stdin)
    let mut options = CompressionOptions::default()
        .with_weights(args.level.to_weights())
        .with_cancel_token(Arc::clone(&interrupted));

    if selected_algo != "default" {
        debug!("Applying plugin selection: {}", selected_algo);
        options = options.with_plugin(selected_algo);
    }

    if let Some(timeout_secs) = args.timeout {
        debug!("Setting compression timeout: {} seconds", timeout_secs);
        options = options.with_timeout(Duration::from_secs(timeout_secs));
    }

    // Start timing
    let start = Instant::now();

    // Compress (cancellation is handled internally by compress_with_options)
    trace!("Starting compression operation");
    let compressed_data = compress_with_options(&input_data, &options)?;

    // Stop timing
    let duration = start.elapsed();
    debug!(
        "Compression completed in {:.3}s, output size: {} bytes",
        duration.as_secs_f64(),
        compressed_data.len()
    );

    // Check for interrupt before writing
    if interrupted.is_cancelled() {
        return Err(CliError::Interrupted);
    }

    // Write output
    if args.stdout {
        // Write to stdout
        trace!("Writing compressed data to stdout");
        utils::write_to_stdout(&compressed_data)?;
    } else if let Some(ref output_path) = args.output {
        // Write to file
        trace!("Writing compressed data to {}", output_path.display());
        utils::validate_output(output_path, args.force)?;
        utils::write_with_cleanup(output_path, &compressed_data)?;

        // Check for cancellation after writing (cleanup partial file if cancelled)
        utils::check_cancelled_with_cleanup(&interrupted, output_path)?;
    }

    // Calculate statistics
    let output_size = compressed_data.len() as u64;
    let compression_ratio = utils::calculate_compression_ratio(input_size, output_size);
    let throughput_mbps = utils::calculate_throughput_mbps(input_size, duration);

    // Log performance metrics (but don't print to stdout/stderr if using stdout mode)
    debug!(
        input_size,
        output_size,
        compression_ratio,
        throughput_mbps,
        plugin = %selected_algo,
        "Stdin compression: throughput {:.2} MB/s, ratio {:.1}%",
        throughput_mbps,
        compression_ratio
    );

    info!(
        output_size,
        compression_ratio,
        throughput_mbps,
        duration_secs = duration.as_secs_f64(),
        plugin = %selected_algo,
        "Compressed stdin: {} bytes -> {} bytes ({:.1}% reduction) in {:.3}s at {:.2} MB/s",
        input_size,
        output_size,
        100.0 - compression_ratio,
        duration.as_secs_f64(),
        throughput_mbps
    );

    Ok(())
}

#[instrument(skip(args, interrupted), fields(file = %input_path.display()))]
fn compress_file(
    input_path: &Path,
    args: &CompressArgs,
    interrupted: Arc<dyn CancellationToken>,
    gpu_enabled: bool,
) -> Result<()> {
    info!("Starting compression of {}", input_path.display());
    // Check for cancellation before starting
    utils::check_cancelled(&interrupted)?;

    // Validate input file
    utils::validate_input(input_path)?;

    // Determine output path
    let output_path = determine_output_path(input_path, &args.output)?;

    // Validate output path
    utils::validate_output(&output_path, args.force)?;

    // Get file metadata for mtime and size
    let file_metadata = fs::metadata(input_path)?;
    let mtime = FileTime::from_last_modification_time(&file_metadata);
    let input_size = file_metadata.len();

    // Show cancel hint for large files (>1MB)
    if !args.stdout {
        crate::feedback::show_cancel_hint(crate::feedback::should_show_hint(input_size));
    }

    // Create progress indicator for larger files (but not when writing to stdout)
    let show_progress = std::io::stderr().is_terminal() && !args.stdout;
    let spinner = if show_progress && input_size > 1024 * 1024 {
        let pb = ProgressBar::new(input_size);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("{spinner:.green} Compressing {msg} [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")
                .expect("Invalid progress bar template")
                .progress_chars("=>-"),
        );
        pb.set_message(input_path.display().to_string());
        pb.enable_steady_tick(Duration::from_millis(100));
        Some(pb)
    } else {
        None
    };

    // Warn if --gpu-device is specified without --plugin gpu-deflate
    if args.gpu_device.is_some() {
        let is_gpu_plugin = args
            .plugin
            .as_deref()
            .is_some_and(|p| p.eq_ignore_ascii_case("gpu-deflate"));
        if !is_gpu_plugin {
            warn!("--gpu-device has no effect without --plugin gpu-deflate");
        }
    }

    // Select algorithm based on file size threshold (FR-016)
    let selected_algo = select_algorithm(
        Some(input_size),
        args.plugin.as_deref(),
        DEFAULT_PARALLEL_THRESHOLD_BYTES,
        gpu_enabled,
    );
    info!(
        "Selected algorithm: {} for {} byte input (threshold: {} bytes)",
        selected_algo, input_size, DEFAULT_PARALLEL_THRESHOLD_BYTES
    );

    // Prepare compression options with metadata
    let file_meta = FileMetadata {
        mtime: Some(mtime.unix_seconds()),
        #[cfg(unix)]
        permissions: {
            use std::os::unix::fs::PermissionsExt;
            Some(file_metadata.permissions().mode())
        },
    };

    let mut options = CompressionOptions::default()
        .with_weights(args.level.to_weights())
        .with_file_metadata(file_meta)
        .with_cancel_token(Arc::clone(&interrupted));

    if selected_algo != "default" {
        debug!("Applying plugin selection: {}", selected_algo);
        options = options.with_plugin(selected_algo);
    }

    if let Some(timeout_secs) = args.timeout {
        debug!("Setting compression timeout: {} seconds", timeout_secs);
        options = options.with_timeout(Duration::from_secs(timeout_secs));
    }

    // Read input file
    trace!("Reading input file: {}", input_path.display());
    let input_data = fs::read(input_path)?;
    debug!("Read {} bytes from input file", input_data.len());

    // Check for cancellation after reading
    utils::check_cancelled(&interrupted)?;

    // Start timing
    let start = Instant::now();

    // Compress
    trace!("Starting compression operation");
    let compressed_data = compress_with_options(&input_data, &options)?;

    // Stop timing
    let duration = start.elapsed();
    debug!(
        "Compression completed in {:.3}s, output size: {} bytes",
        duration.as_secs_f64(),
        compressed_data.len()
    );

    // Clear spinner
    if let Some(pb) = spinner {
        pb.finish_and_clear();
    }

    // Check for interrupt before writing
    if interrupted.is_cancelled() {
        return Err(CliError::Interrupted);
    }

    // Write output
    if args.stdout {
        // Write to stdout
        trace!("Writing compressed data to stdout");
        utils::write_to_stdout(&compressed_data)?;
    } else {
        // Write output file (T085: cleanup on failure/interrupt)
        if let Err(e) = fs::write(&output_path, &compressed_data) {
            // If write failed, ensure no partial file remains
            let _ = fs::remove_file(&output_path);
            return Err(e.into());
        }

        // Check for interrupt after writing (cleanup partial file if interrupted)
        if interrupted.is_cancelled() {
            // Remove the output file we just wrote
            let _ = fs::remove_file(&output_path);
            return Err(CliError::Interrupted);
        }
    }

    // Calculate statistics
    let output_size = compressed_data.len() as u64;
    let compression_ratio = utils::calculate_compression_ratio(input_size, output_size);
    let throughput_mbps = utils::calculate_throughput_mbps(input_size, duration);

    // Report the algorithm that was selected (explicit or auto-selected)
    let plugin_used = selected_algo.to_string();

    // Log performance metrics with structured fields
    debug!(
        input_size,
        output_size,
        compression_ratio,
        throughput_mbps,
        plugin = %plugin_used,
        "Performance metrics - throughput: {:.2} MB/s, compression ratio: {:.1}%, plugin: {}",
        throughput_mbps,
        compression_ratio,
        plugin_used
    );

    let size_reduction = 100.0 - compression_ratio;
    info!(
        input_path = %input_path.display(),
        output_path = %output_path.display(),
        input_size,
        output_size,
        compression_ratio,
        throughput_mbps,
        duration_secs = duration.as_secs_f64(),
        plugin = %plugin_used,
        "Compressed {} -> {} ({:.1}% {}) in {:.3}s at {:.2} MB/s",
        input_path.display(),
        output_path.display(),
        size_reduction.abs(),
        if size_reduction > 0.0 { "smaller" } else { "larger" },
        duration.as_secs_f64(),
        throughput_mbps
    );

    // Create and display result (but not when writing to stdout)
    if !args.stdout {
        let result = CompressionResult {
            input_path: input_path.to_path_buf(),
            output_path: output_path.clone(),
            input_size,
            output_size,
            compression_ratio,
            duration,
            throughput_mbps,
            plugin_used,
        };

        output::format_compression_result(&result, show_progress);
    }

    // NOTE: Original files are kept by default (safe behavior)
    // To delete originals after compression, users should manually delete them
    // TODO: Consider adding a --remove or --delete flag in the future if needed

    Ok(())
}

/// Determine the output file path
fn determine_output_path(input: &Path, output_arg: &Option<PathBuf>) -> Result<PathBuf> {
    if let Some(output) = output_arg {
        // User specified output path
        if output.is_dir() {
            // Output is a directory - use input filename with .crush extension
            let filename = input
                .file_name()
                .ok_or_else(|| CliError::InvalidInput("Invalid input filename".to_string()))?;
            Ok(output.join(filename).with_extension("crush"))
        } else {
            // Output is a file path
            Ok(output.clone())
        }
    } else {
        // Default: add .crush extension to input filename
        let mut output = input.to_path_buf();
        let current_ext = output.extension().and_then(|s| s.to_str()).unwrap_or("");
        let new_ext = if current_ext.is_empty() {
            "crush".to_string()
        } else {
            format!("{}.crush", current_ext)
        };
        output.set_extension(new_ext);
        Ok(output)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn test_determine_output_path_default_adds_crush_ext() {
        let result = determine_output_path(Path::new("data.txt"), &None).expect("ok");
        assert_eq!(result, PathBuf::from("data.txt.crush"));
    }

    #[test]
    fn test_determine_output_path_no_extension() {
        let result = determine_output_path(Path::new("data"), &None).expect("ok");
        assert_eq!(result, PathBuf::from("data.crush"));
    }

    #[test]
    fn test_determine_output_path_explicit_file() {
        let output = Some(PathBuf::from("out.bin"));
        let result = determine_output_path(Path::new("data.txt"), &output).expect("ok");
        assert_eq!(result, PathBuf::from("out.bin"));
    }

    #[test]
    fn test_determine_output_path_to_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let output = Some(dir.path().to_path_buf());
        let result = determine_output_path(Path::new("data.txt"), &output).expect("ok");
        assert_eq!(result, dir.path().join("data.crush"));
    }

    #[test]
    fn test_determine_output_path_with_parent_dir() {
        let result = determine_output_path(Path::new("/tmp/data.log"), &None).expect("ok");
        assert_eq!(result, PathBuf::from("/tmp/data.log.crush"));
    }

    #[test]
    fn test_determine_output_path_double_extension() {
        let result = determine_output_path(Path::new("archive.tar.gz"), &None).expect("ok");
        assert_eq!(result, PathBuf::from("archive.tar.gz.crush"));
    }
}