zbsdiff-cli 1.6.4

CLI tools for zbsdiff
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! zbsdiff command line tool.
#![forbid(unsafe_code)]
use std::io::prelude::*;
use std::{fs, io, process};

use zbsdiff::{Bsdiff, ParallelScheme};

/// Usage message printed on argument errors.
const USAGE: &str = "Usage: zbsdiff [OPTIONS] <SOURCE> <TARGET> <PATCH>";

/// Help text printed for `-h`/`--help`.
const HELP: &str = "fast and memory saving bsdiff 4.x compatible delta \
                    compressor

Usage: zbsdiff [OPTIONS] <SOURCE> <TARGET> <PATCH>

Arguments:
  <SOURCE>  source file
  <TARGET>  target file
  <PATCH>   patch file

Options:
  -P, --no-parallel             disable parallel searching
  -c, --chunk-size <BYTES>      parallel chunk size in bytes (minimum 256 KiB)
  -b, --buffer-size <BYTES>     delta calculation buffer size in bytes
  -z, --compress-level <LEVEL>  bzip2 compression level (0-9)
  -s, --small-match <BYTES>     skip exact matches no longer than this many \
                    bytes
  -h, --help                    print help
  -V, --version                 print version information";

/// Command line arguments for zbsdiff.
#[derive(Debug)]
struct BsdiffArgs {
    /// Source file path, or `-` for stdin.
    source_path: String,
    /// Target file path, or `-` for stdin.
    target_path: String,
    /// Patch file path, or `-` for stdout.
    patch_path: String,
    /// Whether to use parallel searching.
    parallel: bool,
    /// Parallel chunk size in bytes.
    chunk_size: Option<usize>,
    /// Delta calculation buffer size in bytes.
    buffer_size: Option<usize>,
    /// Bzip2 compression level (0-9).
    compress_level: Option<u32>,
    /// Skip exact matches no longer than this many bytes.
    small_match: Option<usize>
}

/// Action requested by the command line arguments.
#[derive(Debug)]
enum Action {
    /// Run the diff with the parsed arguments.
    Run(BsdiffArgs),
    /// Print help text and exit successfully.
    Help,
    /// Print version information and exit successfully.
    Version
}

fn main() {
    let cli_args: Vec<String> = std::env::args().skip(1).collect();
    let action = match parse_args(cli_args.iter().map(String::as_str)) {
        Ok(action) => action,
        Err(message) => {
            eprintln!(
                "error: {message}\n\n{USAGE}\n\nFor more information, try \
                 '--help'."
            );
            process::exit(2);
        }
    };
    match action {
        Action::Help => {
            println!("{HELP}");
        }
        Action::Version => {
            println!("zbsdiff {}", env!("CARGO_PKG_VERSION"));
        }
        Action::Run(ref parsed) => {
            if let Err(e) = execute(parsed) {
                eprintln!("error: {e}");
                process::exit(1);
            }
        }
    }
}

