uu_tail 0.8.0

tail ~ (uutils) display the last lines of input
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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
// This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

// spell-checker:ignore (ToDO) kqueue Signum

use crate::paths::Input;
use crate::{Quotable, parse, platform};
use clap::{Arg, ArgAction, ArgMatches, Command, value_parser};
use same_file::Handle;
use std::ffi::OsString;
use std::io::IsTerminal;
use std::time::Duration;
use uucore::error::{UResult, USimpleError, UUsageError};
use uucore::parser::parse_signed_num::{SignPrefix, parse_signed_num_max};
use uucore::parser::parse_size::ParseSizeError;
use uucore::parser::parse_time;
use uucore::parser::shortcut_value_parser::ShortcutValueParser;
use uucore::translate;
use uucore::{format_usage, show_warning};

pub mod options {
    pub mod verbosity {
        pub const QUIET: &str = "quiet";
        pub const VERBOSE: &str = "verbose";
    }
    pub const BYTES: &str = "bytes";
    pub const FOLLOW: &str = "follow";
    pub const LINES: &str = "lines";
    pub const PID: &str = "pid";
    pub const SLEEP_INT: &str = "sleep-interval";
    pub const ZERO_TERM: &str = "zero-terminated";
    pub const DISABLE_INOTIFY_TERM: &str = "-disable-inotify"; // NOTE: three hyphens is correct
    pub const USE_POLLING: &str = "use-polling";
    pub const RETRY: &str = "retry";
    pub const FOLLOW_RETRY: &str = "F";
    pub const MAX_UNCHANGED_STATS: &str = "max-unchanged-stats";
    pub const ARG_FILES: &str = "files";
    pub const PRESUME_INPUT_PIPE: &str = "-presume-input-pipe"; // NOTE: three hyphens is correct
    pub const DEBUG: &str = "debug";
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Signum {
    Negative(u64),
    Positive(u64),
    PlusZero,
    MinusZero,
}

#[derive(Debug, PartialEq, Eq)]
pub enum FilterMode {
    Bytes(Signum),

    /// Mode for lines delimited by delimiter as u8
    Lines(Signum, u8),
}

impl FilterMode {
    fn from_obsolete_args(args: &parse::ObsoleteArgs) -> Self {
        let signum = if args.plus {
            Signum::Positive(args.num)
        } else {
            Signum::Negative(args.num)
        };
        if args.lines {
            Self::Lines(signum, b'\n')
        } else {
            Self::Bytes(signum)
        }
    }

    fn from(matches: &ArgMatches) -> UResult<Self> {
        let zero_term = matches.get_flag(options::ZERO_TERM);
        let mode = if let Some(arg) = matches.get_one::<String>(options::BYTES) {
            match parse_num(arg) {
                Ok(signum) => Self::Bytes(signum),
                Err(e) => {
                    return Err(USimpleError::new(
                        1,
                        translate!("tail-error-invalid-number-of-bytes", "arg" => e.to_string()),
                    ));
                }
            }
        } else if let Some(arg) = matches.get_one::<String>(options::LINES) {
            match parse_num(arg) {
                Ok(signum) => {
                    let delimiter = if zero_term { 0 } else { b'\n' };
                    Self::Lines(signum, delimiter)
                }
                Err(_) => {
                    return Err(USimpleError::new(
                        1,
                        translate!("tail-error-invalid-number-of-lines", "arg" => arg.quote()),
                    ));
                }
            }
        } else if zero_term {
            Self::default_zero()
        } else {
            Self::default()
        };

        Ok(mode)
    }

