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

//! Reuse builds performed earlier.
//!
//! Nextest allows users to reuse builds done on one machine. This module contains support for that.
//!
//! The main data structures here are [`ReuseBuildInfo`] and [`PathMapper`].

use crate::{
    errors::{
        ArchiveExtractError, ArchiveReadError, MetadataMaterializeError, PathMapperConstructError,
        PathMapperConstructKind,
    },
    list::BinaryList,
    platform::PlatformLibdir,
};
use camino::{Utf8Path, Utf8PathBuf};
use camino_tempfile::Utf8TempDir;
use guppy::graph::PackageGraph;
use nextest_metadata::{BinaryListSummary, PlatformLibdirUnavailable};
use std::{fmt, fs, io, sync::Arc};
use tracing::debug;

mod archive_reporter;
mod archiver;
mod unarchiver;

pub use archive_reporter::*;
pub use archiver::*;
pub use unarchiver::*;

/// The name of the file in which Cargo metadata is stored.
pub const CARGO_METADATA_FILE_NAME: &str = "target/nextest/cargo-metadata.json";

/// The name of the file in which binaries metadata is stored.
pub const BINARIES_METADATA_FILE_NAME: &str = "target/nextest/binaries-metadata.json";

/// The name of the directory in which libdirs are stored.
pub const LIBDIRS_BASE_DIR: &str = "target/nextest/libdirs";

/// Reuse build information.
#[derive(Debug, Default)]
pub struct ReuseBuildInfo {
    /// Cargo metadata and remapping for the target directory.
    pub cargo_metadata: Option<MetadataWithRemap<ReusedCargoMetadata>>,

    /// Binaries metadata JSON and remapping for the target directory.
    pub binaries_metadata: Option<MetadataWithRemap<ReusedBinaryList>>,

    /// Remapping for the build directory.
    ///
    /// When `build.build-dir` is set, the build directory differs from the
    /// target directory. This remap handles that case. When not set, the build
    /// directory remap falls back to the target directory remap.
    pub build_dir_remap: Option<Utf8PathBuf>,

    /// A remapper for libdirs.
    pub libdir_mapper: LibdirMapper,

    /// Optional temporary directory used for cleanup.
    _temp_dir: Option<Utf8TempDir>,
}

impl ReuseBuildInfo {
    /// Creates a new [`ReuseBuildInfo`] from the given cargo and binaries metadata information.
    pub fn new(
        cargo_metadata: Option<MetadataWithRemap<ReusedCargoMetadata>>,
        binaries_metadata: Option<MetadataWithRemap<ReusedBinaryList>>,
        build_dir_remap: Option<Utf8PathBuf>,
        // TODO: accept libdir_mapper as an argument, as well
    ) -> Self {
        Self {
            cargo_metadata,
            binaries_metadata,
            build_dir_remap,
            libdir_mapper: LibdirMapper::default(),
            _temp_dir: None,
        }
    }

    /// Extracts an archive and constructs a [`ReuseBuildInfo`] from it.
    pub fn extract_archive<F>(
        archive_file: &Utf8Path,
        format: ArchiveFormat,
        dest: ExtractDestination,
        callback: F,
        workspace_remap: Option<&Utf8Path>,
    ) -> Result<Self, ArchiveExtractError>
    where
        F: for<'e> FnMut(ArchiveEvent<'e>) -> io::Result<()>,
    {
        let mut file = fs::File::open(archive_file)
            .map_err(|err| ArchiveExtractError::Read(ArchiveReadError::Io(err)))?;

        let mut unarchiver = Unarchiver::new(&mut file, format);
        let ExtractInfo {
            dest_dir,
            temp_dir,
            binary_list,
            cargo_metadata_json,
            graph,
            libdir_mapper,
        } = unarchiver.extract(dest, callback)?;

        let cargo_metadata = MetadataWithRemap {
            metadata: ReusedCargoMetadata::new((cargo_metadata_json, graph)),
            remap: workspace_remap.map(|p| p.to_owned()),
        };
        let binaries_metadata = MetadataWithRemap {
            metadata: ReusedBinaryList::new(binary_list),
            remap: Some(dest_dir.join("target")),
        };

        Ok(Self {
            cargo_metadata: Some(cargo_metadata),
            binaries_metadata: Some(binaries_metadata),
            // Archives normalize build_directory == target_directory, so no
            // separate build dir remap is needed.
            build_dir_remap: None,
            libdir_mapper,
            _temp_dir: temp_dir,
        })
    }

    /// Returns the Cargo metadata.
    pub fn cargo_metadata(&self) -> Option<&ReusedCargoMetadata> {
        self.cargo_metadata.as_ref().map(|m| &m.metadata)
    }

    /// Returns the binaries metadata, reading it from disk if necessary.
    pub fn binaries_metadata(&self) -> Option<&ReusedBinaryList> {
        self.binaries_metadata.as_ref().map(|m| &m.metadata)
    }

    /// Returns true if any component of the build is being reused.
    #[inline]
    pub fn is_active(&self) -> bool {
        self.cargo_metadata.is_some() || self.binaries_metadata.is_some()
    }

    /// Returns the new workspace directory.
    pub fn workspace_remap(&self) -> Option<&Utf8Path> {
        self.cargo_metadata
            .as_ref()
            .and_then(|m| m.remap.as_deref())
    }

    /// Returns the new target directory.
    pub fn target_dir_remap(&self) -> Option<&Utf8Path> {
        self.binaries_metadata
            .as_ref()
            .and_then(|m| m.remap.as_deref())
    }

    /// Returns the new build directory.
    pub fn build_dir_remap(&self) -> Option<&Utf8Path> {
        self.build_dir_remap.as_deref()
    }
}

