runzip 0.1.8

A Rust unzip utility with HTTP URL support using Range requests
Documentation
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
//! Main entry point for the runzip CLI application.
//!
//! This binary provides a command-line interface for extracting ZIP files
//! from both local filesystem and remote HTTP URLs.

use anyhow::Result;
use clap::Parser;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use runzip::{Cli, HttpRangeReader, LocalFileReader, ReadAt, ZipExtractor, ZipFileEntry};

/// Application entry point.
///
/// Parses command-line arguments and dispatches to the appropriate handler
/// based on whether the input is a local file or HTTP URL.
#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    if cli.is_http_url() {
        // Handle remote ZIP file via HTTP Range requests
        let reader = HttpRangeReader::new(cli.file.clone()).await?;
        let transferred_before = reader.transferred_bytes();
        let reader = Arc::new(reader);

        process_zip(reader.clone(), &cli).await?;

        // Display network transfer statistics for HTTP sources
        if !cli.is_quiet() {
            let transferred = reader.transferred_bytes() - transferred_before;
            eprintln!("\nTotal bytes transferred: {}", format_size(transferred));
        }
    } else {
        // Handle local ZIP file
        let reader = Arc::new(LocalFileReader::new(Path::new(&cli.file))?);
        process_zip(reader, &cli).await?;
    }

    Ok(())
}

/// Process a ZIP archive based on CLI options.
///
/// This function handles both listing and extraction modes:
/// - List mode (`-l` or `-v`): Display archive contents
/// - Extract mode: Extract files matching the specified filters
///
/// # Arguments
///
/// * `reader` - A reader implementing the `ReadAt` trait for random access
/// * `cli` - Parsed command-line arguments
///
/// # Returns
///
/// Returns `Ok(())` on success, or an error if processing fails.
async fn process_zip<R: ReadAt + 'static>(reader: Arc<R>, cli: &Cli) -> Result<()> {
    let extractor = ZipExtractor::new(reader);

    // List mode: display archive contents and exit
    if cli.list || cli.verbose {
        return list_files(&extractor, cli.verbose).await;
    }

    // Extract mode: get all entries from the archive
    let entries = extractor.list_files().await?;

    // Apply filters to determine which files to extract:
    // 1. Skip directories (they are created automatically during extraction)
    // 2. If specific files are requested, only include matching entries
    // 3. Exclude files matching the exclusion patterns
    let files_to_extract: Vec<_> = entries
        .iter()
        .filter(|e| {
            // Skip directory entries
            if e.is_directory {
                return false;
            }

            // If specific files are requested via positional arguments,
            // only include entries that match
            if !cli.files.is_empty() {
                let matches = cli.files.iter().any(|f| {
                    if has_glob_chars(f) {
                        // Pattern contains wildcards: use glob matching
                        glob_match(f, &e.file_name)
                    } else {
                        // No wildcards: exact match on filename or full path
                        let basename = Path::new(&e.file_name)
                            .file_name()
                            .map(|s| s.to_string_lossy())
                            .unwrap_or_default();
                        e.file_name == *f || basename == *f
                    }
                });
                if !matches {
                    return false;
                }
            }

            // Exclude files matching the -x patterns
            if cli
                .exclude
                .iter()
                .any(|x| e.file_name.contains(x) || glob_match(x, &e.file_name))
            {
                return false;
            }

            true
        })
        .collect();

    // Extract each matching file
    let multiple_files = cli.pipe && files_to_extract.len() > 1;
    for entry in files_to_extract {
        extract_file(&extractor, entry, cli, multiple_files).await?;
    }

    Ok(())
}

