cargo-liner 0.10.1

Cargo subcommand to install and update binary packages listed in configuration.
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
//! Module handling the execution of cargo for various operations.
//!
//! See [`install_all`] in order to install configured packages.

use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::{env, io, iter};

use clap::ColorChoice;
use color_eyre::Section;
use color_eyre::eyre::{self, Result, WrapErr, eyre};
use log::Level;
use regex::Regex;
use semver::Version;

use crate::cli::BinstallChoice;
use crate::config::DetailedPackageReq;

/// Installs a package, by running `cargo install` passing the `name`, `version`
/// and requested `features`, and returns the exit code of the process, if any.
///
/// The launched process' path is determined using the `$CARGO` environment
/// variable as it is set by Cargo when it calls an external subcommand's
/// corresponding program. See the [Cargo reference] for more details.
///
/// [Cargo reference]: https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands
#[expect(
    clippy::too_many_lines,
    reason = "This is just a long list of options to apply."
)]
fn install(
    pkg_name: &str,
    pkg_req: &DetailedPackageReq,
    force: bool,
    dry_run: bool,
    color: ColorChoice,
    verbosity: i8,
) -> Result<()> {
    let mut cmd = Command::new(env_var()?);

    if !pkg_req.environment.is_empty() {
        cmd.envs(&pkg_req.environment);
        log::trace!("Environment set: {:#?}", pkg_req.environment);
    }

    cmd.args(["--color", &color.to_string()]);
    add_verbosity_arg(&mut cmd, verbosity);
    cmd.args(["install", "--version", &pkg_req.version.to_string()]);

    if !pkg_req.default_features {
        cmd.arg("--no-default-features");
        log::trace!("`--no-default-features` arg added.");
    }

    if pkg_req.all_features {
        cmd.arg("--all-features");
        log::trace!("`--all-features` arg added.");
    }

    if !pkg_req.features.is_empty() {
        cmd.arg("--features").arg(pkg_req.features.join(","));
        log::trace!("`--features` arg added.");
    }

    if let Some(index) = pkg_req.index.as_deref() {
        cmd.args(["--index", index]);
        log::trace!("`--index {index}` args added.");
    }

    if let Some(registry) = pkg_req.registry.as_deref() {
        cmd.args(["--registry", registry]);
        log::trace!("`--registry {registry}` args added.");
    }

    if let Some(git) = pkg_req.git.as_deref() {
        cmd.args(["--git", git]);
        log::trace!("`--git {git}` args added.");
    }

    if let Some(branch) = pkg_req.branch.as_deref() {
        cmd.args(["--branch", branch]);
        log::trace!("`--branch {branch}` args added.");
    }

    if let Some(tag) = pkg_req.tag.as_deref() {
        cmd.args(["--tag", tag]);
        log::trace!("`--tag {tag}` args added.");
    }

    if let Some(rev) = pkg_req.rev.as_deref() {
        cmd.args(["--rev", rev]);
        log::trace!("`--rev {rev}` args added.");
    }

    if let Some(path) = pkg_req.path.as_deref() {
        cmd.args(["--path", path]);
        log::trace!("`--path {path}` args added.");
    }

    for bin in &pkg_req.bins {
        cmd.args(["--bin", bin]);
        log::trace!("`--bin {bin}` args added.");
    }

    if pkg_req.all_bins {
        cmd.arg("--bins");
        log::trace!("`--bins` arg added.");
    }

    for example in &pkg_req.examples {
        cmd.args(["--example", example]);
        log::trace!("`--example {example}` args added.");
    }

    if pkg_req.all_examples {
        cmd.arg("--examples");
        log::trace!("`--examples` arg added.");
    }

    if pkg_req.ignore_rust_version {
        cmd.arg("--ignore-rust-version");
        log::trace!("`--ignore-rust-version` arg added.");
    }

    if force {
        cmd.arg("--force");
        log::trace!("`--force` arg added.");
    }

    if pkg_req.frozen {
        cmd.arg("--frozen");
        log::trace!("`--frozen` arg added.");
    }

    if pkg_req.locked {
        cmd.arg("--locked");
        log::trace!("`--locked` arg added.");
    }

    if pkg_req.offline {
        cmd.arg("--offline");
        log::trace!("`--offline` arg added.");
    }

    // This should be kept here: after all other options and before the `--`.
    if !pkg_req.extra_arguments.is_empty() {
        cmd.args(&pkg_req.extra_arguments);
        log::trace!("Extra arguments added: {:#?}", pkg_req.extra_arguments);
    }

    cmd.args(["--", pkg_name]);
    log_cmd(&cmd);

    // Keep it as late as possible for fidelity.
    if dry_run {
        // TODO: Pass `--dry-run` when stabilized.
        log::warn!("Dry run: would have run `cargo install` for `{pkg_name}`.");
        log::info!("Bump verbosity if additional details are desired.");
        // TODO: Don't forget to check status here as well when passing `--dry-run`.
        Ok(())
    } else {
        let status = cmd
            .status()
            .wrap_err("Failed to execute Cargo.")
            .note(
                "This can happen for many reasons, but it should not happen easily at this point.",
            )
            .suggestion("Read the underlying error message.")?;
        status.success().then_some(()).ok_or_else(|| {
            eyre!("Cargo process finished unsuccessfully: {status}")
                .note("This can happen for many reasons.")
                .suggestion("Read Cargo's output.")
        })
    }
}