    fn default_zero() -> Self {
        Self::Lines(Signum::Negative(10), 0)
    }
}

impl Default for FilterMode {
    fn default() -> Self {
        Self::Lines(Signum::Negative(10), b'\n')
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum FollowMode {
    Descriptor,
    Name,
}

#[derive(Debug)]
pub enum VerificationResult {
    Ok,
    CannotFollowStdinByName,
    NoOutput,
}

#[derive(Debug)]
pub struct Settings {
    pub follow: Option<FollowMode>,
    pub max_unchanged_stats: u32,
    pub mode: FilterMode,
    pub pid: platform::Pid,
    pub retry: bool,
    pub sleep_sec: Duration,
    pub use_polling: bool,
    pub verbose: bool,
    pub presume_input_pipe: bool,
    pub debug: bool,
    /// `FILE(s)` positional arguments
    pub inputs: Vec<Input>,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            max_unchanged_stats: 5,
            sleep_sec: Duration::from_secs_f32(1.0),
            follow: Option::default(),
            mode: FilterMode::default(),
            pid: Default::default(),
            retry: Default::default(),
            use_polling: Default::default(),
            verbose: Default::default(),
            presume_input_pipe: Default::default(),
            debug: Default::default(),
            inputs: Vec::default(),
        }
    }
}

impl Settings {
    pub fn from_obsolete_args(args: &parse::ObsoleteArgs, name: Option<&OsString>) -> Self {
        let mut settings = Self::default();
        if args.follow {
            settings.follow = if name.is_some() {
                Some(FollowMode::Name)
            } else {
                Some(FollowMode::Descriptor)
            };
        }
        settings.mode = FilterMode::from_obsolete_args(args);
        let input = if let Some(name) = name {
            Input::from(name)
        } else {
            Input::default()
        };
        settings.inputs.push(input);
        settings
    }

    pub fn from(matches: &ArgMatches) -> UResult<Self> {
        // We're parsing --follow, -F and --retry under the following conditions:
        // * -F sets --retry and --follow=name
        // * plain --follow or short -f is the same like specifying --follow=descriptor
        // * All these options and flags can occur multiple times as command line arguments
        let follow_retry = matches.get_flag(options::FOLLOW_RETRY);
        // We don't need to check for occurrences of --retry if -F was specified which already sets
        // retry
        let retry = follow_retry || matches.get_flag(options::RETRY);
        let follow = match (
            follow_retry,
            matches
                .get_one::<String>(options::FOLLOW)
                .map(String::as_str),
        ) {
            // -F and --follow if -F is specified after --follow. We don't need to care about the
            // value of --follow.
            (true, Some(_))
                // It's ok to use `index_of` instead of `indices_of` since -F and  --follow
                // overwrite themselves (not only the value but also the index).
                if matches.index_of(options::FOLLOW_RETRY) > matches.index_of(options::FOLLOW) =>
            {
                Some(FollowMode::Name)
            }
            // * -F and --follow=name if --follow=name is specified after -F
            // * No occurrences of -F but --follow=name
            // * -F and no occurrences of --follow
            (_, Some("name")) | (true, None) => Some(FollowMode::Name),
            // * -F and --follow=descriptor (or plain --follow, -f) if --follow=descriptor is
            // specified after -F
            // * No occurrences of -F but --follow=descriptor, --follow, -f
            (_, Some(_)) => Some(FollowMode::Descriptor),
            // The default for no occurrences of -F or --follow
            (false, None) => None,
        };

        let mut settings: Self = Self {
            follow,
            retry,
            use_polling: matches.get_flag(options::USE_POLLING),
            mode: FilterMode::from(matches)?,
            verbose: matches.get_flag(options::verbosity::VERBOSE),
            presume_input_pipe: matches.get_flag(options::PRESUME_INPUT_PIPE),
            debug: matches.get_flag(options::DEBUG),
            ..Default::default()
        };

        if let Some(source) = matches.get_one::<String>(options::SLEEP_INT) {
            settings.sleep_sec = parse_time::from_str(source, false).map_err(|_| {
                UUsageError::new(
                    1,
                    translate!("tail-error-invalid-number-of-seconds", "source" => source.clone()),
                )
            })?;
        }

        if let Some(s) = matches.get_one::<String>(options::MAX_UNCHANGED_STATS) {
            settings.max_unchanged_stats = match s.parse::<u32>() {
                Ok(s) => s,
                Err(_) => {
                    return Err(UUsageError::new(
                        1,
                        translate!("tail-error-invalid-max-unchanged-stats", "value" => s.quote()),
                    ));
                }
            }
        }

        if let Some(pid_str) = matches.get_one::<String>(options::PID) {
            match pid_str.parse() {
                Ok(pid) => {
                    // NOTE: on unix platform::Pid is i32, on windows platform::Pid is u32
                    #[cfg(unix)]
                    if pid < 0 {
                        // NOTE: tail only accepts an unsigned pid
                        return Err(USimpleError::new(
                            1,
                            translate!("tail-error-invalid-pid", "pid" => pid_str.quote()),
                        ));
                    }

                    settings.pid = pid;
                }
                Err(e) => {
                    return Err(USimpleError::new(
                        1,
                        translate!("tail-error-invalid-pid-with-error", "pid" => pid_str.quote(), "error" => e),
                    ));
                }
            }
        }

        settings.inputs = matches
            .get_many::<OsString>(options::ARG_FILES)
            .map_or_else(|| vec![Input::default()], |v| v.map(Input::from).collect());

        settings.verbose = (matches.get_flag(options::verbosity::VERBOSE)
            || settings.inputs.len() > 1)
            && !matches.get_flag(options::verbosity::QUIET);

        Ok(settings)
    }