/// List files in the ZIP archive.
///
/// Supports two output formats:
/// - Simple format (`-l`): Just file names, one per line
/// - Verbose format (`-v`): Detailed table with size, compression ratio, and timestamps
///
/// # Arguments
///
/// * `extractor` - The ZIP extractor instance
/// * `verbose` - If true, display detailed information in table format
///
/// # Returns
///
/// Returns `Ok(())` on success, or an error if listing fails.
async fn list_files<R: ReadAt + 'static>(extractor: &ZipExtractor<R>, verbose: bool) -> Result<()> {
    let entries = extractor.list_files().await?;

    if verbose {
        // Print table header for verbose output
        println!(
            "{:>10}  {:>10}  {:>5}  {:>10}  {:>5}  Name",
            "Length", "Size", "Cmpr", "Date", "Time"
        );
        println!("{}", "-".repeat(70));
    }

    // Track totals for summary line
    let mut total_uncompressed = 0u64;
    let mut total_compressed = 0u64;
    let mut file_count = 0usize;

    for entry in &entries {
        if verbose {
            // Parse DOS timestamp into human-readable format
            let (year, month, day) = entry.mod_date();
            let (hour, minute, _second) = entry.mod_time();

            // Calculate compression ratio as percentage saved
            let ratio = if entry.uncompressed_size > 0 {
                format!(
                    "{:>4}%",
                    100 - (entry.compressed_size * 100 / entry.uncompressed_size)
                )
            } else {
                "  0%".to_string()
            };

            // Print detailed entry information
            println!(
                "{:>10}  {:>10}  {}  {:04}-{:02}-{:02}  {:02}:{:02}  {}",
                entry.uncompressed_size,
                entry.compressed_size,
                ratio,
                year,
                month,
                day,
                hour,
                minute,
                entry.file_name
            );

            // Accumulate totals (excluding directories)
            if !entry.is_directory {
                total_uncompressed += entry.uncompressed_size;
                total_compressed += entry.compressed_size;
                file_count += 1;
            }
        } else {
            // Simple format: just the file name
            println!("{}", entry.file_name);
        }
    }

    // Print summary line in verbose mode
    if verbose {
        println!("{}", "-".repeat(70));
        let total_ratio = if total_uncompressed > 0 {
            format!(
                "{:>4}%",
                100 - (total_compressed * 100 / total_uncompressed)
            )
        } else {
            "  0%".to_string()
        };
        println!(
            "{:>10}  {:>10}  {}  {:>21}  {} files",
            total_uncompressed, total_compressed, total_ratio, "", file_count
        );
    }

    Ok(())
}

/// Extract a single file from the archive.
///
/// Handles various extraction options:
/// - Pipe mode (`-p`): Write to stdout instead of file
/// - Custom output directory (`-d`): Extract to specified directory
/// - Junk paths (`-j`): Ignore directory structure in archive
/// - Overwrite control (`-n`, `-o`): Handle existing files
///
/// # Arguments
///
/// * `extractor` - The ZIP extractor instance
/// * `entry` - The ZIP file entry to extract
/// * `cli` - Parsed command-line arguments
/// * `show_filename` - If true, print filename marker before content (for pipe mode with multiple files)
///
/// # Returns
///
/// Returns `Ok(())` on success, or an error if extraction fails.
async fn extract_file<R: ReadAt + 'static>(
    extractor: &ZipExtractor<R>,
    entry: &ZipFileEntry,
    cli: &Cli,
    show_filename: bool,
) -> Result<()> {
    // Pipe mode: write file contents directly to stdout
    if cli.pipe {
        if show_filename {
            use tokio::io::AsyncWriteExt;
            let mut stdout = tokio::io::stdout();
            stdout
                .write_all(format!("--- {} ---\n", entry.file_name).as_bytes())
                .await?;
        }
        return extractor.extract_to_stdout(entry).await;
    }

    // Determine the output path based on CLI options
    let output_path = if let Some(ref dir) = cli.extract_dir {
        // Extract to custom directory
        let file_name = if cli.junk_paths {
            // Junk paths: use only the base filename, ignore directory structure
            Path::new(&entry.file_name)
                .file_name()
                .map(|s| s.to_string_lossy().to_string())
                .unwrap_or_else(|| entry.file_name.clone())
        } else {
            // Preserve directory structure from archive
            entry.file_name.clone()
        };
        PathBuf::from(dir).join(&file_name)
    } else {
        // Extract to current directory
        let file_name = if cli.junk_paths {
            Path::new(&entry.file_name)
                .file_name()
                .map(|s| s.to_string_lossy().to_string())
                .unwrap_or_else(|| entry.file_name.clone())
        } else {
            entry.file_name.clone()
        };
        PathBuf::from(&file_name)
    };

    // Handle existing files based on overwrite options
    if output_path.exists() {
        if cli.never_overwrite {
            // -n flag: never overwrite, skip silently (unless quiet)
            if !cli.is_quiet() {
                eprintln!("Skipping: {} (file exists)", entry.file_name);
            }
            return Ok(());
        }

        if !cli.overwrite {
            // Default behavior: skip with suggestion to use -o
            if !cli.is_quiet() {
                eprintln!("Skipping: {} (use -o to overwrite)", entry.file_name);
            }
            return Ok(());
        }
        // -o flag: overwrite without prompting (fall through to extraction)
    }

    // Display extraction progress
    if !cli.is_quiet() {
        println!("  extracting: {}", entry.file_name);
    }

    // Perform the actual extraction
    extractor.extract_to_file(entry, &output_path).await?;

    Ok(())
}