/// Adds the adequate verbosity argument to the given Cargo [`Command`].
fn add_verbosity_arg(cmd: &mut Command, verbosity: i8) {
    match verbosity.cmp(&0) {
        Ordering::Greater => {
            let opt = iter::once('-')
                .chain(iter::repeat_n('v', verbosity.try_into().unwrap()))
                .collect::<String>();
            cmd.arg(&opt);
            log::trace!("`{opt}` arg added.");
        }
        Ordering::Less => {
            cmd.arg("-q");
            log::trace!("`-q` arg added.");
        }
        Ordering::Equal => {}
    }
}

/// Equivalent of [`install`] using `cargo-binstall` as a backend.
fn binstall(
    pkg_name: &str,
    pkg_req: &DetailedPackageReq,
    force: bool,
    dry_run: bool,
    verbosity: i8,
) -> Result<()> {
    let mut cmd = Command::new(env_var()?);
    // The tool emits to stdout by default and does not have an option to
    // control that while only stderr is used here, so redirect instead.
    cmd.stdout(io::stderr());

    // Do the same regarding the custom environment variables and extra
    // arguments: the backends are exclusive for a package, so this should not
    // be too confusing, hopefully.
    if !pkg_req.environment.is_empty() {
        cmd.envs(&pkg_req.environment);
        log::trace!("Environment set: {:#?}", pkg_req.environment);
    }

    cmd.args([
        // What we want here.
        "binstall",
        // Telemetry is optional.
        "--disable-telemetry",
        // Non-interactive by design for now.
        "--no-confirm",
        // Also apply the verbosity.
        "--log-level",
        match verbosity {
            i8::MIN..=-3 => "off",
            -2 => "error",
            -1 => "warn",
            0 | 1 => "info",
            2 => "debug",
            3..=i8::MAX => "trace",
        },
        // The package version to install.
        "--version",
        &pkg_req.version.to_string(),
    ]);

    if let Some(index) = pkg_req.index.as_deref() {
        cmd.args(["--index", index]);
        log::trace!("`--index {index}` args added.");
    }

    if let Some(registry) = pkg_req.registry.as_deref() {
        cmd.args(["--registry", registry]);
        log::trace!("`--registry {registry}` args added.");
    }

    if let Some(git) = pkg_req.git.as_deref() {
        cmd.args(["--git", git]);
        log::trace!("`--git {git}` args added.");
    }

    if force {
        cmd.arg("--force");
        log::trace!("`--force` arg added.");
    }

    if dry_run {
        cmd.arg("--dry-run");
        log::trace!("`--dry-run` arg added.");
        log::warn!("Dry run enabled in call to `cargo binstall` for `{pkg_name}`.");
        log::info!("Bump verbosity if additional details are desired.");
    }

    if pkg_req.locked {
        cmd.arg("--locked");
        log::trace!("`--locked` arg added.");
    }

    // This should be kept here: after all other options and before the `--`.
    if !pkg_req.extra_arguments.is_empty() {
        cmd.args(&pkg_req.extra_arguments);
        log::trace!("Extra arguments added: {:#?}", pkg_req.extra_arguments);
    }

    // Synchronize any new arguments added here with the
    // `pkg_req_is_compatible_with_binstall` function below.
    cmd.args(["--", pkg_name]);
    log_cmd(&cmd);

    let status = cmd
        .status()
        .wrap_err("Failed to execute Cargo.")
        .note("This can happen for many reasons, but it should not happen easily at this point.")
        .suggestion("Read the underlying error message.")?;
    status.success().then_some(()).ok_or_else(|| {
        eyre!("Cargo-Binstall process finished unsuccessfully: {status}")
            .note("This can happen for many reasons.")
            .suggestion("Read Cargo-Binstall's output.")
    })
}

