nextest-runner 0.114.0

Core runner logic for cargo nextest.
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
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
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Self-updates for nextest.

use crate::{
    errors::{UpdateError, UpdateVersionParseError},
    helpers::ThemeCharacters,
};
use camino::{Utf8Path, Utf8PathBuf};
use indicatif::{ProgressBar, ProgressStyle};
use mukti_metadata::{
    DigestAlgorithm, MuktiProject, MuktiReleasesJson, ReleaseLocation, ReleaseStatus,
};
use owo_colors::{OwoColorize, Style};
use self_update::{ArchiveKind, Compression, Extract};
use semver::{Version, VersionReq};
use serde::Deserialize;
use sha2::{Digest, Sha256};
#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))]
use std::sync::OnceLock;
use std::{
    fs,
    io::{self, BufRead, BufReader, BufWriter, Write as _},
    str::FromStr,
    time::Duration,
};
use target_spec::Platform;
use tracing::{debug, info, warn};

/// Update backend using mukti
#[derive(Clone, Debug)]
pub struct MuktiBackend {
    /// The URL to download releases from
    pub url: String,

    /// The package name.
    pub package_name: String,
}

impl MuktiBackend {
    /// Fetch releases.
    pub fn fetch_releases(&self, current_version: Version) -> Result<NextestReleases, UpdateError> {
        info!(target: "nextest-runner::update", "checking for self-updates");
        // Is the URL a file that exists on disk? If so, use that.
        let as_path = Utf8Path::new(&self.url);
        let releases_buf = if as_path.exists() {
            fs::read(as_path).map_err(|error| UpdateError::ReadLocalMetadata {
                path: as_path.to_owned(),
                error,
            })?
        } else {
            let agent = ureq_agent();
            agent
                .get(&self.url)
                .call()
                .map_err(UpdateError::Http)?
                .into_body()
                // The default read_to_vec() limit is 10 MiB, which the
                // releases JSON could plausibly exceed as releases
                // accumulate. Use a 64 MiB limit instead.
                .into_with_config()
                .limit(64 * 1024 * 1024)
                .read_to_vec()
                .map_err(UpdateError::Http)?
        };

        let mut releases_json: MuktiReleasesJson =
            serde_json::from_slice(&releases_buf).map_err(UpdateError::ReleaseMetadataDe)?;

        let project = match releases_json.projects.remove(&self.package_name) {
            Some(project) => project,
            None => {
                return Err(UpdateError::MuktiProjectNotFound {
                    not_found: self.package_name.clone(),
                    known: releases_json.projects.keys().cloned().collect(),
                });
            }
        };

        NextestReleases::new(&self.package_name, project, current_version)
    }
}

/// Release info for nextest.
///
/// Returned by [`MuktiBackend::fetch_releases`].
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct NextestReleases {
    /// The package name.
    pub package_name: String,

    /// The mukti project.
    pub project: MuktiProject,

    /// The currently running version.
    pub current_version: Version,

    /// The install path.
    pub bin_install_path: Utf8PathBuf,
}

impl NextestReleases {
    fn new(
        package_name: &str,
        project: MuktiProject,
        current_version: Version,
    ) -> Result<Self, UpdateError> {
        let bin_install_path = std::env::current_exe()
            .and_then(|exe| {
                Utf8PathBuf::try_from(exe)
                    .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
            })
            .map_err(UpdateError::CurrentExe)?;

        Ok(Self {
            package_name: package_name.to_owned(),
            project,
            current_version,
            bin_install_path,
        })
    }