/// Check if a pattern contains glob wildcard characters.
///
/// # Arguments
///
/// * `pattern` - The pattern to check
///
/// # Returns
///
/// Returns `true` if the pattern contains `*` or `?` wildcards.
fn has_glob_chars(pattern: &str) -> bool {
    pattern.contains('*') || pattern.contains('?')
}

/// Simple glob pattern matching supporting `*` and `?` wildcards.
///
/// This is a basic implementation for file matching:
/// - `*` matches zero or more characters
/// - `?` matches exactly one character
///
/// # Arguments
///
/// * `pattern` - The glob pattern to match against
/// * `text` - The text to check for a match
///
/// # Returns
///
/// Returns `true` if the text matches the pattern, `false` otherwise.
///
/// # Examples
///
/// ```ignore
/// assert!(glob_match("*.txt", "readme.txt"));
/// assert!(glob_match("file?.dat", "file1.dat"));
/// assert!(!glob_match("*.txt", "readme.md"));
/// ```
fn glob_match(pattern: &str, text: &str) -> bool {
    let pattern_chars: Vec<char> = pattern.chars().collect();
    let text_chars: Vec<char> = text.chars().collect();

    /// Recursive helper function for glob matching.
    ///
    /// Uses a simple backtracking algorithm to handle `*` wildcards.
    fn do_match(pattern: &[char], text: &[char]) -> bool {
        match (pattern.first(), text.first()) {
            // Both exhausted: match successful
            (None, None) => true,
            // Star matches zero or more characters
            (Some('*'), _) => {
                // Try matching zero characters (skip the star)
                // OR matching one character (keep the star for more)
                do_match(&pattern[1..], text) || (!text.is_empty() && do_match(pattern, &text[1..]))
            }
            // Question mark matches exactly one character
            (Some('?'), Some(_)) => do_match(&pattern[1..], &text[1..]),
            // Literal character match
            (Some(p), Some(t)) if *p == *t => do_match(&pattern[1..], &text[1..]),
            // No match
            _ => false,
        }
    }

    do_match(&pattern_chars, &text_chars)
}

/// Format a byte size into a human-readable string.
///
/// Automatically selects the appropriate unit (bytes, KB, MB, GB)
/// based on the size magnitude.
///
/// # Arguments
///
/// * `size` - The size in bytes to format
///
/// # Returns
///
/// A formatted string with the size and appropriate unit.
///
/// # Examples
///
/// ```ignore
/// assert_eq!(format_size(500), "500 bytes");
/// assert_eq!(format_size(1536), "1.50 KB");
/// assert_eq!(format_size(1048576), "1.00 MB");
/// ```
fn format_size(size: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if size >= GB {
        format!("{:.2} GB", size as f64 / GB as f64)
    } else if size >= MB {
        format!("{:.2} MB", size as f64 / MB as f64)
    } else if size >= KB {
        format!("{:.2} KB", size as f64 / KB as f64)
    } else {
        format!("{} bytes", size)
    }
}