rars-cli 0.12.1

Command-line interface for the rars RAR archive toolkit.
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! Turning a library refusal into one the user can act on.
//!
//! The library knows which formats can do what and says so in its own words:
//! "header encryption is not supported by rar15". The user asked for that with
//! a flag, so the flag is what they need to see, along with a format that would
//! have worked. Both come from the library's own capability data, so the two
//! cannot drift the way a hand-maintained list of messages does.

use crate::cli::TargetFormat;
use crate::error::CliError;
use rars::{ArchiveVersion, Feature, FilterKind, PlanShape, WriterOption};

/// The flag that asks for `option`, as this command's arguments spell it.
///
/// Exhaustive over `WriterOption`, so a new one has to be given a flag here
/// before the CLI will build.
pub(crate) fn flag_for(option: WriterOption, asked: &AskedFilters) -> &'static str {
    match option {
        WriterOption::Feature(Feature::Solid) => "--solid",
        WriterOption::Feature(Feature::HeaderEncryption) => "--encrypt-headers",
        WriterOption::Feature(Feature::QuickOpen) => "--quick-open",
        WriterOption::CompressionLevel => "--level",
        WriterOption::CompressionMethod => "--ppmd",
        WriterOption::DictionarySize => "--dict-size",
        WriterOption::Filter => asked.flag(),
        WriterOption::RecoveryRecord => "--recovery-percent",
        WriterOption::VolumeSize => "--volume-size",
        WriterOption::ArchiveComment => "--comment",
        WriterOption::FileComment => "--file-comment",
        WriterOption::ArchiveMetadata => "--archive-name",
        WriterOption::Password => "--password",
        WriterOption::MemoryLimit => "--memory-limit",
        WriterOption::TempDir => "--temp-dir",
        // WriterOption is non_exhaustive in the library, so this arm cannot be
        // dropped, but every variant above is named deliberately.
        _ => "that option",
    }
}

/// Which filter flag the user typed, so a refusal names it rather than listing
/// every filter flag that exists.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct AskedFilters {
    pub(crate) delta: bool,
    pub(crate) e8: bool,
    pub(crate) e8e9: bool,
    pub(crate) itanium: bool,
    pub(crate) rgb: bool,
    pub(crate) audio: bool,
    pub(crate) arm: bool,
}

impl AskedFilters {
    fn flag(&self) -> &'static str {
        if self.delta {
            "--delta-filter"
        } else if self.e8e9 {
            "--e8e9-filter"
        } else if self.e8 {
            "--e8-filter"
        } else if self.itanium {
            "--itanium-filter"
        } else if self.rgb {
            "--rgb-filter"
        } else if self.audio {
            "--audio-filter"
        } else if self.arm {
            "--arm-filter"
        } else {
            "--auto-filter"
        }
    }

    pub(crate) fn count(&self) -> usize {
        usize::from(self.delta)
            + usize::from(self.e8 || self.e8e9)
            + usize::from(self.itanium)
            + usize::from(self.rgb)
            + usize::from(self.audio)
            + usize::from(self.arm)
    }
}

/// The filter each flag names, so a refusal can say which formats write it.
pub(crate) fn asked_filter_kind(filters: &AskedFilters) -> Option<FilterKind> {
    if filters.itanium {
        Some(FilterKind::Itanium)
    } else if filters.rgb {
        Some(FilterKind::Rgb { width: 3, pos_r: 0 })
    } else if filters.audio {
        Some(FilterKind::Audio { channels: 1 })
    } else if filters.arm {
        Some(FilterKind::Arm)
    } else if filters.e8 || filters.e8e9 {
        Some(FilterKind::E8)
    } else if filters.delta {
        Some(FilterKind::Delta { channels: 1 })
    } else {
        None
    }
}