/// Parses command line arguments.
///
/// # Errors
///
/// Returns a message describing the parse failure.
fn parse_args<'a>(
    args: impl IntoIterator<Item = &'a str>
) -> Result<Action, String> {
    let mut source_path: Option<String> = None;
    let mut target_path: Option<String> = None;
    let mut patch_path: Option<String> = None;
    let mut parallel = true;
    let mut chunk_size: Option<usize> = None;
    let mut buffer_size: Option<usize> = None;
    let mut compress_level: Option<u32> = None;
    let mut small_match: Option<usize> = None;
    let mut help = false;
    let mut version = false;
    let mut end_of_options = false;
    let mut positionals: usize = 0;

    let mut iter = args.into_iter().peekable();
    while let Some(arg) = iter.next() {
        if end_of_options
            || arg == "-"
            || !arg.starts_with('-')
            || arg.is_empty()
        {
            positionals = push_positional(
                arg,
                &mut source_path,
                &mut target_path,
                &mut patch_path,
                positionals
            )?;
            continue;
        }
        if arg == "--" {
            end_of_options = true;
            continue;
        }
        if arg.starts_with("--") {
            let (name, inline_value) = split_long(arg);
            match name {
                "--no-parallel" => {
                    reject_option_value(name, inline_value)?;
                    parallel = false;
                }
                "--chunk-size" => {
                    chunk_size = Some(parse_usize_value(
                        name,
                        inline_value,
                        &mut iter,
                        "<BYTES>"
                    )?);
                }
                "--buffer-size" => {
                    buffer_size = Some(parse_usize_value(
                        name,
                        inline_value,
                        &mut iter,
                        "<BYTES>"
                    )?);
                }
                "--compress-level" => {
                    compress_level = Some(parse_u32_value(
                        name,
                        inline_value,
                        &mut iter,
                        "<LEVEL>"
                    )?);
                }
                "--small-match" => {
                    small_match = Some(parse_usize_value(
                        name,
                        inline_value,
                        &mut iter,
                        "<BYTES>"
                    )?);
                }
                "--help" => {
                    reject_option_value(name, inline_value)?;
                    help = true;
                }
                "--version" => {
                    reject_option_value(name, inline_value)?;
                    version = true;
                }
                _ => {
                    return Err(format!("unexpected argument '{arg}'"));
                }
            }
            continue;
        }
        // Short options: `-x`, `-xvalue`, `-x=value`, or bundles of
        // flag-only options such as `-PV`.
        let body = arg.trim_start_matches('-');
        if body.chars().all(|c| matches!(c, 'P' | 'h' | 'V')) && body.len() > 1
        {
            for flag in body.chars() {
                match flag {
                    'P' => parallel = false,
                    'h' => help = true,
                    'V' => version = true,
                    _ => return Err(format!("unexpected argument '{arg}'"))
                }
            }
            continue;
        }
        let mut chars = body.chars();
        let Some(flag) = chars.next() else {
            return Err(format!("unexpected argument '{arg}'"));
        };
        let rest: String = chars.collect();
        match flag {
            'P' | 'h' | 'V' => {
                if !rest.is_empty() {
                    return Err(format!("unexpected argument '{arg}'"));
                }
                match flag {
                    'P' => parallel = false,
                    'h' => help = true,
                    _ => version = true
                }
            }
            'c' | 'b' | 'z' | 's' => {
                let name = match flag {
                    'c' => "--chunk-size",
                    'b' => "--buffer-size",
                    'z' => "--compress-level",
                    _ => "--small-match"
                };
                let value_name =
                    if flag == 'z' { "<LEVEL>" } else { "<BYTES>" };
                if let Some(inline) = attached_value(&rest) {
                    if flag == 'z' {
                        compress_level =
                            Some(parse_u32_valued(name, inline, value_name)?);
                    } else {
                        let parsed =
                            parse_usize_valued(name, inline, value_name)?;
                        match flag {
                            'c' => chunk_size = Some(parsed),
                            'b' => buffer_size = Some(parsed),
                            _ => small_match = Some(parsed)
                        }
                    }
                } else {
                    let raw = iter.next().ok_or_else(|| {
                        format!(
                            "a value is required for '-{flag} {value_name} \
                             [{name} {value_name}]'"
                        )
                    })?;
                    if flag == 'z' {
                        compress_level =
                            Some(parse_u32_valued(name, raw, value_name)?);
                    } else {
                        let parsed = parse_usize_valued(name, raw, value_name)?;
                        match flag {
                            'c' => chunk_size = Some(parsed),
                            'b' => buffer_size = Some(parsed),
                            _ => small_match = Some(parsed)
                        }
                    }
                }
            }
            _ => {
                return Err(format!("unexpected argument '{arg}'"));
            }
        }
    }

    if help {
        return Ok(Action::Help);
    }
    if version {
        return Ok(Action::Version);
    }
    if positionals != 3 {
        return Err("expected <SOURCE> <TARGET> <PATCH>".to_string());
    }
    let (Some(source_path), Some(target_path), Some(patch_path)) =
        (source_path, target_path, patch_path)
    else {
        return Err("expected <SOURCE> <TARGET> <PATCH>".to_string());
    };
    Ok(Action::Run(BsdiffArgs {
        source_path,
        target_path,
        patch_path,
        parallel,
        chunk_size,
        buffer_size,
        compress_level,
        small_match
    }))
}

/// Pushes a positional argument into the first empty slot.
///
/// # Errors
///
/// Returns a message if more than three positional arguments are given.
fn push_positional(
    arg: &str,
    source_path: &mut Option<String>,
    target_path: &mut Option<String>,
    patch_path: &mut Option<String>,
    positionals: usize
) -> Result<usize, String> {
    match positionals {
        0 => *source_path = Some(arg.to_string()),
        1 => *target_path = Some(arg.to_string()),
        2 => *patch_path = Some(arg.to_string()),
        _ => return Err(format!("unexpected argument '{arg}'"))
    }
    Ok(positionals + 1)
}

/// Splits a long option into its name and optional inline `=value`.
fn split_long(arg: &str) -> (&str, Option<&str>) {
    match arg.split_once('=') {
        Some((name, value)) => (name, Some(value)),
        None => (arg, None)
    }
}

/// Extracts the value attached to a short option (`-c123`, `-c=123`).
fn attached_value(rest: &str) -> Option<&str> {
    if rest.is_empty() {
        None
    } else if let Some(stripped) = rest.strip_prefix('=') {
        Some(stripped)
    } else {
        Some(rest)
    }
}