    /// Checks for whether an update should be performed.
    pub fn check<'a>(
        &'a self,
        version_req: &UpdateVersionReq,
        force: bool,
        bin_path_in_archive: &'a Utf8Path,
        perform_setup_fn: impl FnOnce(&Version) -> bool,
    ) -> Result<CheckStatus<'a>, UpdateError> {
        let (version, version_data) = self.resolve_version(version_req)?;
        debug!(
            target: "nextest-runner::update",
            "current version is {}, update version is {version}",
            self.current_version,
        );

        if &self.current_version == version && !force {
            return Ok(CheckStatus::AlreadyOnRequested(version.clone()));
        }
        if &self.current_version > version && !force {
            return Ok(CheckStatus::DowngradeNotAllowed {
                current_version: self.current_version.clone(),
                requested: version.clone(),
            });
        }

        // Look for data for this platform.
        let triple = self.target_triple();
        debug!(target: "nextest-runner::update", "target triple: {triple}");

        let location = version_data
            .locations
            .iter()
            .find(|&data| data.format == TAR_GZ_SUFFIX && data.target == triple)
            .ok_or_else(|| {
                let known_triples = version_data
                    .locations
                    .iter()
                    .filter(|data| data.format == TAR_GZ_SUFFIX)
                    .map(|data| data.target.clone())
                    .collect();
                UpdateError::NoTargetData {
                    version: version.clone(),
                    triple,
                    known_triples,
                }
            })?;

        let force_disable_setup = version_data
            .metadata
            .is_some_and(|metadata| metadata.force_disable_setup);
        let perform_setup = !force_disable_setup && perform_setup_fn(version);

        Ok(CheckStatus::Success(MuktiUpdateContext {
            context: self,
            version: version.clone(),
            location: location.clone(),
            bin_path_in_archive,
            perform_setup,
        }))
    }

    // ---
    // Helper methods
    // ---

    fn resolve_version(
        &self,
        version_req: &UpdateVersionReq,
    ) -> Result<(&Version, ReleaseVersionData), UpdateError> {
        match version_req {
            UpdateVersionReq::Latest => {
                // Get the latest stable (non-prerelease) version.
                let (version, release_data) = self
                    .project
                    .get_latest_matching(&VersionReq::STAR)
                    .ok_or(UpdateError::NoStableVersion)?;
                Ok((version, self.parse_release_data(release_data)))
            }
            UpdateVersionReq::Version(update_version) => self.get_version_data(update_version),
            UpdateVersionReq::LatestPrerelease(kind) => self.get_latest_prerelease(*kind),
        }
    }

    fn get_version_data(
        &self,
        version: &UpdateVersion,
    ) -> Result<(&Version, ReleaseVersionData), UpdateError> {
        let (version, release_data) = match version {
            UpdateVersion::Exact(version) => {
                self.project.get_version_data(version).ok_or_else(|| {
                    let known = self
                        .project
                        .all_versions()
                        .map(|(v, release_data)| (v.clone(), release_data.status))
                        .collect();
                    UpdateError::VersionNotFound {
                        version: version.clone(),
                        known,
                    }
                })?
            }
            UpdateVersion::Req(req) => self
                .project
                .get_latest_matching(req)
                .ok_or_else(|| UpdateError::NoMatchForVersionReq { req: req.clone() })?,
        };

        Ok((version, self.parse_release_data(release_data)))
    }

    fn get_latest_prerelease(
        &self,
        kind: PrereleaseKind,
    ) -> Result<(&Version, ReleaseVersionData), UpdateError> {
        // all_versions() returns versions in descending order (most recent first).
        for (version, release_data) in self.project.all_versions() {
            if release_data.status == ReleaseStatus::Active && kind.matches(version) {
                return Ok((version, self.parse_release_data(release_data)));
            }
        }

        Err(UpdateError::NoVersionForPrereleaseKind { kind })
    }

    fn parse_release_data(
        &self,
        release_data: &mukti_metadata::ReleaseVersionData,
    ) -> ReleaseVersionData {
        // Parse the metadata into our custom format.
        let metadata = if release_data.metadata.is_null() {
            None
        } else {
            // Attempt to parse the metadata.
            match serde_json::from_value::<NextestReleaseMetadata>(release_data.metadata.clone()) {
                Ok(metadata) => Some(metadata),
                Err(error) => {
                    warn!(
                        target: "nextest-runner::update",
                        "failed to parse custom release metadata: {error}",
                    );
                    None
                }
            }
        };

        ReleaseVersionData {
            release_url: release_data.release_url.clone(),
            status: release_data.status,
            locations: release_data.locations.clone(),
            metadata,
        }
    }

    fn target_triple(&self) -> String {
        // In this case, use the build target, *not* `rustc -vV` output. This
        // ensures that e.g. musl binary updates continue to use the musl
        // target.
        let current = Platform::build_target().expect("build target could not be detected");
        let triple_str = current.triple_str();
        if triple_str.ends_with("-apple-darwin") {
            // Nextest builds a universal binary for Mac.
            "universal-apple-darwin".to_owned()
        } else {
            triple_str.to_owned()
        }
    }
}