    pub fn has_only_stdin(&self) -> bool {
        self.inputs.iter().all(Input::is_stdin)
    }

    pub fn has_stdin(&self) -> bool {
        self.inputs.iter().any(Input::is_stdin)
    }

    pub fn num_inputs(&self) -> usize {
        self.inputs.len()
    }

    /// Check [`Settings`] for problematic configurations of tail originating from user provided
    /// command line arguments and print appropriate warnings.
    pub fn check_warnings(&self) {
        if self.retry {
            if self.follow.is_none() {
                show_warning!("{}", translate!("tail-warning-retry-ignored"));
            } else if self.follow == Some(FollowMode::Descriptor) {
                show_warning!("{}", translate!("tail-warning-retry-only-effective"));
            }
        }

        if self.pid != 0 {
            if self.follow.is_none() {
                show_warning!("{}", translate!("tail-warning-pid-ignored"));
            } else if !platform::supports_pid_checks(self.pid) {
                show_warning!("{}", translate!("tail-warning-pid-not-supported"));
            }
        }

        // This warning originates from gnu's tail implementation of the equivalent warning. If the
        // user wants to follow stdin, but tail is blocking indefinitely anyways, because of stdin
        // as `tty` (but no otherwise blocking stdin), then we print a warning that `--follow`
        // cannot be applied under these circumstances and is therefore ineffective.
        if self.follow.is_some() && self.has_stdin() {
            let blocking_stdin = self.pid == 0
                && self.follow == Some(FollowMode::Descriptor)
                && self.num_inputs() == 1
                && Handle::stdin().is_ok_and(|handle| {
                    handle
                        .as_file()
                        .metadata()
                        .is_ok_and(|meta| !meta.is_file())
                });

            if !blocking_stdin && std::io::stdin().is_terminal() {
                show_warning!("{}", translate!("tail-warning-following-stdin-ineffective"));
            }
        }
    }