/// Metadata as either deserialized contents or a path, along with a possible directory remap.
#[derive(Clone, Debug)]
pub struct MetadataWithRemap<T> {
    /// The metadata.
    pub metadata: T,

    /// The remapped directory.
    pub remap: Option<Utf8PathBuf>,
}

/// Type parameter for [`MetadataWithRemap`].
pub trait MetadataKind: Clone + fmt::Debug {
    /// The type of metadata stored.
    type MetadataType: Sized;

    /// Constructs a new [`MetadataKind`] from the given metadata.
    fn new(metadata: Self::MetadataType) -> Self;

    /// Reads a path, resolving it into this data type.
    fn materialize(path: &Utf8Path) -> Result<Self, MetadataMaterializeError>;
}

/// [`MetadataKind`] for a [`BinaryList`].
#[derive(Clone, Debug)]
pub struct ReusedBinaryList {
    /// The binary list.
    pub binary_list: Arc<BinaryList>,
}

impl MetadataKind for ReusedBinaryList {
    type MetadataType = BinaryList;

    fn new(binary_list: Self::MetadataType) -> Self {
        Self {
            binary_list: Arc::new(binary_list),
        }
    }

    fn materialize(path: &Utf8Path) -> Result<Self, MetadataMaterializeError> {
        // Three steps: read the contents, turn it into a summary, and then turn it into a
        // BinaryList.
        //
        // Buffering the contents in memory is generally much faster than trying to read it
        // using a BufReader.
        let contents =
            fs::read_to_string(path).map_err(|error| MetadataMaterializeError::Read {
                path: path.to_owned(),
                error,
            })?;

        let summary: BinaryListSummary = serde_json::from_str(&contents).map_err(|error| {
            MetadataMaterializeError::Deserialize {
                path: path.to_owned(),
                error,
            }
        })?;

        let binary_list = BinaryList::from_summary(summary).map_err(|error| {
            MetadataMaterializeError::RustBuildMeta {
                path: path.to_owned(),
                error: Box::new(error),
            }
        })?;

        Ok(Self::new(binary_list))
    }
}

/// [`MetadataKind`] for Cargo metadata.
#[derive(Clone, Debug)]
pub struct ReusedCargoMetadata {
    /// Cargo metadata JSON.
    pub json: Arc<String>,

    /// The package graph.
    pub graph: Arc<PackageGraph>,
}

impl MetadataKind for ReusedCargoMetadata {
    type MetadataType = (String, PackageGraph);

    fn new((json, graph): Self::MetadataType) -> Self {
        Self {
            json: Arc::new(json),
            graph: Arc::new(graph),
        }
    }

    fn materialize(path: &Utf8Path) -> Result<Self, MetadataMaterializeError> {
        // Read the contents into memory, then parse them as a `PackageGraph`.
        let json =
            std::fs::read_to_string(path).map_err(|error| MetadataMaterializeError::Read {
                path: path.to_owned(),
                error,
            })?;
        let graph = PackageGraph::from_json(&json).map_err(|error| {
            MetadataMaterializeError::PackageGraphConstruct {
                path: path.to_owned(),
                error: Box::new(error),
            }
        })?;

        Ok(Self::new((json, graph)))
    }
}