/// Like `mukti-metadata`'s `ReleaseVersionData`, except with parsed metadata.
#[derive(Clone, Debug)]
pub struct ReleaseVersionData {
    /// Canonical URL for this release
    pub release_url: String,

    /// The status of a release
    pub status: ReleaseStatus,

    /// Release locations
    pub locations: Vec<ReleaseLocation>,

    /// Custom domain-specific information stored about this release.
    pub metadata: Option<NextestReleaseMetadata>,
}

/// Nextest-specific release metadata.
#[derive(Clone, Debug, Deserialize)]
pub struct NextestReleaseMetadata {
    /// Whether to force disable `cargo nextest self setup` for this version.
    #[serde(default)]
    pub force_disable_setup: bool,
}

/// The result of [`NextestReleases::check`].
#[derive(Clone, Debug)]
pub enum CheckStatus<'a> {
    /// The current version is the same as the requested version.
    AlreadyOnRequested(Version),

    /// A downgrade was requested but wasn't allowed.
    DowngradeNotAllowed {
        /// The currently running version.
        current_version: Version,

        /// The requested version.
        requested: Version,
    },

    /// All checks were performed successfully and we are ready to update.
    Success(MuktiUpdateContext<'a>),
}

/// Display styles for update progress output.
#[derive(Clone, Debug, Default)]
pub struct UpdateDisplayStyles {
    /// Style for the progress bar prefix (e.g. "Downloading").
    pub progress_prefix: Style,

    /// Theme characters for the progress bar (ASCII or Unicode).
    pub theme_characters: ThemeCharacters,
}

impl UpdateDisplayStyles {
    /// Creates colorized styles.
    pub fn colorize(&mut self) {
        self.progress_prefix = Style::new().green().bold();
    }
}

/// Context for an update.
///
/// Returned as part of the `Success` variant of [`CheckStatus`].
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct MuktiUpdateContext<'a> {
    /// The `MuktiReleases` context.
    pub context: &'a NextestReleases,

    /// The version being updated to.
    pub version: Version,

    /// The target-specific release location from which the package will be downloaded.
    pub location: ReleaseLocation,

    /// The path to the binary within the archive.
    pub bin_path_in_archive: &'a Utf8Path,

    /// Whether to run `cargo nextest self setup` as part of the update.
    pub perform_setup: bool,
}