/// Returns whether all of the given package requirement's set options will
/// indeed be passed onto `cargo-binstall` or if some of them will be ignored.
///
///  * `true`: fully compatible, all options passed;
///  * `false`: some options would be skipped;
fn pkg_req_is_compatible_with_binstall(pkg_req: &DetailedPackageReq) -> bool {
    // Full destructuring to avoid forgetting to update this function.
    let DetailedPackageReq {
        version: _,
        default_features,
        all_features,
        features,
        index: _,
        registry: _,
        git: _,
        branch,
        tag,
        rev,
        path,
        // TODO: stop considering this incompatible and pass it along.
        bins,
        all_bins,
        examples,
        all_examples,
        force: _,
        ignore_rust_version,
        frozen,
        locked: _,
        offline,
        extra_arguments: _,
        environment: _,
        skip_check: _,
        no_fail_fast: _,
        binstall: _,
    } = pkg_req;
    // Work by double negation: not incompatible.
    !(!*default_features
        || *all_features
        || !features.is_empty()
        || branch.is_some()
        || tag.is_some()
        || rev.is_some()
        || path.is_some()
        || !bins.is_empty()
        || *all_bins
        || !examples.is_empty()
        || *all_examples
        || *ignore_rust_version
        || *frozen
        || *offline)
}

/// Heuristically determines whether `cargo-binstall` is installed or not.
///
/// Currently, it first tries to see if it is among the installed packages if
/// they have been retrieved previously, and tries to call the program directly
/// with some additional validation if not.
fn binstall_is_available(installed: &BTreeSet<String>) -> bool {
    // When `--skip-check` is used.
    let res = if installed.is_empty() {
        binstall_version()
            .inspect(|ver| log::debug!("cargo-binstall successfully reports: {ver:?}"))
            .inspect_err(|err| log::debug!("cargo-binstall automatic detection failed: {err:?}"))
            .is_ok()
    } else {
        installed.contains("cargo-binstall")
    };

    log::debug!(
        "Considering cargo-binstall as {}available.",
        if res { "" } else { "not " },
    );
    res
}

/// Calls `cargo-binstall -V` and parses the returned version.
fn binstall_version() -> Result<Version> {
    let out = Command::new(env_var()?)
        .env_clear()
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .stdout(Stdio::piped())
        .args(["binstall", "-V"])
        .output()
        .wrap_err("Failed to execute Cargo.")
        .note("This can happen for many reasons, but it should not happen easily at this point.")
        .suggestion("Read the underlying error message.")?;

    if out.status.success() {
        String::from_utf8(out.stdout)
            .wrap_err("`cargo binstall -V` succeeded but returned a non-UTF8 output.")
            .note("This is rather unexpected.")
            .suggestion("Run it yourself to see if it behaves correctly.")?
            .trim_end()
            .parse()
            .wrap_err("`cargo binstall -V` succeeded but returned something else than a version.")
            .note("This is rather unexpected.")
            .suggestion("Run it yourself to see if it behaves correctly.")
    } else {
        Err(eyre!("Cargo or `cargo binstall` failed.")
            .note("This can simply be because it is not installed.")
            .suggestion("Install and run it yourself to see if it behaves correctly."))
    }
}