/// Rejects `--flag=value` usage for flag-only options.
///
/// # Errors
///
/// Returns a message if an inline value was supplied.
fn reject_option_value(
    name: &str,
    inline_value: Option<&str>
) -> Result<(), String> {
    if inline_value.is_some() {
        return Err(format!("option '{name}' does not take a value"));
    }
    Ok(())
}

/// Parses a `usize`-valued long option.
///
/// # Errors
///
/// Returns a message if the value is missing or not a non-negative integer.
fn parse_usize_value<'a>(
    name: &str,
    inline_value: Option<&'a str>,
    iter: &mut impl Iterator<Item = &'a str>,
    value_name: &str
) -> Result<usize, String> {
    let raw = match inline_value {
        Some(value) => value,
        None => iter.next().ok_or_else(|| {
            format!("a value is required for '{name} {value_name}'")
        })?
    };
    parse_usize_valued(name, raw, value_name)
}

/// Parses a `u32`-valued long option.
///
/// # Errors
///
/// Returns a message if the value is missing or not a non-negative integer.
fn parse_u32_value<'a>(
    name: &str,
    inline_value: Option<&'a str>,
    iter: &mut impl Iterator<Item = &'a str>,
    value_name: &str
) -> Result<u32, String> {
    let raw = match inline_value {
        Some(value) => value,
        None => iter.next().ok_or_else(|| {
            format!("a value is required for '{name} {value_name}'")
        })?
    };
    parse_u32_valued(name, raw, value_name)
}

/// Parses a raw `usize` value.
///
/// # Errors
///
/// Returns a message if the value is not a non-negative integer.
fn parse_usize_valued(
    name: &str,
    raw: &str,
    value_name: &str
) -> Result<usize, String> {
    raw.parse::<usize>().map_err(|_| {
        format!(
            "invalid value '{raw}' for '{name} {value_name}': expected a \
             non-negative integer"
        )
    })
}

/// Parses a raw `u32` value.
///
/// # Errors
///
/// Returns a message if the value is not a non-negative integer.
fn parse_u32_valued(
    name: &str,
    raw: &str,
    value_name: &str
) -> Result<u32, String> {
    raw.parse::<u32>().map_err(|_| {
        format!(
            "invalid value '{raw}' for '{name} {value_name}': expected a \
             non-negative integer"
        )
    })
}

/// Executes the bsdiff process.
///
/// # Errors
///
/// Returns error if validation fails or I/O operations fail.
fn execute(args: &BsdiffArgs) -> io::Result<()> {
    // validate command line arguments
    if !matches!(args.compress_level, Some(0..=9) | None) {
        return Err(io::Error::other("compression level must be in range 0-9"));
    }

    // setup input/output
    if args.source_path == "-" && args.target_path == "-" {
        return Err(io::Error::other("source and target are both from stdin"));
    }
    let source = input_bytes(&args.source_path)?;
    let target = input_bytes(&args.target_path)?;
    let patch = output_writer(&args.patch_path)?;

    // setup delta compressor
    let mut bsdiff = Bsdiff::new(source.as_slice(), target.as_slice());
    if !args.parallel {
        if args.chunk_size.is_some() {
            return Err(io::Error::other(
                "--chunk-size cannot be used with --no-parallel"
            ));
        }
        bsdiff = bsdiff.parallel_scheme(ParallelScheme::Never);
    } else if let Some(mut chunk_size) = args.chunk_size {
        chunk_size = Ord::max(chunk_size, 256 * 1024);
        bsdiff = bsdiff.parallel_scheme(ParallelScheme::ChunkSize(chunk_size));
    } else {
        bsdiff = bsdiff.parallel_scheme(ParallelScheme::Auto);
    }
    if let Some(compress_level) = args.compress_level {
        bsdiff = bsdiff.compression_level(compress_level);
    }
    if let Some(buffer_size) = args.buffer_size {
        bsdiff = bsdiff.buffer_size(buffer_size);
    }
    if let Some(small_match) = args.small_match {
        bsdiff = bsdiff.small_match(small_match);
    }

    // execute delta compressor
    bsdiff.compare(patch)?;
    Ok(())
}

/// Reads bytes from a file or stdin.
///
/// # Errors
///
/// Returns error if the file cannot be read.
fn input_bytes(path: &str) -> io::Result<Vec<u8>> {
    let mut data;
    if path == "-" {
        data = Vec::new();
        io::stdin().read_to_end(&mut data)?;
    } else {
        data = fs::read(path)?;
    }
    Ok(data)
}

/// Creates an output writer for a file or stdout.
///
/// # Errors
///
/// Returns error if the file cannot be created.
fn output_writer(path: &str) -> io::Result<Box<dyn Write>> {
    if path == "-" {
        Ok(Box::new(io::stdout()))
    } else {
        Ok(Box::new(fs::File::create(path)?))
    }
}