impl MuktiUpdateContext<'_> {
    /// Performs the update.
    pub fn do_update(&self, styles: &UpdateDisplayStyles) -> Result<(), UpdateError> {
        // This method is adapted from self_update's update_extended.

        let tmp_dir_parent = self.context.bin_install_path.parent().ok_or_else(|| {
            UpdateError::CurrentExe(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "parent directory of current exe `{}` could not be determined",
                    self.context.bin_install_path
                ),
            ))
        })?;
        let tmp_backup_dir_prefix = format!("__{}_backup", self.context.package_name);
        let tmp_backup_filename = tmp_backup_dir_prefix.clone();

        if cfg!(windows) {
            // Windows executables can not be removed while they are running, which prevents clean up
            // of the temporary directory by the `tempfile` crate after we move the running executable
            // into it during an update. We clean up any previously created temporary directories here.
            // Ignore errors during cleanup since this is not critical for completing the update.
            let _ = cleanup_backup_temp_directories(
                tmp_dir_parent,
                &tmp_backup_dir_prefix,
                &tmp_backup_filename,
            );
        }

        let tmp_archive_dir_prefix = format!("{}_download", self.context.package_name);
        let tmp_archive_dir = camino_tempfile::Builder::new()
            .prefix(&tmp_archive_dir_prefix)
            .tempdir_in(tmp_dir_parent)
            .map_err(|error| UpdateError::TempDirCreate {
                location: tmp_dir_parent.to_owned(),
                error,
            })?;
        let tmp_dir_path: &Utf8Path = tmp_archive_dir.path();
        let tmp_archive_path =
            tmp_dir_path.join(format!("{}.{TAR_GZ_SUFFIX}", self.context.package_name));
        let tmp_archive = fs::File::create(&tmp_archive_path).map_err(|error| {
            UpdateError::TempArchiveCreate {
                archive_path: tmp_archive_path.clone(),
                error,
            }
        })?;
        let mut tmp_archive_buf = BufWriter::new(tmp_archive);

        let agent = ureq_agent();
        let resp = agent
            .get(&self.location.url)
            .header(http::header::ACCEPT.as_str(), "application/octet-stream")
            .call()
            .map_err(UpdateError::Http)?;

        let content_length: Option<u64> =
            match resp.headers().get(http::header::CONTENT_LENGTH.as_str()) {
                Some(v) => {
                    let s = v.to_str().map_err(|_| UpdateError::ContentLengthInvalid {
                        value: format!("{v:?}"),
                    })?;
                    let len = s
                        .parse::<u64>()
                        .map_err(|_| UpdateError::ContentLengthInvalid {
                            value: s.to_owned(),
                        })?;
                    Some(len)
                }
                None => None,
            };

        // Stream the response body to the archive file with a progress bar.
        // into_reader() has no size limit, unlike read_to_vec(). This is
        // intentional: release archives are ~10 MiB as of March 2026 and
        // are streamed to a temporary file via tmp_archive_buf above,
        // not buffered entirely in memory. The SHA-256 checksum verified
        // later guards against corruption or truncation.
        let mut src = BufReader::new(resp.into_body().into_reader());
        let prefix = format!("{}", "Downloading".style(styles.progress_prefix));
        let progress_bar = match content_length {
            Some(size) => {
                let pb = ProgressBar::new(size);
                pb.set_style(
                    ProgressStyle::default_bar()
                        .template(
                            "  {prefix:>10} [{elapsed_precise:>9}] {wide_bar} \
                             {bytes:>9}/{total_bytes:>9}",
                        )
                        .expect("valid progress bar template")
                        .progress_chars(styles.theme_characters.progress_chars()),
                );
                pb
            }
            None => {
                let pb = ProgressBar::new_spinner();
                pb.set_style(
                    ProgressStyle::default_spinner()
                        .template("  {prefix:>10} [{elapsed_precise:>9}] {bytes}")
                        .expect("valid progress spinner template"),
                );
                pb
            }
        };
        progress_bar.set_prefix(prefix);

        let mut downloaded: u64 = 0;
        loop {
            let n = {
                let buf = src.fill_buf().map_err(UpdateError::HttpBody)?;
                tmp_archive_buf
                    .write_all(buf)
                    .map_err(|error| UpdateError::TempArchiveWrite {
                        archive_path: tmp_archive_path.clone(),
                        error,
                    })?;
                buf.len()
            };
            if n == 0 {
                break;
            }
            src.consume(n);
            downloaded += n as u64;
            progress_bar.set_position(downloaded);
        }
        progress_bar.finish();

        // Verify that we received the expected number of bytes.
        if let Some(expected) = content_length
            && downloaded != expected
        {
            return Err(UpdateError::ContentLengthMismatch {
                expected,
                actual: downloaded,
            });
        }

        debug!(target: "nextest-runner::update", "downloaded to {tmp_archive_path}");

        let tmp_archive =
            tmp_archive_buf
                .into_inner()
                .map_err(|error| UpdateError::TempArchiveWrite {
                    archive_path: tmp_archive_path.clone(),
                    error: error.into_error(),
                })?;
        tmp_archive
            .sync_all()
            .map_err(|error| UpdateError::TempArchiveWrite {
                archive_path: tmp_archive_path.clone(),
                error,
            })?;
        std::mem::drop(tmp_archive);

        // Verify the checksum of the downloaded file if available.
        let mut hasher = Sha256::default();
        // Just read the file into memory for now -- it would be nice to have an
        // incremental hasher that updates the hash as it's being downloaded,
        // but it's not critical since our archives are quite small.
        let mut tmp_archive =
            fs::File::open(&tmp_archive_path).map_err(|error| UpdateError::TempArchiveRead {
                archive_path: tmp_archive_path.clone(),
                error,
            })?;
        io::copy(&mut tmp_archive, &mut hasher).map_err(|error| UpdateError::TempArchiveRead {
            archive_path: tmp_archive_path.clone(),
            error,
        })?;
        let hash = hasher.finalize();
        let hash_str = hex::encode(hash);

        match self.location.checksums.get(&DigestAlgorithm::SHA256) {
            Some(checksum) => {
                if checksum.0 != hash_str {
                    return Err(UpdateError::ChecksumMismatch {
                        expected: checksum.0.clone(),
                        actual: hash_str,
                    });
                }
                debug!(target: "nextest-runner::update", "SHA-256 checksum verified: {hash_str}");
            }
            None => {
                warn!(target: "nextest-runner::update", "unable to verify SHA-256 checksum of downloaded archive ({hash_str})");
            }
        }

        // Now extract data from this archive.
        Extract::from_source(tmp_archive_path.as_std_path())
            .archive(ArchiveKind::Tar(Some(Compression::Gz)))
            .extract_file(
                tmp_archive_dir.path().as_std_path(),
                self.bin_path_in_archive,
            )
            .map_err(UpdateError::SelfUpdate)?;

        // Since we're currently restricted to .tar.gz which carries metadata with it, there's no
        // need to make this file executable.

        let new_exe = tmp_dir_path.join(self.bin_path_in_archive);
        debug!(target: "nextest-runner::update", "extracted to {new_exe}, replacing existing binary");

        let tmp_backup_dir = camino_tempfile::Builder::new()
            .prefix(&tmp_backup_dir_prefix)
            .tempdir_in(tmp_dir_parent)
            .map_err(|error| UpdateError::TempDirCreate {
                location: tmp_dir_parent.to_owned(),
                error,
            })?;

        let tmp_backup_dir_path: &Utf8Path = tmp_backup_dir.path();
        let tmp_file_path = tmp_backup_dir_path.join(&tmp_backup_filename);

        Move::from_source(&new_exe)
            .replace_using_temp(&tmp_file_path)
            .to_dest(&self.context.bin_install_path)?;

        // Finally, run `cargo nextest self setup` if requested.
        if self.perform_setup {
            info!(target: "nextest-runner::update", "running `cargo nextest self setup`");
            let mut cmd = std::process::Command::new(&self.context.bin_install_path);
            cmd.args(["nextest", "self", "setup", "--source", "self-update"]);
            let status = cmd.status().map_err(UpdateError::SelfSetup)?;
            if !status.success() {
                return Err(UpdateError::SelfSetup(io::Error::other(format!(
                    "`cargo nextest self setup` failed with exit code {}",
                    status
                        .code()
                        .map_or("(unknown)".to_owned(), |c| c.to_string())
                ))));
            }
        }

        Ok(())
    }
}