/// Refuses a filter this format has no way to encode.
///
/// Separate from the option table because every filtering format has filters;
/// what differs is which ones, and the two families are complementary rather
/// than nested, so the suggestion is worth making.
pub(crate) fn reject_unsupported_filter(
    target: ArchiveVersion,
    filters: &AskedFilters,
) -> Result<(), CliError> {
    let Some(kind) = asked_filter_kind(filters) else {
        return Ok(());
    };
    if kind.is_supported_by(target) {
        return Ok(());
    }
    let names = format_list(rars::formats_supporting_filter(kind), target);
    Err(CliError::usage(format!(
        "{} is not supported by --format {target}{names}",
        flag_for(WriterOption::Filter, filters),
    )))
}

/// Refuses more than one explicit filter.
///
/// A member carries one transform, so naming two is asking for something no
/// format can do, whichever formats they are.
pub(crate) fn reject_multiple_filters(filters: &AskedFilters) -> Result<(), CliError> {
    if filters.count() > 1 {
        return Err(CliError::usage(
            "only one filter can be asked for at a time",
        ));
    }
    Ok(())
}

/// Refuses a filter or an engine choice on an archive that is not compressed.
///
/// Both exist to make compression go further, so with `--store` they ask for
/// nothing. Saying so beats writing an archive that quietly ignored the flag.
pub(crate) fn reject_coding_without_compression(
    filters: &AskedFilters,
    auto_filter: bool,
    ppmd: bool,
) -> Result<(), CliError> {
    let flag = if ppmd {
        "--ppmd"
    } else if filters.count() > 0 || auto_filter {
        flag_for(WriterOption::Filter, filters)
    } else {
        return Ok(());
    };
    Err(CliError::usage(format!(
        "{flag} needs something to compress; drop --store or --level 0"
    )))
}

/// Refuses the filter requests a solid archive cannot honour.
///
/// RAR 5 and RAR 7 code solid members as one chain and skip the filter search
/// entirely, so neither a named filter nor `--auto-filter` reaches them; both
/// used to be taken and dropped. RAR 2.9 takes either, search included: its
/// chain measures each candidate against the history so far, which is the only
/// place a filter can be measured once one exists.
pub(crate) fn reject_filter_with_solid(
    target: ArchiveVersion,
    filters: &AskedFilters,
    auto_filter: bool,
    solid: bool,
) -> Result<(), CliError> {
    if !solid || target.family() != rars::ArchiveFamily::Rar50Plus {
        return Ok(());
    }
    if filters.count() == 0 && !auto_filter {
        return Ok(());
    }
    Err(CliError::usage(format!(
        "{} cannot be used with --solid; solid members share one dictionary",
        flag_for(WriterOption::Filter, filters),
    )))
}

/// Formats the user could have asked for instead, in `--format` spelling.
///
/// Computed from the library rather than written down, so a writer that gains a
/// feature does not leave a stale suggestion behind. Only formats `--format`
/// actually accepts are offered.
fn alternatives(option: WriterOption, shape: PlanShape, exclude: ArchiveVersion) -> String {
    format_list(rars::formats_supporting(option, shape), exclude)
}

fn format_list(targets: Vec<ArchiveVersion>, exclude: ArchiveVersion) -> String {
    let names: Vec<_> = targets
        .into_iter()
        .filter(|&target| target != exclude)
        .filter(|&target| TargetFormat::from_archive_version(target).is_some())
        .map(|target| format!("--format {target}"))
        .collect();
    match names.len() {
        0 => String::new(),
        1 => format!("; use {}", names[0]),
        _ => format!(
            "; use {} or {}",
            names[..names.len() - 1].join(", "),
            names[names.len() - 1]
        ),
    }
}

/// Renders a library refusal in the command line's own terms.
///
/// Anything that is not a refusal passes through: those already say what went
/// wrong in terms the user can see, like a missing file or a bad password.
pub(crate) fn map_write_error(
    error: rars::Error,
    shape: PlanShape,
    filters: &AskedFilters,
) -> CliError {
    match error {
        rars::Error::UnsupportedWriterOption {
            target,
            option,
            because,
        } => CliError::usage(format!(
            "{} is not supported by --format {target}{}{}",
            flag_for(option, filters),
            because.map(|why| format!(" ({why})")).unwrap_or_default(),
            alternatives(option, shape, target),
        )),
        other => CliError::general(other.to_string()),
    }
}

