ci-cargo 0.2.1

Continuous integration using cargo for Clippy and tests for all possible features.
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
use super::{
    args::{CheckClippyTargets, Ignored, Target, TestTargets},
    manifest,
};
use std::{
    collections::HashSet,
    io::{Error, StderrLock, Write as _},
    path::{Path, PathBuf},
    process::{Command, Stdio},
};
/// Error returned from [`Toolchain::get_version`].
pub(crate) enum ToolchainErr {
    /// [`Command::output`] erred with the contained `Error` for the contained `Command`.
    CommandFail(Command, Error),
    /// [`Command::output`] was successful for the contained `Command`, but it didn't return a status code.
    ///
    /// The contained `String` is the potentially empty content written to `stderr`.
    CommandNoStatus(Command, String),
    /// [`Command::output`] was successful for the contained `Command`, but it returned an error status code
    /// represented by the contained `i32`.
    ///
    /// The contained `String` is the potentially empty content written to `stderr`.
    CommandErr(Command, String, i32),
    /// [`Command::output`] was successful for the contained `Command`, but the data it wrote to `stdout` was not
    /// valid UTF-8.
    StdoutNotUtf8(Command),
    /// [`Command::output`] was successful for the contained `Command`, but the data it wrote to `stderr` was not
    /// valid UTF-8.
    StderrNotUtf8(Command),
    /// [`Command::output`] was successful for the contained `Command`, but the non-empty data it wrote to
    /// `stdout` was unexpected.
    ///
    /// The contained `String` is the unexpected data.
    UnexpectedOutput(Command, String),
    /// The parsed MSRV value is newer than `stable` or the default toolchain.
    MsrvTooHigh,
    /// Error when `cargo +<MSRV> -V` returns a version not compatible with the defined MSRV.
    ///
    /// The contained `Version` is the installed MSRV.
    MsrvNotCompatibleWithInstalledMsrv(Version),
}
impl ToolchainErr {
    /// Writes `self` to `stderr`.
    pub(crate) fn write(self, mut stderr: StderrLock<'_>) -> Result<(), Error> {
        match self {
            Self::CommandFail(cmd, err) => stderr
                .write_all(cmd.get_program().to_string_lossy().as_bytes())
                .and_then(|()| {
                    cmd.get_args().try_fold((), |(), arg| {
                        stderr.write_all(b" ").and_then(|()| {
                            stderr
                                .write_all(arg.to_string_lossy().as_bytes())
                        })
                    }).and_then(|()| writeln!(stderr, " erred: {err}"))
                }),
            Self::CommandNoStatus(cmd, err) => stderr
                .write_all(cmd.get_program().to_string_lossy().as_bytes())
                .and_then(|()| {
                    cmd.get_args().try_fold((), |(), arg| {
                        stderr.write_all(b" ").and_then(|()| {
                            stderr
                                .write_all(arg.to_string_lossy().as_bytes())
                        })
                    }).and_then(|()| {
                        if err.is_empty() {
                            writeln!(stderr, " did not return a status code and didn't write anything to stderr.")
                        } else {
                            writeln!(stderr, " did not return a status code but wrote the following to stderr: {err}")
                        }
                    })
                }),
            Self::CommandErr(cmd, err, status) => stderr
                .write_all(cmd.get_program().to_string_lossy().as_bytes())
                .and_then(|()| {
                    cmd.get_args().try_fold((), |(), arg| {
                        stderr.write_all(b" ").and_then(|()| {
                            stderr
                                .write_all(arg.to_string_lossy().as_bytes())
                        })
                    }).and_then(|()| {
                        if err.is_empty() {
                            writeln!(stderr, " returned status code {status} but didn't write anything to stderr.")
                        } else {
                            writeln!(stderr, " returned status code {status} and wrote the following to stderr: {err}")
                        }
                    })
                }),
            Self::StdoutNotUtf8(cmd) => stderr
                .write_all(cmd.get_program().to_string_lossy().as_bytes())
                .and_then(|()| {
                    cmd.get_args().try_fold((), |(), arg| {
                        stderr.write_all(b" ").and_then(|()| {
                            stderr
                                .write_all(arg.to_string_lossy().as_bytes())
                        })
                    }).and_then(|()| writeln!(stderr, " wrote invalid UTF-8 to stdout."))
                }),
            Self::StderrNotUtf8(cmd) => stderr
                .write_all(cmd.get_program().to_string_lossy().as_bytes())
                .and_then(|()| {
                    cmd.get_args().try_fold((), |(), arg| {
                        stderr.write_all(b" ").and_then(|()| {
                            stderr
                                .write_all(arg.to_string_lossy().as_bytes())
                        })
                    }).and_then(|()| writeln!(stderr, " wrote invalid UTF-8 to stderr."))
                }),
            Self::UnexpectedOutput(cmd, output) => stderr
                .write_all(cmd.get_program().to_string_lossy().as_bytes())
                .and_then(|()| {
                    cmd.get_args().try_fold((), |(), arg| {
                        stderr.write_all(b" ").and_then(|()| {
                            stderr
                                .write_all(arg.to_string_lossy().as_bytes())
                        })
                    }).and_then(|()| writeln!(stderr, " wrote the following unexpected data to stdout: {output}"))
                }),
            Self::MsrvTooHigh => writeln!(stderr, "MSRV is higher than cargo stable."),
            Self::MsrvNotCompatibleWithInstalledMsrv(version)=> writeln!(stderr, "cargo +<MSRV> -V returned '{}.{}.{}' which is inconsistent with the defined MSRV.", version.major, version.minor, version.patch),
        }
    }
}
/// Error returned when running any `cargo` command.
pub(crate) enum CargoErr {
    /// [`Command::output`] erred with the contained `Error` for the contained `Command`.
    CommandFail(Command, Error),
    /// [`Command::output`] was successful for the contained `Command`, but it didn't return a status code.
    ///
    /// The first contained `String` is the potentially empty content written to `stderr`, and the second
    /// `String` is the potentially empty content written to `stdout`.
    CommandNoStatus(Command, String, String),
    /// [`Command::output`] was successful for the contained `Command`, but it returned an error status code.
    ///
    /// The first contained `String` is the potentially empty content written to `stderr`, and the second
    /// `String` is the potentially empty content written to `stdout`.
    CommandErr(Command, String, String),
    /// [`Command::output`] was successful for the contained `Command`, but the data it wrote to `stdout` was not
    /// valid UTF-8.
    StdoutNotUtf8(Command),
    /// [`Command::output`] was successful for the contained `Command`, but the data it wrote to `stderr` was not
    /// valid UTF-8.
    StderrNotUtf8(Command),
    /// [`Command::output`] was successful for the contained `Command`, but a `compile_error` occurred for the
    /// `"default"` feature.
    CompileErrDefault(Command),
    /// [`Command::output`] was successful for the contained `Command`, but a `compile_error` occurred when
    /// no features were enabled and when there isn't a `"default"` feature defined.
    CompileErrNoFeatures(Command),
}
impl CargoErr {
    /// Writes `self` to `stderr`.
    pub(crate) fn write(self, mut stderr: StderrLock<'_>) -> Result<(), Error> {
        match self {
            Self::CommandFail(cmd, err) => writeln!(stderr, "{err}").map(|()| cmd),
            Self::CommandNoStatus(cmd, err, out) => if out.is_empty() {
                Ok(())
            } else {
                writeln!(stderr, "{out}")
            }
            .and_then(|()| {
                if err.is_empty() {
                    writeln!(stderr, "Missing status code and nothing written to stderr.")
                } else {
                    writeln!(
                        stderr,
                        "Missing status code, but the following was written to stderr: {err}"
                    )
                }
                .map(|()| cmd)
            }),
            Self::CommandErr(cmd, err, out) => if out.is_empty() {
                Ok(())
            } else {
                writeln!(stderr, "{out}")
            }
            .and_then(|()| {
                if err.is_empty() {
                    Ok(cmd)
                } else {
                    writeln!(stderr, "{err}").map(|()| cmd)
                }
            }),
            Self::StdoutNotUtf8(cmd) => {
                writeln!(stderr, "Invalid UTF-8 written to stdout.").map(|()| cmd)
            }
            Self::StderrNotUtf8(cmd) => {
                writeln!(stderr, "Invalid UTF-8 written to stderr.").map(|()| cmd)
            }
            Self::CompileErrDefault(cmd) => {
                writeln!(stderr, "compile_error! raised on default feature.").map(|()| cmd)
            }
            Self::CompileErrNoFeatures(cmd) => writeln!(
                stderr,
                "compile_error! raised with no features when a default feature does not exist."
            )
            .map(|()| cmd),
        }
        .and_then(|cmd| {
            stderr
                .write_all(cmd.get_program().to_string_lossy().as_bytes())
                .and_then(|()| {
                    cmd.get_args()
                        .try_fold((), |(), arg| {
                            stderr
                                .write_all(b" ")
                                .and_then(|()| stderr.write_all(arg.to_string_lossy().as_bytes()))
                        })
                        .and_then(|()| writeln!(stderr))
                })
        })
    }
}
/// Compiler version.
#[cfg_attr(test, derive(PartialEq))]
pub(crate) struct Version {
    /// Major version.
    pub major: u64,
    /// Minor version.
    pub minor: u64,
    /// Patch version.
    pub patch: u64,
}
/// `"+stable"`.
const PLUS_STABLE: &str = "+stable";
/// `"RUSTUP_HOME"`.
const RUSTUP_HOME: &str = "RUSTUP_HOME";
/// `"CARGO_HOME"`.
const CARGO_HOME: &str = "CARGO_HOME";
/// Toolchain to use.
#[expect(
    variant_size_differences,
    reason = "fine. This doesn't get triggered if the other variants were unit variants despite Toolchain being the same size."
)]
#[derive(Clone, Copy)]
pub(crate) enum Toolchain<'a> {
    /// `cargo +stable`.
    Stable,
    /// `cargo`.
    ///
    /// Contained `bool` is `true` iff `--ignore-rust-version` should be passed.
    Default(bool),
    /// `cargo +<MSRV>`.
    Msrv(&'a str),
}
impl Toolchain<'_> {
    /// Extracts the compiler version from `stdout`.
    ///
    /// This must only be called by [`Self::get_version`].
    #[expect(unsafe_code, reason = "comments justify correctness")]
    fn parse_stdout(cmd: Command, stdout: Vec<u8>) -> Result<Version, Box<ToolchainErr>> {
        /// `"cargo "`.
        const CARGO: &[u8; 6] = b"cargo ";
        if let Ok(utf8) = String::from_utf8(stdout) {
            utf8.as_bytes()
                .split_at_checked(CARGO.len())
                .and_then(|(pref, rem)| {
                    if pref == CARGO {
                        let mut iter = rem.split(|b| *b == b'.');
                        if let Some(fst) = iter.next()
                            // SAFETY:
                            // Original input was a `str`, and we split on a single-byte
                            // UTF-8 code unit.
                            && let Ok(major) = manifest::parse_int(unsafe {
                                str::from_utf8_unchecked(fst)
                            })
                            && let Some(snd) = iter.next()
                            // SAFETY:
                            // Original input was a `str`, and we split on a single-byte
                            // UTF-8 code unit.
                            && let Ok(minor) = manifest::parse_int(unsafe {
                                str::from_utf8_unchecked(snd)
                            })
                            && let Some(lst) = iter.next()
                            && iter.next().is_none()
                            && let Some(lst_fst) = lst.split(|b| *b == b' ').next()
                            // SAFETY:
                            // Original input was a `str`, and we split on a single-byte
                            // UTF-8 code unit.
                            && let Ok(patch) = manifest::parse_int(unsafe {
                                str::from_utf8_unchecked(lst_fst)
                            })
                        {
                            Some(Version {
                                major,
                                minor,
                                patch,
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                })
                .ok_or_else(|| Box::new(ToolchainErr::UnexpectedOutput(cmd, utf8)))
        } else {
            Err(Box::new(ToolchainErr::StdoutNotUtf8(cmd)))
        }
    }
    /// Returns the version.
    pub(crate) fn get_version(
        self,
        rustup_home: Option<&Path>,
        cargo_path: &Path,
        cargo_home: Option<&Path>,
    ) -> Result<Version, Box<ToolchainErr>> {
        let mut cmd = Command::new(cargo_path);
        if let Some(env) = rustup_home {
            _ = cmd.env(RUSTUP_HOME, env);
        }
        if let Some(env) = cargo_home {
            _ = cmd.env(CARGO_HOME, env);
        }
        match self {
            Self::Stable => {
                _ = cmd.arg(PLUS_STABLE);
            }
            Self::Default(_) => {}
            Self::Msrv(val) => {
                _ = cmd.arg(val);
            }
        }
        match cmd
            .arg("-V")
            .stderr(Stdio::piped())
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .output()
        {
            Ok(output) => {
                if let Some(status_code) = output.status.code() {
                    if status_code == 0i32 {
                        Self::parse_stdout(cmd, output.stdout)
                    } else if let Ok(err) = String::from_utf8(output.stderr) {
                        Err(Box::new(ToolchainErr::CommandErr(cmd, err, status_code)))
                    } else {
                        Err(Box::new(ToolchainErr::StderrNotUtf8(cmd)))
                    }
                } else if let Ok(err) = String::from_utf8(output.stderr) {
                    Err(Box::new(ToolchainErr::CommandNoStatus(cmd, err)))
                } else {
                    Err(Box::new(ToolchainErr::StderrNotUtf8(cmd)))
                }
            }
            Err(e) => Err(Box::new(ToolchainErr::CommandFail(cmd, e))),
        }
    }
}
/// `"--all-targets"`.
const DASH_DASH_ALL_TARGETS: &str = "--all-targets";
/// `"--benches"`.
const DASH_DASH_BENCHES: &str = "--benches";
/// `"--bins"`.
const DASH_DASH_BINS: &str = "--bins";
/// `"--examples"`.
const DASH_DASH_EXAMPLES: &str = "--examples";
/// `"--lib"`.
const DASH_DASH_LIB: &str = "--lib";
/// `"--tests"`.
const DASH_DASH_TESTS: &str = "--tests";
/// `"-p"`.
const DASH_P: &str = "-p";
/// `"-q"`.
const DASH_Q: &str = "-q";
/// `"--color"`.
const DASH_DASH_COLOR: &str = "--color";
/// `"always"`.
const ALWAYS: &str = "always";
/// `"never"`.
const NEVER: &str = "never";
/// `"--no-default-features"`.
const DASH_DASH_NO_DEFAULT_FEATURES: &str = "--no-default-features";
/// `"--features"`.
const DASH_DASH_FEATURES: &str = "--features";
/// `"--"`.
const DASH_DASH: &str = "--";
/// `"default"`.
const DEFAULT: &str = "default";
/// `"--ignore-rust-version"`.
const DASH_DASH_IGNORE_RUST_VERSION: &str = "--ignore-rust-version";
/// Common options to pass to [`Clippy::run`] and [`Test::run`].
pub(crate) struct Options<'toolchain, 'package, 'errs> {
    /// The `cargo` toolchain to use.
    pub toolchain: Toolchain<'toolchain>,
    /// The path to the `rustup` storage directory.
    pub rustup_home: Option<PathBuf>,
    /// The path to `cargo`.
    pub cargo_path: PathBuf,
    /// The path to the `cargo` storage directory.
    pub cargo_home: Option<PathBuf>,
    /// Name of the package.
    pub package_name: &'package str,
    /// `true` iff color should be written to `stdout` and `stderr`.
    pub color: bool,
    /// `true` iff `compile_error`s should be ignored.
    pub ignore_compile_errors: bool,
    /// `true` iff a feature named `"default"` exists.
    pub default_feature_does_not_exist: bool,
    /// Hash set of non-terminating errors to be written at the very end.
    pub non_terminating_errors: &'errs mut HashSet<String>,
}
/// Executes `cmd`.
fn execute_command(
    mut cmd: Command,
    options: &mut Options<'_, '_, '_>,
    features: &str,
) -> Result<(), Box<CargoErr>> {
    match cmd.stdout(Stdio::piped()).output() {
        Ok(output) => {
            if let Some(code) = output.status.code() {
                match code {
                    0i32 => {
                        if !output.stderr.is_empty() {
                            _ = options.non_terminating_errors.insert(
                                match String::from_utf8(output.stderr) {
                                    Ok(err) => err,
                                    Err(e) => e.to_string(),
                                },
                            );
                        }
                        Ok(())
                    }
                    101i32 => {
                        /// `"compile_error!"` as a byte string.
                        const COMPILE_ERROR: &[u8; 14] = b"compile_error!";
                        if output
                            .stderr
                            .windows(COMPILE_ERROR.len())
                            .any(|window| window == COMPILE_ERROR)
                        {
                            if options.ignore_compile_errors {
                                if features == DEFAULT {
                                    Err(Box::new(CargoErr::CompileErrDefault(cmd)))
                                } else if options.default_feature_does_not_exist
                                    && features.is_empty()
                                {
                                    Err(Box::new(CargoErr::CompileErrNoFeatures(cmd)))
                                } else {
                                    Ok(())
                                }
                            } else if let Ok(err) = String::from_utf8(output.stderr) {
                                if let Ok(stdout) = String::from_utf8(output.stdout) {
                                    Err(Box::new(CargoErr::CommandErr(cmd, err, stdout)))
                                } else {
                                    Err(Box::new(CargoErr::StdoutNotUtf8(cmd)))
                                }
                            } else {
                                Err(Box::new(CargoErr::StderrNotUtf8(cmd)))
                            }
                        } else if let Ok(err) = String::from_utf8(output.stderr) {
                            if let Ok(stdout) = String::from_utf8(output.stdout) {
                                Err(Box::new(CargoErr::CommandErr(cmd, err, stdout)))
                            } else {
                                Err(Box::new(CargoErr::StdoutNotUtf8(cmd)))
                            }
                        } else {
                            Err(Box::new(CargoErr::StderrNotUtf8(cmd)))
                        }
                    }
                    _ => {
                        if let Ok(err) = String::from_utf8(output.stderr) {
                            if let Ok(stdout) = String::from_utf8(output.stdout) {
                                Err(Box::new(CargoErr::CommandErr(cmd, err, stdout)))
                            } else {
                                Err(Box::new(CargoErr::StdoutNotUtf8(cmd)))
                            }
                        } else {
                            Err(Box::new(CargoErr::StderrNotUtf8(cmd)))
                        }
                    }
                }
            } else if let Ok(err) = String::from_utf8(output.stderr) {
                if let Ok(stdout) = String::from_utf8(output.stdout) {
                    Err(Box::new(CargoErr::CommandNoStatus(cmd, err, stdout)))
                } else {
                    Err(Box::new(CargoErr::StdoutNotUtf8(cmd)))
                }
            } else {
                Err(Box::new(CargoErr::StderrNotUtf8(cmd)))
            }
        }
        Err(e) => Err(Box::new(CargoErr::CommandFail(cmd, e))),
    }
}
/// `cargo check`.
pub(crate) struct Check;
impl Check {
    /// Execute `cargo check`.
    pub(crate) fn run(
        options: &mut Options<'_, '_, '_>,
        targets: CheckClippyTargets,
        features: &str,
    ) -> Result<(), Box<CargoErr>> {
        let mut c = Command::new(options.cargo_path.as_path());
        _ = c.stderr(Stdio::piped()).stdin(Stdio::null());
        if let Some(ref env) = options.rustup_home {
            _ = c.env(RUSTUP_HOME, env);
        }
        if let Some(ref env) = options.cargo_home {
            _ = c.env(CARGO_HOME, env);
        }
        let ignore_msrv = match options.toolchain {
            Toolchain::Stable => {
                _ = c.arg(PLUS_STABLE);
                false
            }
            Toolchain::Default(ignore_msrv) => ignore_msrv,
            Toolchain::Msrv(ref msrv) => {
                _ = c.arg(msrv);
                false
            }
        };
        _ = c
            .arg("check")
            .arg(DASH_P)
            .arg(options.package_name)
            .arg(DASH_Q);
        match targets {
            CheckClippyTargets::Default => {}
            CheckClippyTargets::All => {
                _ = c.arg(DASH_DASH_ALL_TARGETS);
            }
            CheckClippyTargets::Targets(tar) => {
                if tar.contains(Target::Benches) {
                    _ = c.arg(DASH_DASH_BENCHES);
                }
                if tar.contains(Target::Bins) {
                    _ = c.arg(DASH_DASH_BINS);
                }
                if tar.contains(Target::Examples) {
                    _ = c.arg(DASH_DASH_EXAMPLES);
                }
                if tar.contains(Target::Lib) {
                    _ = c.arg(DASH_DASH_LIB);
                }
                if tar.contains(Target::Tests) {
                    _ = c.arg(DASH_DASH_TESTS);
                }
            }
        }
        if ignore_msrv {
            _ = c.arg(DASH_DASH_IGNORE_RUST_VERSION);
        }
        _ = c
            .arg(DASH_DASH_COLOR)
            .arg(if options.color { ALWAYS } else { NEVER })
            .arg(DASH_DASH_NO_DEFAULT_FEATURES);
        if !features.is_empty() {
            _ = c.arg(DASH_DASH_FEATURES).arg(features);
        }
        execute_command(c, options, features)
    }
}
/// `cargo clippy`.
pub(crate) struct Clippy;
impl Clippy {
    /// Execute `cargo clippy`.
    pub(crate) fn run(
        options: &mut Options<'_, '_, '_>,
        targets: CheckClippyTargets,
        deny_warnings: bool,
        features: &str,
    ) -> Result<(), Box<CargoErr>> {
        let mut c = Command::new(options.cargo_path.as_path());
        _ = c.stderr(Stdio::piped()).stdin(Stdio::null());
        if let Some(ref env) = options.rustup_home {
            _ = c.env(RUSTUP_HOME, env);
        }
        if let Some(ref env) = options.cargo_home {
            _ = c.env(CARGO_HOME, env);
        }
        let ignore_msrv = match options.toolchain {
            Toolchain::Stable => {
                _ = c.arg(PLUS_STABLE);
                false
            }
            Toolchain::Default(ignore_msrv) => ignore_msrv,
            Toolchain::Msrv(ref msrv) => {
                _ = c.arg(msrv);
                false
            }
        };
        _ = c
            .arg("clippy")
            .arg(DASH_P)
            .arg(options.package_name)
            .arg(DASH_Q);
        match targets {
            CheckClippyTargets::Default => {}
            CheckClippyTargets::All => {
                _ = c.arg(DASH_DASH_ALL_TARGETS);
            }
            CheckClippyTargets::Targets(tar) => {
                if tar.contains(Target::Benches) {
                    _ = c.arg(DASH_DASH_BENCHES);
                }
                if tar.contains(Target::Bins) {
                    _ = c.arg(DASH_DASH_BINS);
                }
                if tar.contains(Target::Examples) {
                    _ = c.arg(DASH_DASH_EXAMPLES);
                }
                if tar.contains(Target::Lib) {
                    _ = c.arg(DASH_DASH_LIB);
                }
                if tar.contains(Target::Tests) {
                    _ = c.arg(DASH_DASH_TESTS);
                }
            }
        }
        if ignore_msrv {
            _ = c.arg(DASH_DASH_IGNORE_RUST_VERSION);
        }
        _ = c
            .arg(DASH_DASH_COLOR)
            .arg(if options.color { ALWAYS } else { NEVER })
            .arg(DASH_DASH_NO_DEFAULT_FEATURES);
        if !features.is_empty() {
            _ = c.arg(DASH_DASH_FEATURES).arg(features);
        }
        if deny_warnings {
            _ = c.arg(DASH_DASH).arg("-Dwarnings");
        }
        execute_command(c, options, features)
    }
}
/// `cargo test`.
pub(crate) struct Test;
impl Test {
    /// Execute `cargo test`.
    pub(crate) fn run(
        options: &mut Options<'_, '_, '_>,
        targets: TestTargets,
        ignored: Ignored,
        features: &str,
    ) -> Result<(), Box<CargoErr>> {
        /// `"--ignored"`.
        const DASH_DASH_IGNORED: &str = "--ignored";
        /// `"--include-ignored"`.
        const DASH_DASH_INCLUDE_IGNORED: &str = "--include-ignored";
        let mut c = Command::new(options.cargo_path.as_path());
        _ = c.stderr(Stdio::piped()).stdin(Stdio::null());
        if let Some(ref env) = options.rustup_home {
            _ = c.env(RUSTUP_HOME, env);
        }
        if let Some(ref env) = options.cargo_home {
            _ = c.env(CARGO_HOME, env);
        }
        let ignore_msrv = match options.toolchain {
            Toolchain::Stable => {
                _ = c.arg(PLUS_STABLE);
                false
            }
            Toolchain::Default(ignore_msrv) => ignore_msrv,
            Toolchain::Msrv(ref msrv) => {
                _ = c.arg(msrv);
                false
            }
        };
        _ = c
            .arg("test")
            .arg(DASH_P)
            .arg(options.package_name)
            .arg(DASH_Q);
        match targets {
            TestTargets::Default => {}
            TestTargets::All => {
                _ = c.arg(DASH_DASH_ALL_TARGETS);
            }
            TestTargets::Targets(tar) => {
                if tar.contains(Target::Benches) {
                    _ = c.arg(DASH_DASH_BENCHES);
                }
                if tar.contains(Target::Bins) {
                    _ = c.arg(DASH_DASH_BINS);
                }
                if tar.contains(Target::Examples) {
                    _ = c.arg(DASH_DASH_EXAMPLES);
                }
                if tar.contains(Target::Lib) {
                    _ = c.arg(DASH_DASH_LIB);
                }
                if tar.contains(Target::Tests) {
                    _ = c.arg(DASH_DASH_TESTS);
                }
            }
            TestTargets::Doc => {
                _ = c.arg("--doc");
            }
        }
        if ignore_msrv {
            _ = c.arg(DASH_DASH_IGNORE_RUST_VERSION);
        }
        _ = c
            .arg(DASH_DASH_COLOR)
            .arg(if options.color { ALWAYS } else { NEVER })
            .arg(DASH_DASH_NO_DEFAULT_FEATURES);
        if !features.is_empty() {
            _ = c.arg(DASH_DASH_FEATURES).arg(features);
        }
        _ = c
            .arg(DASH_DASH)
            .arg(DASH_DASH_COLOR)
            .arg(if options.color { ALWAYS } else { NEVER });
        match ignored {
            Ignored::None => {}
            Ignored::Only => {
                _ = c.arg(DASH_DASH_IGNORED);
            }
            Ignored::Include => {
                _ = c.arg(DASH_DASH_INCLUDE_IGNORED);
            }
        }
        execute_command(c, options, features)
    }
}
#[cfg(test)]
mod tests {
    use super::{Command, Toolchain, ToolchainErr, Version};
    #[expect(clippy::cognitive_complexity, reason = "a lot of tests")]
    #[test]
    fn toolchain_parse() {
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), vec![255]), Err(e) if matches!(*e, ToolchainErr::StdoutNotUtf8(_)))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), Vec::new()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v.is_empty()))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1.2".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1.2"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1.2.3.".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1.2.3."))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1.2.3a".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1.2.3a"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b" cargo 1.2.3".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == " cargo 1.2.3"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"Cargo 1.2.3".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "Cargo 1.2.3"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1.00.0".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1.00.0"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1.2.03".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1.2.03"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo -1.2.3".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo -1.2.3"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo1.2.3".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo1.2.3"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo  1.2.3".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo  1.2.3"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo\t1.2.3".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo\t1.2.3"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1..3".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1..3"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1.".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1."))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 111111111111111111111111.2.3".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 111111111111111111111111.2.3"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1.2.3.4".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1.2.3.4"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 1.2.3-nightly".to_vec()), Err(e) if matches!(*e, ToolchainErr::UnexpectedOutput(_, ref v) if v == "cargo 1.2.3-nightly"))
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 18446744073709551615.18446744073709551615.18446744073709551615".to_vec()), Ok(v) if v == Version { major: u64::MAX, minor: u64::MAX, patch: u64::MAX, })
        );
        assert!(
            matches!(Toolchain::parse_stdout(Command::new(""), b"cargo 0.0.0 asdflk 0023n0=lk0932(!@#V)\x00".to_vec()), Ok(v) if v == Version { major: 0, minor: 0, patch: 0, })
        );
    }
}