/// Moves a file from the given path to the specified destination.
///
/// `source` and `dest` must be on the same filesystem.
/// If `replace_using_temp` is specified, the destination file will be
/// replaced using the given temporary path.
/// If the existing `dest` file is a currently running long running program,
/// `replace_using_temp` may run into errors cleaning up the temp dir.
/// If that's the case for your use-case, consider not specifying a temp dir to use.
///
/// * Errors:
///     * Io - copying / renaming
#[derive(Debug)]
struct Move<'a> {
    source: &'a Utf8Path,
    temp: Option<&'a Utf8Path>,
}
impl<'a> Move<'a> {
    /// Specify source file
    pub fn from_source(source: &'a Utf8Path) -> Move<'a> {
        Self { source, temp: None }
    }

    /// If specified and the destination file already exists, the "destination"
    /// file will be moved to the given temporary location before the "source"
    /// file is moved to the "destination" file.
    ///
    /// In the event of an `io` error while renaming "source" to "destination",
    /// the temporary file will be moved back to "destination".
    ///
    /// The `temp` dir must be explicitly provided since `rename` operations require
    /// files to live on the same filesystem.
    pub fn replace_using_temp(&mut self, temp: &'a Utf8Path) -> &mut Self {
        self.temp = Some(temp);
        self
    }

    /// Move source file to specified destination
    pub fn to_dest(&self, dest: &Utf8Path) -> Result<(), UpdateError> {
        match self.temp {
            None => Self::fs_rename(self.source, dest),
            Some(temp) => {
                if dest.exists() {
                    // Move the existing dest to a temp location so we can move it
                    // back it there's an error. If the existing `dest` file is a
                    // long running program, this may prevent the temp dir from
                    // being cleaned up.
                    Self::fs_rename(dest, temp)?;
                    if let Err(e) = Self::fs_rename(self.source, dest) {
                        Self::fs_rename(temp, dest)?;
                        return Err(e);
                    }
                } else {
                    Self::fs_rename(self.source, dest)?;
                }
                Ok(())
            }
        }
    }

    // ---
    // Helper methods
    // ---

    fn fs_rename(source: &Utf8Path, dest: &Utf8Path) -> Result<(), UpdateError> {
        fs::rename(source, dest).map_err(|error| UpdateError::FsRename {
            source: source.to_owned(),
            dest: dest.to_owned(),
            error,
        })
    }
}

fn cleanup_backup_temp_directories(
    tmp_dir_parent: &Utf8Path,
    tmp_dir_prefix: &str,
    expected_tmp_filename: &str,
) -> io::Result<()> {
    for entry in fs::read_dir(tmp_dir_parent)? {
        let entry = entry?;
        let tmp_dir_name = if let Ok(tmp_dir_name) = entry.file_name().into_string() {
            tmp_dir_name
        } else {
            continue;
        };

        // For safety, check that the temporary directory contains only the expected backup
        // binary file before removing. If subdirectories or other files exist then the user
        // is using the temp directory for something else. This is unlikely, but we should
        // be careful with `fs::remove_dir_all`.
        let is_expected_tmp_file = |tmp_file_entry: std::io::Result<fs::DirEntry>| {
            tmp_file_entry
                .ok()
                .filter(|e| e.file_name() == expected_tmp_filename)
                .is_some()
        };

        if tmp_dir_name.starts_with(tmp_dir_prefix)
            && fs::read_dir(entry.path())?.all(is_expected_tmp_file)
        {
            fs::remove_dir_all(entry.path())?;
        }
    }
    Ok(())
}

/// Returns a ureq agent configured with rustls and the aws-lc-rs crypto
/// provider.
///
/// On RISC-V, rustls/aws-lc-rs aren't available; see the RISC-V variant
/// below.
#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))]
fn ureq_agent() -> ureq::Agent {
    // Install aws-lc-rs as the default rustls crypto provider. The OnceLock
    // ensures we only attempt this once; if it's already set (by us or someone
    // else), we log and move on.
    static PROVIDER_INSTALLED: OnceLock<()> = OnceLock::new();
    PROVIDER_INSTALLED.get_or_init(|| {
        if rustls::crypto::CryptoProvider::install_default(
            rustls::crypto::aws_lc_rs::default_provider(),
        )
        .is_err()
        {
            warn!(
                target: "nextest-runner::update",
                "a rustls crypto provider was already installed; \
                 using the existing provider",
            );
        }
    });

    ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            // Set a connect timeout to avoid hanging on unreachable hosts.
            // No global timeout: binary downloads can be large on slow
            // connections, and the progress bar keeps the user informed.
            .timeout_connect(Some(CONNECT_TIMEOUT))
            .tls_config(
                ureq::tls::TlsConfig::builder()
                    .provider(ureq::tls::TlsProvider::Rustls)
                    .build(),
            )
            .build(),
    )
}