/// A helper for path remapping.
///
/// This is useful when running tests in a different directory, or a different computer, from
/// building them.
#[derive(Clone, Debug, Default)]
pub struct PathMapper {
    workspace: Option<(Utf8PathBuf, Utf8PathBuf)>,
    target_dir: Option<(Utf8PathBuf, Utf8PathBuf)>,
    build_dir: Option<(Utf8PathBuf, Utf8PathBuf)>,
    libdir_mapper: LibdirMapper,
}

impl PathMapper {
    /// Constructs the path mapper.
    pub fn new(
        orig_workspace_root: impl Into<Utf8PathBuf>,
        workspace_remap: Option<&Utf8Path>,
        orig_target_dir: impl Into<Utf8PathBuf>,
        target_dir_remap: Option<&Utf8Path>,
        orig_build_dir: impl Into<Utf8PathBuf>,
        build_dir_remap: Option<&Utf8Path>,
        libdir_mapper: LibdirMapper,
    ) -> Result<Self, PathMapperConstructError> {
        let workspace_root = workspace_remap
            .map(|root| Self::canonicalize_dir(root, PathMapperConstructKind::WorkspaceRoot))
            .transpose()?;
        let target_dir = target_dir_remap
            .map(|dir| Self::canonicalize_dir(dir, PathMapperConstructKind::TargetDir))
            .transpose()?;
        let build_dir = build_dir_remap
            .map(|dir| Self::canonicalize_dir(dir, PathMapperConstructKind::BuildDir))
            .transpose()?;

        Ok(Self {
            workspace: workspace_root.map(|w| (orig_workspace_root.into(), w)),
            target_dir: target_dir.map(|d| (orig_target_dir.into(), d)),
            build_dir: build_dir.map(|d| (orig_build_dir.into(), d)),
            libdir_mapper,
        })
    }

    /// Constructs a no-op path mapper.
    pub fn noop() -> Self {
        Self {
            workspace: None,
            target_dir: None,
            build_dir: None,
            libdir_mapper: LibdirMapper::default(),
        }
    }

    /// Returns the libdir mapper.
    pub fn libdir_mapper(&self) -> &LibdirMapper {
        &self.libdir_mapper
    }

    fn canonicalize_dir(
        input: &Utf8Path,
        kind: PathMapperConstructKind,
    ) -> Result<Utf8PathBuf, PathMapperConstructError> {
        let canonicalized_path =
            input
                .canonicalize()
                .map_err(|err| PathMapperConstructError::Canonicalization {
                    kind,
                    input: input.into(),
                    err,
                })?;
        let canonicalized_path: Utf8PathBuf =
            canonicalized_path
                .try_into()
                .map_err(|err| PathMapperConstructError::NonUtf8Path {
                    kind,
                    input: input.into(),
                    err,
                })?;
        if !canonicalized_path.is_dir() {
            return Err(PathMapperConstructError::NotADirectory {
                kind,
                input: input.into(),
                canonicalized_path,
            });
        }

        Ok(os_imp::strip_verbatim(canonicalized_path))
    }

    /// Returns the canonicalized workspace root, if a workspace remap was
    /// specified.
    pub fn new_workspace_root(&self) -> Option<&Utf8Path> {
        self.workspace.as_ref().map(|(_, new)| new.as_path())
    }

    pub(super) fn new_target_dir(&self) -> Option<&Utf8Path> {
        self.target_dir.as_ref().map(|(_, new)| new.as_path())
    }

    pub(super) fn new_build_dir(&self) -> Option<&Utf8Path> {
        self.build_dir.as_ref().map(|(_, new)| new.as_path())
    }

    pub(crate) fn map_cwd(&self, path: Utf8PathBuf) -> Utf8PathBuf {
        Self::remap_path(self.workspace.as_ref(), path)
    }

    /// Remaps a path under the target directory.
    ///
    /// Use this for paths that are relative to `target_directory`, such as
    /// non-test binaries and archive include paths.
    pub(crate) fn map_target_path(&self, path: Utf8PathBuf) -> Utf8PathBuf {
        Self::remap_path(self.target_dir.as_ref(), path)
    }