/// Refuses anything the chosen format cannot do, before any input is read.
///
/// The writers check this too, but only once they are writing, and by then the
/// command line has read every input it was given. A refusal is worth arriving
/// before the reading, not after it.
pub(crate) fn reject_unsupported(
    target: ArchiveVersion,
    shape: PlanShape,
    filters: &AskedFilters,
    asked: &[(WriterOption, bool)],
) -> Result<(), CliError> {
    for &(option, wanted) in asked {
        if wanted && !rars::supports(target, option, shape) {
            // Several options are refused only once the archive is split, so
            // "not supported by --format rar50" on its own would read as a gap
            // in the format rather than a reason to drop --volume-size.
            let because = (shape.volumes && rars::supports(target, option, without_volumes(shape)))
                .then_some("in a volume set");
            return Err(map_write_error(
                rars::Error::UnsupportedWriterOption {
                    target,
                    option,
                    because,
                },
                shape,
                filters,
            ));
        }
    }
    Ok(())
}

/// The same plan without the split, to ask whether splitting is the reason.
fn without_volumes(shape: PlanShape) -> PlanShape {
    PlanShape::new()
        .compressed(shape.compressed)
        .filtered(shape.filtered)
}

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

    #[test]
    fn flags_filters_and_conflicts_have_actionable_messages() {
        let cases = [
            (
                AskedFilters {
                    delta: true,
                    ..Default::default()
                },
                "--delta-filter",
                FilterKind::Delta { channels: 1 },
            ),
            (
                AskedFilters {
                    e8: true,
                    ..Default::default()
                },
                "--e8-filter",
                FilterKind::E8,
            ),
            (
                AskedFilters {
                    e8e9: true,
                    ..Default::default()
                },
                "--e8e9-filter",
                FilterKind::E8,
            ),
            (
                AskedFilters {
                    itanium: true,
                    ..Default::default()
                },
                "--itanium-filter",
                FilterKind::Itanium,
            ),
            (
                AskedFilters {
                    rgb: true,
                    ..Default::default()
                },
                "--rgb-filter",
                FilterKind::Rgb { width: 3, pos_r: 0 },
            ),
            (
                AskedFilters {
                    audio: true,
                    ..Default::default()
                },
                "--audio-filter",
                FilterKind::Audio { channels: 1 },
            ),
            (
                AskedFilters {
                    arm: true,
                    ..Default::default()
                },
                "--arm-filter",
                FilterKind::Arm,
            ),
        ];
        for (filters, flag, kind) in cases {
            assert_eq!(flag_for(WriterOption::Filter, &filters), flag);
            assert_eq!(asked_filter_kind(&filters), Some(kind));
            assert_eq!(filters.count(), 1);
            assert!(reject_multiple_filters(&filters).is_ok());
            assert!(reject_coding_without_compression(&filters, false, false)
                .unwrap_err()
                .to_string()
                .starts_with(flag));
        }
        let none = AskedFilters::default();
        assert_eq!(flag_for(WriterOption::Filter, &none), "--auto-filter");
        assert_eq!(asked_filter_kind(&none), None);
        assert!(reject_coding_without_compression(&none, false, false).is_ok());
        assert!(reject_coding_without_compression(&none, true, false)
            .unwrap_err()
            .to_string()
            .starts_with("--auto-filter"));
        assert!(reject_coding_without_compression(&none, true, true)
            .unwrap_err()
            .to_string()
            .starts_with("--ppmd"));
        let aliases = AskedFilters {
            e8: true,
            e8e9: true,
            ..Default::default()
        };
        assert_eq!(aliases.count(), 1);
        let multiple = AskedFilters {
            delta: true,
            arm: true,
            ..Default::default()
        };
        assert_eq!(
            reject_multiple_filters(&multiple).unwrap_err().exit_code(),
            2
        );
    }

    #[test]
    fn solid_filter_refusals_depend_on_family_and_request() {
        let none = AskedFilters::default();
        let delta = AskedFilters {
            delta: true,
            ..Default::default()
        };
        assert!(reject_filter_with_solid(ArchiveVersion::Rar50, &delta, false, false).is_ok());
        assert!(reject_filter_with_solid(ArchiveVersion::Rar29, &delta, false, true).is_ok());
        assert!(reject_filter_with_solid(ArchiveVersion::Rar50, &none, false, true).is_ok());
        assert!(
            reject_filter_with_solid(ArchiveVersion::Rar50, &none, true, true)
                .unwrap_err()
                .to_string()
                .starts_with("--auto-filter")
        );
        assert!(
            reject_filter_with_solid(ArchiveVersion::Rar70, &delta, false, true)
                .unwrap_err()
                .to_string()
                .starts_with("--delta-filter")
        );
        assert!(reject_unsupported_filter(ArchiveVersion::Rar50, &none).is_ok());
        assert!(reject_unsupported_filter(ArchiveVersion::Rar50, &delta).is_ok());
    }

    #[test]
    fn refusals_cover_every_current_option_and_preserve_other_errors() {
        let flags = [
            "--solid",
            "--encrypt-headers",
            "--quick-open",
            "--level",
            "--ppmd",
            "--dict-size",
            "--auto-filter",
            "--recovery-percent",
            "--volume-size",
            "--comment",
            "--file-comment",
            "--archive-name",
            "--password",
            "--memory-limit",
            "--temp-dir",
        ];
        for (option, flag) in WriterOption::ALL.into_iter().zip(flags) {
            assert_eq!(flag_for(option, &AskedFilters::default()), flag);
        }
        let error = map_write_error(
            rars::Error::InvalidHeader("broken"),
            PlanShape::new(),
            &AskedFilters::default(),
        );
        assert_eq!(error.exit_code(), 1);
        assert_eq!(
            error.to_string(),
            rars::Error::InvalidHeader("broken").to_string()
        );
        assert_eq!(format_list(vec![], ArchiveVersion::Rar50), "");
        assert_eq!(
            format_list(
                vec![
                    ArchiveVersion::Rar13,
                    ArchiveVersion::Rar50,
                    ArchiveVersion::Rar29
                ],
                ArchiveVersion::Rar50
            ),
            "; use --format rar29"
        );
        let shape = PlanShape::new()
            .compressed(true)
            .filtered(true)
            .volumes(true);
        let error = reject_unsupported(
            ArchiveVersion::Rar50,
            shape,
            &AskedFilters::default(),
            &[
                (WriterOption::FileComment, false),
                (WriterOption::ArchiveMetadata, true),
            ],
        )
        .unwrap_err();
        assert_eq!(error.exit_code(), 2);
        assert!(error.to_string().contains("--archive-name"));
        assert!(error.to_string().contains("in a volume set"), "{error}");
    }

    #[test]
    fn a_refusal_names_the_flag_that_was_typed() {
        let filters = AskedFilters {
            rgb: true,
            ..AskedFilters::default()
        };
        let error = reject_unsupported_filter(ArchiveVersion::Rar50, &filters).unwrap_err();
        assert_eq!(
            error.to_string(),
            "--rgb-filter is not supported by --format rar50; \
             use --format rar29, --format rar30 or --format rar40"
        );
    }

    #[test]
    fn a_refusal_offers_only_formats_the_argument_accepts() {
        let error = reject_unsupported(
            ArchiveVersion::Rar15,
            PlanShape::new(),
            &AskedFilters::default(),
            &[(WriterOption::Feature(Feature::HeaderEncryption), true)],
        )
        .unwrap_err();
        assert_eq!(
            error.to_string(),
            "--encrypt-headers is not supported by --format rar15; \
             use --format rar30, --format rar40, --format rar50 or --format rar70"
        );
        // rar13 exists in the library but --format does not accept it, so it is
        // never suggested.
        assert!(!error.to_string().contains("rar13"));
    }

    #[test]
    fn what_the_format_can_do_is_not_refused() {
        assert!(reject_unsupported(
            ArchiveVersion::Rar50,
            PlanShape::new().compressed(true),
            &AskedFilters::default(),
            &[
                (WriterOption::Feature(Feature::Solid), true),
                (WriterOption::RecoveryRecord, true),
                (WriterOption::ArchiveMetadata, true),
            ],
        )
        .is_ok());
    }
}