/// Returns a ureq agent configured with native-tls.
///
/// On RISC-V, rustls/aws-lc-rs aren't available (see
/// <https://github.com/nextest-rs/nextest/issues/820>), so native-tls is used
/// instead.
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
fn ureq_agent() -> ureq::Agent {
    ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(CONNECT_TIMEOUT))
            .tls_config(
                ureq::tls::TlsConfig::builder()
                    .provider(ureq::tls::TlsProvider::NativeTls)
                    .build(),
            )
            .build(),
    )
}

/// Connect timeout for HTTP requests. Matches reqwest's old default of 30
/// seconds, which self_update 0.42.0 relied on implicitly.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);

const TAR_GZ_SUFFIX: &str = "tar.gz";

/// Represents the user's requested version for an update.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UpdateVersionReq {
    /// Update to the latest stable (non-prerelease) version.
    Latest,

    /// Update to a specific version or version requirement.
    Version(UpdateVersion),

    /// Update to the latest prerelease of the given kind.
    LatestPrerelease(PrereleaseKind),
}

/// The kind of prerelease to look for.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PrereleaseKind {
    /// Beta channel (includes beta `-b.N`, RC `-rc.N`, and stable versions).
    Beta,

    /// Release candidate channel (`-rc.N` and stable versions).
    Rc,
}