/// Runs `cargo install` or `binstall` for the given package depending on the
/// current Cargo-wise environment and specified choice strategy, with priority
/// for `binstall` when in auto mode.
#[expect(clippy::too_many_arguments, reason = "Plumbing.")]
fn install_one(
    installed: &BTreeSet<String>,
    pkg_name: &str,
    pkg_req: &DetailedPackageReq,
    force: bool,
    dry_run: bool,
    binstall: BinstallChoice,
    color: ColorChoice,
    verbosity: i8,
) -> Result<()> {
    // HACK: disable the auto mode under testing to easily avoid bothersome
    // hacks and maintenance there in order to avoid failing when the tool is
    // installed locally compared to current CI. Tests targeting binstall have
    // to explicitly enable the feature through the `always` setting.
    if binstall == BinstallChoice::Always
        || binstall == BinstallChoice::Auto
            && !context_seems_testing(false)
            && binstall_is_available(installed)
    {
        // See #31: avoid using Binstall in cases where incompatible arguments
        // would not be forwarded but still be important for overall success.
        if binstall == BinstallChoice::Always || pkg_req_is_compatible_with_binstall(pkg_req) {
            log::debug!("Using `cargo-binstall` as the installation method.");
            return self::binstall(pkg_name, pkg_req, force, dry_run, verbosity);
        }

        log::warn!(
            "`{pkg_name}` has some ignored incompatible options set, not using \
             `cargo-binstall` for it; see the documentation for more details.",
        );
    }

    log::debug!("Using `cargo install` as the installation method.");
    install(pkg_name, pkg_req, force, dry_run, color, verbosity)
}

/// Runs `cargo install` or `binstall` for all packages listed in the given
/// user configuration and returns a per-package installation report.
///
/// Returns `Ok(report)` when `no_fail_fast` is `true`, otherwise `Err(err)` of
/// the first error `err` encountered.
#[expect(clippy::too_many_arguments, reason = "Plumbing.")]
pub fn install_all(
    packages: &BTreeMap<String, DetailedPackageReq>,
    installed: &BTreeSet<String>,
    no_fail_fast: bool,
    force: bool,
    dry_run: bool,
    binstall: BinstallChoice,
    color: ColorChoice,
    verbosity: i8,
) -> Result<InstallReport> {
    // Returned installation report.
    let mut rep = BTreeMap::new();
    // Aggregation of errors when `no_fail_fast` is enabled.
    let mut err_rep = None::<eyre::Report>;

    for (pkg_name, pkg) in packages {
        let is_installed = installed.contains(pkg_name);
        log::info!(
            "{}ing `{pkg_name}`...",
            if is_installed { "Updat" } else { "Install" }
        );

        if let Err(err) = install_one(
            installed,
            pkg_name,
            pkg,
            force || pkg.force,
            dry_run,
            // FIXME: this lets the per-package configuration have precedence
            // over the global defaults, but over the CLI as well; optionals
            // should be introduced in order to re-order things properly instead.
            pkg.binstall.unwrap_or(binstall),
            color,
            verbosity,
        )
        .inspect(|()| {
            rep.insert(
                pkg_name.clone(),
                if is_installed {
                    InstallStatus::Updated
                } else {
                    InstallStatus::Installed
                },
            );
        })
        .wrap_err_with(|| {
            rep.insert(pkg_name.clone(), InstallStatus::Failed);
            format!(
                "Failed to {} {pkg_name:?}.",
                if is_installed { "update" } else { "install" }
            )
        }) {
            if no_fail_fast || pkg.no_fail_fast {
                // Can't use `Option::map_or` for ownership reasons.
                err_rep = Some(match err_rep {
                    Some(err_rep) => err_rep.wrap_err(err),
                    None => err,
                });
            } else {
                return Err(err.suggestion(
                    "Use `ship --no-fail-fast` to ignore this and continue on with other packages.",
                ));
            }
        }
    }

    Ok(InstallReport {
        package_statuses: rep,
        error_report: err_rep,
    })
}