    /// Verify [`Settings`] and try to find unsolvable misconfigurations of tail originating from
    /// user provided command line arguments. In contrast to [`Settings::check_warnings`] these
    /// misconfigurations usually lead to the immediate exit or abortion of the running `tail`
    /// process.
    pub fn verify(&self) -> VerificationResult {
        // Mimic GNU's tail for `tail -F`
        if self.inputs.iter().any(Input::is_stdin) && self.follow == Some(FollowMode::Name) {
            return VerificationResult::CannotFollowStdinByName;
        }

        // Mimic GNU's tail for -[nc]0 without -f and exit immediately
        if self.follow.is_none()
            && matches!(
                self.mode,
                FilterMode::Lines(Signum::MinusZero, _) | FilterMode::Bytes(Signum::MinusZero)
            )
        {
            return VerificationResult::NoOutput;
        }

        VerificationResult::Ok
    }
}

pub fn parse_obsolete(arg: &OsString, input: Option<&OsString>) -> UResult<Option<Settings>> {
    match parse::parse_obsolete(arg) {
        Some(Ok(args)) => Ok(Some(Settings::from_obsolete_args(&args, input))),
        None => Ok(None),
        Some(Err(e)) => {
            Err(USimpleError::new(
                1,
                match e {
                    // this ensures compatibility to GNU's error message (as tested in misc/tail)
                    parse::ParseError::Context => {
                        translate!(
                            "tail-error-option-used-in-invalid-context",
                            "option" => arg.to_string_lossy().chars().nth(1).unwrap_or_default(),
                        )
                    }
                    parse::ParseError::InvalidEncoding => {
                        translate!("tail-error-bad-argument-encoding", "arg" => arg.quote())
                    }
                },
            ))
        }
    }
}

fn parse_num(src: &str) -> Result<Signum, ParseSizeError> {
    let result = parse_signed_num_max(src)?;
    // tail: '+' means "starting from line/byte N", default/'-' means "last N"
    let is_plus = result.sign == Some(SignPrefix::Plus);

    match (result.value, is_plus) {
        (0, true) => Ok(Signum::PlusZero),
        (0, false) => Ok(Signum::MinusZero),
        (n, true) => Ok(Signum::Positive(n)),
        (n, false) => Ok(Signum::Negative(n)),
    }
}

pub fn parse_args(args: impl uucore::Args) -> UResult<Settings> {
    let args_vec: Vec<OsString> = args.collect();
    let clap_args = uu_app().try_get_matches_from(args_vec.clone());
    let clap_result = match clap_args {
        Ok(matches) => Ok(Settings::from(&matches)?),
        Err(err) => Err(err.into()),
    };

    // clap isn't able to handle obsolete syntax.
    // therefore, we want to check further for obsolete arguments.
    // argv[0] is always present, argv[1] might be obsolete arguments
    // argv[2] might contain an input file, argv[3] isn't allowed in obsolete mode
    if args_vec.len() != 2 && args_vec.len() != 3 {
        return clap_result;
    }

    // At this point, there are a few possible cases:
    //
    //    1. clap has succeeded and the arguments would be invalid for the obsolete syntax.
    //    2. The case of `tail -c 5` is ambiguous. clap parses this as `tail -c5`,
    //       but it could also be interpreted as valid obsolete syntax (tail -c on file '5').
    //       GNU chooses to interpret this as `tail -c5`, like clap.
    //    3. `tail -f foo` is also ambiguous, but has the same effect in both cases. We can safely
    //        use the clap result here.
    //    4. clap succeeded for obsolete arguments starting with '+', but misinterprets them as
    //       input files (e.g. 'tail +f').
    //    5. clap failed because of unknown flags, but possibly valid obsolete arguments
    //        (e.g. tail -l; tail -10c).
    //
    // In cases 4 & 5, we want to try parsing the obsolete arguments, which corresponds to
    // checking whether clap succeeded or the first argument starts with '+'.
    let possible_obsolete_args = &args_vec[1];
    if clap_result.is_ok() && !possible_obsolete_args.to_string_lossy().starts_with('+') {
        return clap_result;
    }
    match parse_obsolete(possible_obsolete_args, args_vec.get(2))? {
        Some(settings) => Ok(settings),
        None => clap_result,
    }
}

pub fn uu_app() -> Command {
    #[cfg(target_os = "linux")]
    let polling_help = translate!("tail-help-polling-linux");
    #[cfg(all(unix, not(target_os = "linux")))]
    let polling_help = translate!("tail-help-polling-unix");
    #[cfg(target_os = "windows")]
    let polling_help = translate!("tail-help-polling-windows");
    #[cfg(not(any(unix, target_os = "windows")))]
    let polling_help = translate!("tail-help-polling-unix");

    Command::new("tail")
        .version(uucore::crate_version!())
        .help_template(uucore::localized_help_template("tail"))
        .about(translate!("tail-about"))
        .override_usage(format_usage(&translate!("tail-usage")))
        .infer_long_args(true)
        .arg(
            Arg::new(options::BYTES)
                .short('c')
                .long(options::BYTES)
                .allow_hyphen_values(true)
                .overrides_with_all([options::BYTES, options::LINES])
                .help(translate!("tail-help-bytes")),
        )
        .arg(
            Arg::new(options::FOLLOW)
                .short('f')
                .long(options::FOLLOW)
                .default_missing_value("descriptor")
                .num_args(0..=1)
                .require_equals(true)
                .value_parser(ShortcutValueParser::new(["descriptor", "name"]))
                .overrides_with(options::FOLLOW)
                .help(translate!("tail-help-follow")),
        )
        .arg(
            Arg::new(options::LINES)
                .short('n')
                .long(options::LINES)
                .allow_hyphen_values(true)
                .overrides_with_all([options::BYTES, options::LINES])
                .help(translate!("tail-help-lines")),
        )
        .arg(
            Arg::new(options::PID)
                .long(options::PID)
                .value_name("PID")
                .help(translate!("tail-help-pid"))
                .overrides_with(options::PID),
        )
        .arg(
            Arg::new(options::verbosity::QUIET)
                .short('q')
                .long(options::verbosity::QUIET)
                .visible_alias("silent")
                .overrides_with_all([options::verbosity::QUIET, options::verbosity::VERBOSE])
                .help(translate!("tail-help-quiet"))
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new(options::SLEEP_INT)
                .short('s')
                .value_name("N")
                .long(options::SLEEP_INT)
                .help(translate!("tail-help-sleep-interval")),
        )
        .arg(
            Arg::new(options::MAX_UNCHANGED_STATS)
                .value_name("N")
                .long(options::MAX_UNCHANGED_STATS)
                .help(translate!("tail-help-max-unchanged-stats")),
        )
        .arg(
            Arg::new(options::verbosity::VERBOSE)
                .short('v')
                .long(options::verbosity::VERBOSE)
                .overrides_with_all([options::verbosity::QUIET, options::verbosity::VERBOSE])
                .help(translate!("tail-help-verbose"))
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new(options::ZERO_TERM)
                .short('z')
                .long(options::ZERO_TERM)
                .help(translate!("tail-help-zero-terminated"))
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new(options::USE_POLLING)
                .alias(options::DISABLE_INOTIFY_TERM) // NOTE: Used by GNU's test suite
                .alias("dis") // NOTE: Used by GNU's test suite
                .long(options::USE_POLLING)
                .help(polling_help)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new(options::RETRY)
                .long(options::RETRY)
                .help(translate!("tail-help-retry"))
                .overrides_with(options::RETRY)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new(options::FOLLOW_RETRY)
                .short('F')
                .help(translate!("tail-help-follow-retry"))
                .overrides_with(options::FOLLOW_RETRY)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new(options::DEBUG)
                .long(options::DEBUG)
                .help(translate!("tail-help-debug"))
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new(options::PRESUME_INPUT_PIPE)
                .long("presume-input-pipe")
                .alias(options::PRESUME_INPUT_PIPE)
                .hide(true)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new(options::ARG_FILES)
                .action(ArgAction::Append)
                .num_args(1..)
                .value_parser(value_parser!(OsString))
                .value_hint(clap::ValueHint::FilePath),
        )
}

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