impl PrereleaseKind {
    /// Returns true if this version is acceptable for this prerelease kind.
    ///
    /// `Beta` accepts stable, RC, or beta versions.
    ///
    /// `Rc` accepts stable or RC versions (not beta).
    pub fn matches(&self, version: &Version) -> bool {
        // Stable versions are always acceptable.
        if version.pre.is_empty() {
            return true;
        }
        let pre_str = version.pre.as_str();
        match self {
            // Beta accepts everything: stable, -b.N, or -rc.N.
            PrereleaseKind::Beta => pre_str.starts_with("b.") || pre_str.starts_with("rc."),
            // RC accepts stable or -rc.N (not -b.N).
            PrereleaseKind::Rc => pre_str.starts_with("rc."),
        }
    }

    /// Returns a description of this prerelease kind for user-facing messages.
    pub fn description(&self) -> &'static str {
        match self {
            PrereleaseKind::Beta => "beta or RC",
            PrereleaseKind::Rc => "RC",
        }
    }
}

/// Represents the version this project is being updated to.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UpdateVersion {
    /// Update to this exact version.
    Exact(Version),

    /// Update to the latest non-pre-release, non-yanked version matching this [`VersionReq`].
    Req(VersionReq),
}

/// Parses x.y.z as if it were =x.y.z, and provides error messages in the case of invalid
/// values.
impl FromStr for UpdateVersion {
    type Err = UpdateVersionParseError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        // Adapted from Cargo's source:
        // https://github.com/rust-lang/cargo/blob/6b8e1922261bbed1894bf40069fb2d5dc8d62fb0/src/cargo/ops/cargo_install.rs#L760-L806

        // If the version begins with character <, >, =, ^, ~ parse it as a
        // version range, otherwise parse it as a specific version

        if input == "latest" {
            return Ok(UpdateVersion::Req(VersionReq::STAR));
        }

        let first = input
            .chars()
            .next()
            .ok_or(UpdateVersionParseError::EmptyString)?;

        let is_req = "<>=^~".contains(first) || input.contains('*');
        if is_req {
            match input.parse::<VersionReq>() {
                Ok(v) => Ok(Self::Req(v)),
                Err(error) => Err(UpdateVersionParseError::InvalidVersionReq {
                    input: input.to_owned(),
                    error,
                }),
            }
        } else {
            match input.parse::<Version>() {
                Ok(v) => Ok(Self::Exact(v)),
                Err(error) => Err(UpdateVersionParseError::InvalidVersion {
                    input: input.to_owned(),
                    error,
                }),
            }
        }
    }
}