    /// Remaps a path under the build directory.
    ///
    /// Use this for paths that are relative to `build_directory`, such as test
    /// binaries, build script out dirs, and linked paths.
    pub(crate) fn map_build_path(&self, path: Utf8PathBuf) -> Utf8PathBuf {
        Self::remap_path(self.build_dir.as_ref(), path)
    }

    fn remap_path(mapping: Option<&(Utf8PathBuf, Utf8PathBuf)>, path: Utf8PathBuf) -> Utf8PathBuf {
        match mapping {
            Some((from, to)) => match path.strip_prefix(from) {
                Ok(p) if !p.as_str().is_empty() => to.join(p),
                Ok(_) => to.clone(),
                Err(_) => {
                    debug!(
                        target: "nextest-runner::reuse_build",
                        "path `{path}` does not start with remap prefix `{from}`, \
                         returning unchanged",
                    );
                    path
                }
            },
            None => path,
        }
    }
}

/// A mapper for lib dirs.
///
/// Archives store parts of lib dirs, which must be remapped to the new target directory.
#[derive(Clone, Debug, Default)]
pub struct LibdirMapper {
    /// The host libdir mapper.
    pub(crate) host: PlatformLibdirMapper,

    /// The target libdir mapper.
    pub(crate) target: PlatformLibdirMapper,
}

/// A mapper for an individual platform libdir.
///
/// Part of [`LibdirMapper`].
#[derive(Clone, Debug, Default)]
pub(crate) enum PlatformLibdirMapper {
    Path(Utf8PathBuf),
    Unavailable,
    #[default]
    NotRequested,
}

impl PlatformLibdirMapper {
    pub(crate) fn map(&self, original: &PlatformLibdir) -> PlatformLibdir {
        match self {
            PlatformLibdirMapper::Path(new) => {
                // Just use the new path. (We may have to check original in the future, but it
                // doesn't seem necessary for now -- if a libdir has been provided to the remapper,
                // that's that.)
                PlatformLibdir::Available(new.clone())
            }
            PlatformLibdirMapper::Unavailable => {
                // In this case, the original value is ignored -- we expected a libdir to be
                // present, but it wasn't.
                PlatformLibdir::Unavailable(PlatformLibdirUnavailable::NOT_IN_ARCHIVE)
            }
            PlatformLibdirMapper::NotRequested => original.clone(),
        }
    }
}

#[cfg(windows)]
mod os_imp {
    use camino::Utf8PathBuf;
    use std::ptr;
    use windows_sys::Win32::Storage::FileSystem::GetFullPathNameW;

    /// Strips verbatim prefix from a path if possible.
    pub(super) fn strip_verbatim(path: Utf8PathBuf) -> Utf8PathBuf {
        let path_str = String::from(path);
        if path_str.starts_with(r"\\?\UNC") {
            // In general we don't expect UNC paths, so just return the path as is.
            path_str.into()
        } else if path_str.starts_with(r"\\?\") {
            const START_LEN: usize = r"\\?\".len();

            let is_absolute_exact = {
                let mut v = path_str[START_LEN..].encode_utf16().collect::<Vec<u16>>();
                // Ensure null termination.
                v.push(0);
                is_absolute_exact(&v)
            };

            if is_absolute_exact {
                path_str[START_LEN..].into()
            } else {
                path_str.into()
            }
        } else {
            // Not a verbatim path, so return it as is.
            path_str.into()
        }
    }