    use crate::parse::ObsoleteArgs;

    use super::*;

    #[test]
    fn test_parse_num_when_sign_is_given() {
        let result = parse_num("+0");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Signum::PlusZero);

        let result = parse_num("+1");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Signum::Positive(1));

        let result = parse_num("-0");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Signum::MinusZero);

        let result = parse_num("-1");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Signum::Negative(1));
    }

    #[test]
    fn test_parse_num_when_no_sign_is_given() {
        let result = parse_num("0");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Signum::MinusZero);

        let result = parse_num("1");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Signum::Negative(1));
    }

    #[test]
    fn test_parse_obsolete_settings_f() {
        let args = ObsoleteArgs {
            follow: true,
            ..Default::default()
        };
        let result = Settings::from_obsolete_args(&args, None);
        assert_eq!(result.follow, Some(FollowMode::Descriptor));

        let result = Settings::from_obsolete_args(&args, Some(&"file".into()));
        assert_eq!(result.follow, Some(FollowMode::Name));
    }

    #[rstest]
    #[case::default(vec![], None, false)]
    #[case::retry(vec!["--retry"], None, true)]
    #[case::multiple_retry(vec!["--retry", "--retry"], None, true)]
    #[case::follow_long(vec!["--follow"], Some(FollowMode::Descriptor), false)]
    #[case::follow_short(vec!["-f"], Some(FollowMode::Descriptor), false)]
    #[case::follow_long_with_retry(vec!["--follow", "--retry"], Some(FollowMode::Descriptor), true)]
    #[case::follow_short_with_retry(vec!["-f", "--retry"], Some(FollowMode::Descriptor), true)]
    #[case::follow_overwrites_previous_selection_1(vec!["--follow=name", "--follow=descriptor"], Some(FollowMode::Descriptor), false)]
    #[case::follow_overwrites_previous_selection_2(vec!["--follow=descriptor", "--follow=name"], Some(FollowMode::Name), false)]
    #[case::big_f(vec!["-F"], Some(FollowMode::Name), true)]
    #[case::multiple_big_f(vec!["-F", "-F"], Some(FollowMode::Name), true)]
    #[case::big_f_with_retry_then_does_not_change(vec!["-F", "--retry"], Some(FollowMode::Name), true)]
    #[case::big_f_with_follow_descriptor_then_change(vec!["-F", "--follow=descriptor"], Some(FollowMode::Descriptor), true)]
    #[case::multiple_big_f_with_follow_descriptor_then_no_change(vec!["-F", "--follow=descriptor", "-F"], Some(FollowMode::Name), true)]
    #[case::big_f_with_follow_short_then_change(vec!["-F", "-f"], Some(FollowMode::Descriptor), true)]
    #[case::follow_descriptor_with_big_f_then_change(vec!["--follow=descriptor", "-F"], Some(FollowMode::Name), true)]
    #[case::follow_short_with_big_f_then_change(vec!["-f", "-F"], Some(FollowMode::Name), true)]
    #[case::big_f_with_follow_name_then_not_change(vec!["-F", "--follow=name"], Some(FollowMode::Name), true)]
    #[case::follow_name_with_big_f_then_not_change(vec!["--follow=name", "-F"], Some(FollowMode::Name), true)]
    #[case::big_f_with_multiple_long_follow(vec!["--follow=name", "-F", "--follow=descriptor"], Some(FollowMode::Descriptor), true)]
    #[case::big_f_with_multiple_long_follow_name(vec!["--follow=name", "-F", "--follow=name"], Some(FollowMode::Name), true)]
    #[case::big_f_with_multiple_short_follow(vec!["-f", "-F", "-f"], Some(FollowMode::Descriptor), true)]
    #[case::multiple_big_f_with_multiple_short_follow(vec!["-f", "-F", "-f", "-F"], Some(FollowMode::Name), true)]
    fn test_parse_settings_follow_mode_and_retry(
        #[case] args: Vec<&str>,
        #[case] expected_follow_mode: Option<FollowMode>,
        #[case] expected_retry: bool,
    ) {
        let settings =
            Settings::from(&uu_app().no_binary_name(true).get_matches_from(args)).unwrap();
        assert_eq!(settings.follow, expected_follow_mode);
        assert_eq!(settings.retry, expected_retry);
    }
}