/// Result of [`install_all`].
#[must_use]
#[derive(Debug)]
pub struct InstallReport {
    /// Installation status per package name.
    pub package_statuses: BTreeMap<String, InstallStatus>,
    /// Aggregation of errors to bubble up.
    pub error_report: Option<eyre::Report>,
}

/// Result of [`install`] for some package.
#[derive(Debug)]
pub enum InstallStatus {
    /// The package was newly installed with success.
    Installed,
    /// The package was successfully updated, replacing a previous version.
    Updated,
    /// The package failed to install or update.
    Failed,
}

/// Runs `cargo uninstall` with the given package name.
fn uninstall(pkg_name: &str, dry_run: bool, color: ColorChoice, verbosity: i8) -> Result<()> {
    let mut cmd = Command::new(env_var()?);
    cmd.args(["--color", &color.to_string()]);
    add_verbosity_arg(&mut cmd, verbosity);
    cmd.args(["uninstall", "--", pkg_name]);
    log_cmd(&cmd);

    if dry_run {
        log::warn!("Dry run: would have run `cargo uninstall` for `{pkg_name}`.");
        log::info!("Bump verbosity if additional details are desired.");
        return Ok(());
    }

    let status = cmd
        .status()
        .wrap_err("Failed to execute Cargo.")
        .note("This can happen for many reasons, but it should not happen easily at this point.")
        .suggestion("Read the underlying error message.")?;
    status.success().then_some(()).ok_or_else(|| {
        eyre!("Cargo process finished unsuccessfully: {status}")
            .note("This can happen for many reasons.")
            .suggestion("Read Cargo's output.")
    })
}

/// Uninstalls all the packages given by name.
pub fn uninstall_all(
    pkg_names: impl IntoIterator<Item = impl AsRef<str>>,
    no_fail_fast: bool,
    dry_run: bool,
    color: ColorChoice,
    verbosity: i8,
) -> Result<()> {
    // Aggregation of errors when `no_fail_fast` is enabled.
    let mut err_rep = None::<eyre::Report>;

    for pkg_name in pkg_names {
        let pkg_name = pkg_name.as_ref();
        log::info!("Uninstalling {pkg_name:?}...");

        if let Err(err) = uninstall(pkg_name, dry_run, color, verbosity)
            .wrap_err_with(|| format!("Failed to uninstall {pkg_name:?}."))
        {
            if no_fail_fast {
                err_rep = Some(match err_rep {
                    Some(err_rep) => err_rep.wrap_err(err),
                    None => err,
                });
            } else {
                return Err(err.suggestion(
                    "Use `-k/--no-fail-fast` to ignore this and continue on with other packages.",
                ));
            }
        }
    }

    err_rep.map_or(Ok(()), Err)
}

/// Spawns `cargo search` for the given package with only stdout piped and
/// returns the corresponding child process handle to be used with
/// [`finish_search_exact`].
fn spawn_search_exact(pkg: &str) -> Result<Child> {
    // HACK: detect the test context in order to adapt the execution to it.
    let is_test = context_seems_testing(true);
    let mut cmd = Command::new(env_var()?);

    cmd.stdin(Stdio::null());
    cmd.stderr(if is_test || log::log_enabled!(Level::Debug) {
        Stdio::inherit()
    } else {
        Stdio::null()
    });
    cmd.stdout(Stdio::piped());
    cmd.args(["--color=never", "search"]);

    if is_test {
        cmd.arg("--registry=dummy-registry");
    }

    cmd.args(["--limit=1", "--", pkg]);

    log_cmd(&cmd);
    cmd.spawn()
        .wrap_err("Failed to spawn Cargo.")
        .note("This can happen for many reasons, but it should not happen easily at this point.")
        .suggestion("Read the underlying error message.")
}