    /// Test that the path is absolute, fully qualified and unchanged when processed by the Windows API.Add commentMore actions
    ///
    /// For example:
    ///
    /// - `C:\path\to\file` will return true.
    /// - `C:\path\to\nul` returns false because the Windows API will convert it to \\.\NUL
    /// - `C:\path\to\..\file` returns false because it will be resolved to `C:\path\file`.
    ///
    /// This is a useful property because it means the path can be converted from and to and verbatim
    /// path just by changing the prefix.
    fn is_absolute_exact(path: &[u16]) -> bool {
        // Adapted from the Rust project: https://github.com/rust-lang/rust/commit/edfc74722556c659de6fa03b23af3b9c8ceb8ac2

        // This is implemented by checking that passing the path through
        // GetFullPathNameW does not change the path in any way.

        // Windows paths are limited to i16::MAX length
        // though the API here accepts a u32 for the length.
        if path.is_empty() || path.len() > u32::MAX as usize || path.last() != Some(&0) {
            return false;
        }
        // The path returned by `GetFullPathNameW` must be the same length as the
        // given path, otherwise they're not equal.
        let buffer_len = path.len();
        let mut new_path = Vec::with_capacity(buffer_len);
        let result = unsafe {
            GetFullPathNameW(
                path.as_ptr(),
                new_path.capacity() as u32,
                new_path.as_mut_ptr(),
                ptr::null_mut(),
            )
        };
        // Note: if non-zero, the returned result is the length of the buffer without the null termination
        if result == 0 || result as usize != buffer_len - 1 {
            false
        } else {
            // SAFETY: `GetFullPathNameW` initialized `result` bytes and does not exceed `nBufferLength - 1` (capacity).
            unsafe {
                new_path.set_len((result as usize) + 1);
            }
            path == new_path
        }
    }
}

#[cfg(unix)]
mod os_imp {
    use camino::Utf8PathBuf;

    pub(super) fn strip_verbatim(path: Utf8PathBuf) -> Utf8PathBuf {
        // On Unix, there aren't any verbatin paths, so just return the path as
        // is.
        path
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{list::RustBuildMeta, platform::BuildPlatforms};

    /// Ensure that PathMapper turns relative paths into absolute ones.
    #[test]
    fn test_path_mapper_relative() {
        let current_dir: Utf8PathBuf = std::env::current_dir()
            .expect("current dir obtained")
            .try_into()
            .expect("current dir is valid UTF-8");

        let temp_workspace_root = Utf8TempDir::new().expect("new temp dir created");
        let workspace_root_path: Utf8PathBuf = os_imp::strip_verbatim(
            temp_workspace_root
                .path()
                // On Mac, the temp dir is a symlink, so canonicalize it.
                .canonicalize()
                .expect("workspace root canonicalized correctly")
                .try_into()
                .expect("workspace root is valid UTF-8"),
        );
        let rel_workspace_root = pathdiff::diff_utf8_paths(&workspace_root_path, &current_dir)
            .expect("abs to abs diff is non-None");

        let temp_target_dir = Utf8TempDir::new().expect("new temp dir created");
        let target_dir_path: Utf8PathBuf = os_imp::strip_verbatim(
            temp_target_dir
                .path()
                .canonicalize()
                .expect("target dir canonicalized correctly")
                .try_into()
                .expect("target dir is valid UTF-8"),
        );
        let rel_target_dir = pathdiff::diff_utf8_paths(&target_dir_path, &current_dir)
            .expect("abs to abs diff is non-None");

        let temp_build_dir = Utf8TempDir::new().expect("new temp dir created");
        let build_dir_path: Utf8PathBuf = os_imp::strip_verbatim(
            temp_build_dir
                .path()
                .canonicalize()
                .expect("build dir canonicalized correctly")
                .try_into()
                .expect("build dir is valid UTF-8"),
        );
        let rel_build_dir = pathdiff::diff_utf8_paths(&build_dir_path, &current_dir)
            .expect("abs to abs diff is non-None");

        // These aren't really used other than to do mapping against.
        let orig_workspace_root = Utf8PathBuf::from(
            std::env::var("NEXTEST_WORKSPACE_ROOT")
                .expect("NEXTEST_WORKSPACE_ROOT is set (running under cargo nextest run)"),
        );
        let orig_target_dir = orig_workspace_root.join("target");
        let orig_build_dir = orig_workspace_root.join("build");

        let path_mapper = PathMapper::new(
            orig_workspace_root.as_path(),
            Some(&rel_workspace_root),
            &orig_target_dir,
            Some(&rel_target_dir),
            &orig_build_dir,
            Some(&rel_build_dir),
            LibdirMapper::default(),
        )
        .expect("remapped paths exist");

        assert_eq!(
            path_mapper.map_cwd(orig_workspace_root.join("foobar")),
            workspace_root_path.join("foobar")
        );
        assert_eq!(
            path_mapper.map_target_path(orig_target_dir.join("foobar")),
            target_dir_path.join("foobar")
        );
        assert_eq!(
            path_mapper.map_build_path(orig_build_dir.join("foobar")),
            build_dir_path.join("foobar")
        );
    }

    /// Test that when build_dir and target_dir are separate, each maps
    /// independently.
    #[test]
    fn test_path_mapper_separate_build_dir() {
        let temp_target_dir = Utf8TempDir::new().expect("new temp dir created");
        let target_dir_path: Utf8PathBuf = os_imp::strip_verbatim(
            temp_target_dir
                .path()
                .canonicalize()
                .expect("target dir canonicalized correctly")
                .try_into()
                .expect("target dir is valid UTF-8"),
        );

        let temp_build_dir = Utf8TempDir::new().expect("new temp dir created");
        let build_dir_path: Utf8PathBuf = os_imp::strip_verbatim(
            temp_build_dir
                .path()
                .canonicalize()
                .expect("build dir canonicalized correctly")
                .try_into()
                .expect("build dir is valid UTF-8"),
        );

        let orig_workspace_root = Utf8PathBuf::from(
            std::env::var("NEXTEST_WORKSPACE_ROOT")
                .expect("NEXTEST_WORKSPACE_ROOT is set (running under cargo nextest run)"),
        );
        let orig_target_dir = orig_workspace_root.join("target");
        let orig_build_dir = orig_workspace_root.join("build");

        let path_mapper = PathMapper::new(
            orig_workspace_root.as_path(),
            None,
            &orig_target_dir,
            Some(target_dir_path.as_path()),
            &orig_build_dir,
            Some(build_dir_path.as_path()),
            LibdirMapper::default(),
        )
        .expect("remapped paths exist");

        // Target paths remap under target_dir.
        assert_eq!(
            path_mapper.map_target_path(orig_target_dir.join("debug/mybin")),
            target_dir_path.join("debug/mybin"),
        );

        // Build paths remap under build_dir.
        assert_eq!(
            path_mapper.map_build_path(orig_build_dir.join("debug/deps/test-abc123")),
            build_dir_path.join("debug/deps/test-abc123"),
        );

        // Paths not matching either prefix are returned unchanged.
        let unrelated = Utf8PathBuf::from("/some/other/path");
        assert_eq!(path_mapper.map_target_path(unrelated.clone()), unrelated,);
        assert_eq!(path_mapper.map_build_path(unrelated.clone()), unrelated,);
    }

    /// Test that `map_paths` falls back to target_dir remap when no explicit
    /// build_dir remap is set.
    #[test]
    fn test_map_paths_build_dir_fallback() {
        let temp_target_dir = Utf8TempDir::new().expect("new temp dir created");
        let target_dir_path: Utf8PathBuf = os_imp::strip_verbatim(
            temp_target_dir
                .path()
                .canonicalize()
                .expect("target dir canonicalized correctly")
                .try_into()
                .expect("target dir is valid UTF-8"),
        );

        let orig_workspace_root = Utf8PathBuf::from(
            std::env::var("NEXTEST_WORKSPACE_ROOT")
                .expect("NEXTEST_WORKSPACE_ROOT is set (running under cargo nextest run)"),
        );
        let orig_target_dir = orig_workspace_root.join("target");
        let orig_build_dir = orig_workspace_root.join("build");

        // Only target_dir remap is set, no build_dir remap.
        let path_mapper = PathMapper::new(
            orig_workspace_root.as_path(),
            None,
            &orig_target_dir,
            Some(target_dir_path.as_path()),
            &orig_build_dir,
            None,
            LibdirMapper::default(),
        )
        .expect("remapped paths exist");

        // new_build_dir() returns None since no explicit build dir remap was
        // passed.
        assert_eq!(path_mapper.new_build_dir(), None);
        assert_eq!(
            path_mapper.new_target_dir(),
            Some(target_dir_path.as_path()),
        );

        // Verify the fallback by actually calling map_paths: since no
        // build_dir remap is set, map_paths should fall back to the
        // target_dir remap for build_directory.
        let build_platforms = BuildPlatforms::new_with_no_target()
            .expect("creating BuildPlatforms without target triple succeeds");
        let meta = RustBuildMeta::new(&orig_target_dir, &orig_build_dir, build_platforms);
        let mapped = meta.map_paths(&path_mapper);

        assert_eq!(mapped.target_directory, target_dir_path);
        assert_eq!(
            mapped.build_directory, target_dir_path,
            "build_directory should fall back to the target_dir remap",
        );
    }
}