/// Waits for the given child process as spawned by [`spawn_search_exact`] to
/// finish and extract the received package version from the output.
fn finish_search_exact(pkg: &str, proc: Child) -> Result<Version> {
    let out = proc
        .wait_with_output()
        .wrap_err_with(|| format!("Failed to wait for the Cargo child process for {pkg:?}."))
        .note("This can happen for many reasons, but it should not happen easily at this point.")
        .suggestion("Read the underlying error message.")?;

    if !out.status.success() {
        eyre::bail!(
            "Search for {:?} failed on {:?} with stderr: {:?}",
            pkg,
            out.status.code(),
            String::from_utf8(out.stderr),
        );
    }

    let stdout = String::from_utf8(out.stdout)
        .wrap_err("Failed to decode the standard output.")
        .note("This really should not happen.")
        .suggestion(crate::OPEN_ISSUE_MSG)?;
    log::trace!("Search for {pkg:?} got: {stdout:?}");

    // See https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions.
    let ver = Regex::new(&format!(r#"{pkg}\s=\s"([0-9a-zA-Z.+-]+)"\s+#.*"#))
        .wrap_err_with(|| format!("Failed to build the search regex for {pkg:?}."))
        .note("This can happen if the package name contains some special characters.")
        .suggestion("Check that the name is the intended one or open an issue.")?
        .captures(
            stdout
                .lines()
                .next()
                .ok_or_else(|| eyre!("Not at least one line in search output for {pkg:#?}."))
                .suggestion("Check that the package does indeed exist.")?,
        )
        .ok_or_else(|| eyre!("No regex capture while parsing search output for {pkg:#?}."))
        .suggestion("Check that the package does indeed exist.")?
        .get(1)
        .ok_or_else(|| eyre!("Version not captured by regex matching search output for {pkg:#?}."))
        .note(
            "This should not easily happen at this point: the search returned the wanted package.",
        )
        .suggestion(crate::OPEN_ISSUE_MSG)?
        .as_str()
        .parse::<Version>()
        .wrap_err_with(|| format!("Failed to parse the version received for {pkg:?}."))
        .note(
            "This should not easily happen at this point: the search returned the wanted package.",
        )
        .suggestion(crate::OPEN_ISSUE_MSG)?;
    log::trace!("Parsed version is: {ver:#?}.");

    Ok(ver)
}

/// Runs `*_search_exact` for all packages in the given list and returns the
/// thus fetched versions in the collected map.
pub fn search_exact_all(pkgs: &[impl AsRef<str>]) -> Result<BTreeMap<String, Version>> {
    log::info!("Fetching latest package versions...");
    let mut procs = Vec::new();
    let mut vers = BTreeMap::new();

    log::debug!("Spawning search child processes in parallel...");
    for pkg in pkgs.iter().map(AsRef::as_ref) {
        procs.push(
            spawn_search_exact(pkg)
                .wrap_err_with(|| format!("Failed to spawn search for {pkg:?}."))?,
        );
    }

    log::debug!("Waiting for each search child processes to finish...");
    for (pkg, proc) in pkgs.iter().map(AsRef::as_ref).zip(procs.into_iter()) {
        vers.insert(
            pkg.to_owned(),
            finish_search_exact(pkg, proc)
                .wrap_err_with(|| format!("Failed to finish search for {pkg:?}."))?,
        );
    }

    Ok(vers)
}

/// Runs `cargo config get` with the given configuration key and returns the
/// collected string value.
pub fn config_get(key: &str) -> Result<String> {
    let mut cmd = Command::new(env_var()?);
    // HACK: get access to nightly features.
    // FIXME: remove when `config` gets stabilized.
    cmd.env("RUSTC_BOOTSTRAP", "1");
    cmd.args([
        "--color=never",
        "-Zunstable-options",
        "config",
        "get",
        "--format=json-value",
        "--",
        key,
    ]);

    log_cmd(&cmd);
    let out = cmd
        .output()
        .wrap_err("Failed to execute Cargo.")
        .note("This can happen for many reasons, but it should not happen easily at this point.")
        .suggestion("Read the underlying error message.")?;
    out.status.success().then_some(()).ok_or_else(|| {
        eyre!(
            "Command failed with status: {:#?} and stderr: {:#?}.",
            out.status,
            String::from_utf8(out.stderr),
        )
    })?;

    let out_str = String::from_utf8(out.stdout)
        .wrap_err("Failed to decode the standard output.")
        .note("This really should not happen.")
        .suggestion(crate::OPEN_ISSUE_MSG)?;
    log::trace!("Got: {out_str:#?}.");
    Ok(out_str.trim_end().trim_matches('"').to_owned())
}

/// Wrapper around [`home::cargo_home`] with additional reporting context.
pub fn home() -> Result<PathBuf> {
    home::cargo_home()
        .wrap_err("Failed to get the path to Cargo's home.")
        .suggestion("Check the current directory's permissions and your user OS configuration.")
}

/// Fetches the `CARGO` variable from the environment.
fn env_var() -> Result<String> {
    env::var("CARGO")
        .wrap_err("Failed to get the `CARGO` environment variable.")
        .note("This should not happen easily as it is set by Cargo.")
        .suggestion("Run the command through Cargo as intended.")
}

/// Heuristically detects whether the current execution context seems like a
/// testing one or not.
///
/// It currently uses some environment variable that `cargo-test-support`'s
/// `cargo_test` macro sets for invoked Cargo instances. Set
/// `__THIS_IS_REALLY_TESTING_BUT_HUSH` to any value to make this always return
/// `false`. `version_checking` should be `true` when calling this from the
/// `cargo search` version checking.
fn context_seems_testing(version_checking: bool) -> bool {
    (version_checking || env::var_os("__THIS_IS_REALLY_TESTING_BUT_HUSH").is_none())
        && env::var_os("__CARGO_TEST_ROOT").is_some_and(|var| {
            let path = PathBuf::from(var);
            path.is_absolute() && path.is_dir()
        })
}

/// Logs the program and arguments of the given command to DEBUG.
fn log_cmd(cmd: &Command) {
    log::debug!(
        "Running {:#?} with arguments {:#?}...",
        cmd.get_program().to_string_lossy(),
        cmd.get_args()
            .map(OsStr::to_string_lossy)
            .collect::<Vec<_>>(),
    );
}

#[cfg(test)]
mod tests {
    use std::sync::{LazyLock, Mutex};

    use cargo_test_macro::cargo_test;

    use super::*;
    use crate::testing;

    const SELF: &str = clap::crate_name!();
    const NONE: &str = "azertyuiop-qsdfghjklm_wxcvbn";
    static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

    #[cargo_test]
    fn test_singlethreaded_searchspawn_self_isok() -> Result<()> {
        let _lk = LOCK.lock();
        let _reg = testing::init_registry();
        testing::fake_publish(SELF, "0.0.0");
        testing::set_env();

        let proc = spawn_search_exact(SELF)?;
        assert_ne!(proc.id(), 0);
        assert!(proc.stdin.is_none());
        assert!(proc.stderr.is_none());
        assert!(proc.stdout.is_some());

        let res = proc.wait_with_output()?;
        assert!(res.status.success());
        assert!(String::from_utf8(res.stdout)?.lines().count() > 0);

        Ok(())
    }

    #[cargo_test]
    fn test_singlethreaded_searchfinish_self_isok() -> Result<()> {
        let _lk = LOCK.lock();
        let _reg = testing::init_registry();
        testing::fake_publish(SELF, "0.0.0");
        testing::set_env();

        assert!(
            finish_search_exact(SELF, spawn_search_exact(SELF)?)?
                <= clap::crate_version!().parse()?
        );
        Ok(())
    }

    #[cargo_test]
    fn test_singlethreaded_searchspawn_none_isok() -> Result<()> {
        let _lk = LOCK.lock();
        let _reg = testing::init_registry();
        testing::set_env();

        let proc = spawn_search_exact(NONE)?;
        assert_ne!(proc.id(), 0);
        assert!(proc.stdin.is_none());
        assert!(proc.stderr.is_none());
        assert!(proc.stdout.is_some());

        let res = proc.wait_with_output()?;
        assert!(res.status.success());
        assert_eq!(String::from_utf8(res.stdout)?.lines().count(), 0);

        Ok(())
    }

    #[cargo_test]
    fn test_singlethreaded_searchfinish_none_iserr() -> Result<()> {
        let _lk = LOCK.lock();
        let _reg = testing::init_registry();
        testing::set_env();

        assert!(finish_search_exact(NONE, spawn_search_exact(NONE)?).is_err());
        Ok(())
    }

    #[cargo_test]
    fn test_singlethreaded_searchall_selfandothers_isok() -> Result<()> {
        let _lk = LOCK.lock();
        let _reg = testing::init_registry();
        testing::fake_publish_all([
            (SELF, clap::crate_version!()),
            ("cargo-expand", "1.0.79"),
            ("cargo-tarpaulin", "0.27.3"),
            ("bat", "0.24.0"),
        ]);
        testing::set_env();

        for (pkg, ver) in search_exact_all(&[SELF, "cargo-expand", "cargo-tarpaulin", "bat"])? {
            assert_eq!(
                ver,
                match &*pkg {
                    SELF => clap::crate_version!(),
                    "cargo-expand" => "1.0.79",
                    "cargo-tarpaulin" => "0.27.3",
                    "bat" => "0.24.0",
                    pkg => eyre::bail!("Unexpected package: {pkg:?}"),
                }
                .parse()?,
            );
        }
        Ok(())
    }

    #[cargo_test]
    fn test_singlethreaded_searchall_none_iserr() {
        let _lk = LOCK.lock();
        let _reg = testing::init_registry();
        testing::set_env();

        assert!(search_exact_all(&[NONE]).is_err());
    }

    #[ignore = "Long and online test."]
    #[cargo_test]
    fn test_singlethreaded_binstall() {
        let _lk = LOCK.lock();
        let _reg = testing::init_registry();
        testing::fake_install_all([
            (SELF, clap::crate_version!(), false),
            ("bat", "0.23.0", false),
        ]);
        testing::fake_publish_all([(SELF, clap::crate_version!()), ("bat", "0.24.0")]);
        testing::set_env();

        binstall(
            "bat",
            &DetailedPackageReq {
                version: "0.24.0".parse().unwrap(),
                ..Default::default()
            },
            false,
            false,
            0,
        )
        .unwrap();
    }

    #[cargo_test]
    fn test_singlethreaded_binstallisavailable_yes() {
        let _lk = LOCK.lock();
        testing::fake_install("cargo-binstall", "0.0.0", false);
        testing::set_env();

        assert!(binstall_is_available(
            &["cargo-binstall".to_owned()].into_iter().collect()
        ));
    }

    #[ignore = "Fails if not actually installed."]
    #[cargo_test]
    fn test_singlethreaded_binstallisavailable_emptyset_yes() {
        let _lk = LOCK.lock();
        testing::fake_install("cargo-binstall", "0.0.0", false);
        testing::set_env();

        assert!(binstall_is_available(&BTreeSet::new()));
    }

    #[cargo_test]
    fn test_singlethreaded_binstallisavailable_no() {
        let _lk = LOCK.lock();
        testing::fake_install("abc", "0.0.0", false);
        testing::set_env();

        assert!(!binstall_is_available(
            &["abc".to_owned()].into_iter().collect()
        ));
    }

    #[ignore = "Fails if actually installed."]
    #[cargo_test]
    fn test_singlethreaded_binstallisavailable_emptyset_no() {
        let _lk = LOCK.lock();
        testing::fake_install("abc", "0.0.0", false);
        testing::set_env();

        assert!(!binstall_is_available(&BTreeSet::new()));
    }

    #[ignore = "Fails if not actually installed in the precise version."]
    #[cargo_test]
    fn test_singlethreaded_binstallversion() {
        let _lk = LOCK.lock();
        testing::fake_install("cargo-binstall", "1.10.17", false);
        testing::set_env();

        assert_eq!(binstall_version().unwrap(), "1.10.17".parse().unwrap());
    }

    #[test]
    fn test_configget_withenv_installroot() -> Result<()> {
        let _lk = LOCK.lock();
        // SAFETY: mutually-exclusive test execution.
        unsafe { env::set_var("CARGO_INSTALL_ROOT", "/tmp") };
        assert_eq!(config_get("install.root")?, "/tmp");
        // SAFETY: mutually-exclusive test execution.
        unsafe { env::remove_var("CARGO_INSTALL_ROOT") };
        Ok(())
    }
}