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

//! Support for [target runners](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerunner)

use crate::{
    cargo_config::{CargoConfig, CargoConfigSource, CargoConfigs, DiscoveredConfig, Runner},
    errors::TargetRunnerError,
    platform::BuildPlatforms,
};
use camino::{Utf8Path, Utf8PathBuf};
use nextest_metadata::BuildPlatform;
use std::fmt;
use target_spec::Platform;

/// A [target runner](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerunner)
/// used to execute a test binary rather than the default of executing natively.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TargetRunner {
    host: Option<PlatformRunner>,
    target: Option<PlatformRunner>,
}

impl TargetRunner {
    /// Acquires the [target runner](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerunner)
    /// which can be set in a [.cargo/config.toml](https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure)
    /// or via a `CARGO_TARGET_{TRIPLE}_RUNNER` environment variable
    pub fn new(
        configs: &CargoConfigs,
        build_platforms: &BuildPlatforms,
    ) -> Result<Self, TargetRunnerError> {
        let host = PlatformRunner::by_precedence(configs, &build_platforms.host)?;
        let target = match &build_platforms.target {
            Some(target) => PlatformRunner::by_precedence(configs, &target.platform)?,
            None => host.clone(),
        };

        Ok(Self { host, target })
    }

    /// Creates an empty target runner that does not delegate to any runner binaries.
    pub fn empty() -> Self {
        Self {
            host: None,
            target: None,
        }
    }

    /// Returns the target [`PlatformRunner`].
    #[inline]
    pub fn target(&self) -> Option<&PlatformRunner> {
        self.target.as_ref()
    }

    /// Returns the host [`PlatformRunner`].
    #[inline]
    pub fn host(&self) -> Option<&PlatformRunner> {
        self.host.as_ref()
    }

    /// Returns the [`PlatformRunner`] for the given build platform (host or target).
    #[inline]
    pub fn for_build_platform(&self, build_platform: BuildPlatform) -> Option<&PlatformRunner> {
        match build_platform {
            BuildPlatform::Target => self.target(),
            BuildPlatform::Host => self.host(),
        }
    }

    /// Returns the platform runners for all build platforms.
    #[inline]
    pub fn all_build_platforms(&self) -> [(BuildPlatform, Option<&PlatformRunner>); 2] {
        [
            (BuildPlatform::Target, self.target()),
            (BuildPlatform::Host, self.host()),
        ]
    }
}

/// A target runner scoped to a specific platform (host or target).
///
/// This forms part of [`TargetRunner`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PlatformRunner {
    runner_binary: Utf8PathBuf,
    args: Vec<String>,
    source: PlatformRunnerSource,
}

impl PlatformRunner {
    fn by_precedence(
        configs: &CargoConfigs,
        platform: &Platform,
    ) -> Result<Option<Self>, TargetRunnerError> {
        Self::find_config(configs, platform)
    }

    /// Attempts to find a target runner for the specified target from a
    /// [cargo config](https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure)
    ///
    /// Not part of the public API. For testing only.
    #[doc(hidden)]
    pub fn find_config(
        configs: &CargoConfigs,
        target: &Platform,
    ) -> Result<Option<Self>, TargetRunnerError> {
        // Now that we've found all of the config files that could declare
        // a runner that matches our target triple, we need to actually find
        // all the matches, but in reverse order as the closer the config is
        // to our current working directory, the higher precedence it has
        for discovered_config in configs.discovered_configs() {
            match discovered_config {
                DiscoveredConfig::CliOption { config, source }
                | DiscoveredConfig::File { config, source } => {
                    if let Some(runner) =
                        Self::from_cli_option_or_file(target, config, source, configs.cwd())?
                    {
                        return Ok(Some(runner));
                    }
                }
                DiscoveredConfig::Env => {
                    // Check if we have a CARGO_TARGET_{TRIPLE}_RUNNER environment variable
                    // set, and if so use that.
                    if let Some(tr) = Self::from_env(Self::runner_env_var(target), configs.cwd())? {
                        return Ok(Some(tr));
                    }
                }
            }
        }

        Ok(None)
    }

    fn from_cli_option_or_file(
        target: &target_spec::Platform,
        config: &CargoConfig,
        source: &CargoConfigSource,
        cwd: &Utf8Path,
    ) -> Result<Option<Self>, TargetRunnerError> {
        if let Some(targets) = &config.target {
            // First lookup by the exact triple, as that one always takes precedence
            if let Some(parent) = targets.get(target.triple_str()) {
                if let Some(runner) = &parent.runner {
                    return Ok(Some(Self::parse_runner(
                        PlatformRunnerSource::CargoConfig {
                            source: source.clone(),
                            target_table: target.triple_str().into(),
                        },
                        runner.clone(),
                        cwd,
                    )?));
                }
            }

            // Next check if there are target.'cfg(..)' expressions that match
            // the target. cargo states that it is not allowed for more than
            // 1 cfg runner to match the target, but we let cargo handle that
            // error itself, we just use the first one that matches
            for (cfg, runner) in targets.iter().filter_map(|(k, v)| match &v.runner {
                Some(runner) if k.starts_with("cfg(") => Some((k, runner)),
                _ => None,
            }) {
                // Treat these as non-fatal, but would be good to log maybe
                let expr = match target_spec::TargetSpecExpression::new(cfg) {
                    Ok(expr) => expr,
                    Err(_err) => continue,
                };

                if expr.eval(target) == Some(true) {
                    return Ok(Some(Self::parse_runner(
                        PlatformRunnerSource::CargoConfig {
                            source: source.clone(),
                            target_table: cfg.clone(),
                        },
                        runner.clone(),
                        cwd,
                    )?));
                }
            }
        }

        Ok(None)
    }

    fn from_env(env_key: String, cwd: &Utf8Path) -> Result<Option<Self>, TargetRunnerError> {
        if let Some(runner_var) = std::env::var_os(&env_key) {
            let runner = runner_var
                .into_string()
                .map_err(|_osstr| TargetRunnerError::InvalidEnvironmentVar(env_key.clone()))?;
            Self::parse_runner(
                PlatformRunnerSource::Env(env_key),
                Runner::Simple(runner),
                cwd,
            )
            .map(Some)
        } else {
            Ok(None)
        }
    }

    // Not part of the public API. Exposed for testing only.
    #[doc(hidden)]
    pub fn runner_env_var(target: &Platform) -> String {
        let triple_str = target.triple_str().to_ascii_uppercase().replace('-', "_");
        format!("CARGO_TARGET_{triple_str}_RUNNER")
    }

    fn parse_runner(
        source: PlatformRunnerSource,
        runner: Runner,
        cwd: &Utf8Path,
    ) -> Result<Self, TargetRunnerError> {
        let (runner_binary, args) = match runner {
            Runner::Simple(value) => {
                // We only split on whitespace, which doesn't take quoting into account,
                // but I believe that cargo doesn't do that either
                let mut runner_iter = value.split_whitespace();

                let runner_binary =
                    runner_iter
                        .next()
                        .ok_or_else(|| TargetRunnerError::BinaryNotSpecified {
                            key: source.clone(),
                            value: value.clone(),
                        })?;
                let args = runner_iter.map(String::from).collect();
                (
                    Self::normalize_runner(runner_binary, source.resolve_dir(cwd)),
                    args,
                )
            }
            Runner::List(mut values) => {
                if values.is_empty() {
                    return Err(TargetRunnerError::BinaryNotSpecified {
                        key: source,
                        value: String::new(),
                    });
                } else {
                    let runner_binary = values.remove(0);
                    (
                        Self::normalize_runner(&runner_binary, source.resolve_dir(cwd)),
                        values,
                    )
                }
            }
        };

        Ok(Self {
            runner_binary,
            args,
            source,
        })
    }

    // https://github.com/rust-lang/cargo/blob/40b674cd1115299034fafa34e7db3a9140b48a49/src/cargo/util/config/mod.rs#L735-L743
    fn normalize_runner(runner_binary: &str, resolve_dir: &Utf8Path) -> Utf8PathBuf {
        let is_path =
            runner_binary.contains('/') || (cfg!(windows) && runner_binary.contains('\\'));
        if is_path {
            resolve_dir.join(runner_binary)
        } else {
            // A pathless name.
            runner_binary.into()
        }
    }

    /// Gets the runner binary path.
    ///
    /// Note that this is returned as a `str` specifically to avoid duct's
    /// behavior of prepending `.` to paths it thinks are relative, the path
    /// specified for a runner can be a full path, but it is most commonly a
    /// binary found in `PATH`
    #[inline]
    pub fn binary(&self) -> &str {
        self.runner_binary.as_str()
    }

    /// Gets the (optional) runner binary arguments
    #[inline]
    pub fn args(&self) -> impl Iterator<Item = &str> {
        self.args.iter().map(AsRef::as_ref)
    }

    /// Returns the location where the platform runner is defined.
    #[inline]
    pub fn source(&self) -> &PlatformRunnerSource {
        &self.source
    }
}

/// The place where a platform runner's configuration was picked up from.
///
/// Returned by [`PlatformRunner::source`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlatformRunnerSource {
    /// The platform runner was defined by this environment variable.
    Env(String),

    /// The platform runner was defined through a `.cargo/config.toml` or `.cargo/config` file, or
    /// via `--config` (unstable).
    CargoConfig {
        /// The configuration source.
        source: CargoConfigSource,

        /// The table name within `target` that was used.
        ///
        /// # Examples
        ///
        /// If `target.'cfg(target_os = "linux")'.runner` is used, this is `cfg(target_os = "linux")`.
        target_table: String,
    },
}

impl PlatformRunnerSource {
    // https://github.com/rust-lang/cargo/blob/3959f87158ea4f8733e2fcbe032b8a50ae0b6834/src/cargo/util/config/value.rs#L66-L75
    fn resolve_dir<'a>(&'a self, cwd: &'a Utf8Path) -> &'a Utf8Path {
        match self {
            Self::Env(_) => cwd,
            Self::CargoConfig { source, .. } => source.resolve_dir(cwd),
        }
    }
}

impl fmt::Display for PlatformRunnerSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Env(var) => {
                write!(f, "environment variable `{var}`")
            }
            Self::CargoConfig {
                source: CargoConfigSource::CliOption,
                target_table,
            } => {
                write!(f, "`target.{target_table}.runner` specified by `--config`")
            }
            Self::CargoConfig {
                source: CargoConfigSource::File(path),
                target_table,
            } => {
                write!(f, "`target.{target_table}.runner` within `{path}`")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use camino_tempfile::Utf8TempDir;
    use color_eyre::eyre::{Context, Result};
    use target_spec::TargetFeatures;

    #[test]
    fn test_find_config() {
        let dir = setup_temp_dir().unwrap();
        let dir_path = dir.path().canonicalize_utf8().unwrap();
        let dir_foo_path = dir_path.join("foo");
        let dir_foo_bar_path = dir_foo_path.join("bar");

        // ---
        // Searches through the full directory tree
        // ---
        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-msvc", TargetFeatures::Unknown).unwrap(),
                &[],
                &dir_foo_bar_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: "wine".into(),
                args: vec!["--test-arg".into()],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::File(dir_path.join("foo/bar/.cargo/config.toml")),
                    target_table: "x86_64-pc-windows-msvc".into()
                },
            }),
        );

        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-gnu", TargetFeatures::Unknown).unwrap(),
                &[],
                &dir_foo_bar_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: "wine2".into(),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::File(dir_path.join("foo/bar/.cargo/config.toml")),
                    target_table: "cfg(windows)".into()
                },
            }),
        );

        assert_eq!(
            find_config(
                Platform::new("x86_64-unknown-linux-gnu", TargetFeatures::Unknown).unwrap(),
                &[],
                &dir_foo_bar_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: dir_path.join("unix-runner"),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::File(dir_path.join(".cargo/config")),
                    target_table: "cfg(unix)".into()
                },
            }),
        );

        // ---
        // Searches starting from the "foo" directory which has no .cargo/config in it
        // ---
        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-msvc", TargetFeatures::Unknown).unwrap(),
                &[],
                &dir_foo_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: dir_path.join("../parent-wine"),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::File(dir_path.join(".cargo/config")),
                    target_table: "x86_64-pc-windows-msvc".into()
                },
            }),
        );

        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-gnu", TargetFeatures::Unknown).unwrap(),
                &[],
                &dir_foo_path,
                &dir_path,
            ),
            None,
        );

        // ---
        // Searches starting and ending at the root directory.
        // ---
        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-msvc", TargetFeatures::Unknown).unwrap(),
                &[],
                &dir_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: dir_path.join("../parent-wine"),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::File(dir_path.join(".cargo/config")),
                    target_table: "x86_64-pc-windows-msvc".into()
                },
            }),
        );

        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-gnu", TargetFeatures::Unknown).unwrap(),
                &[],
                &dir_path,
                &dir_path,
            ),
            None,
        );

        // ---
        // CLI configs
        // ---
        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-msvc", TargetFeatures::Unknown).unwrap(),
                &["target.'cfg(windows)'.runner='windows-runner'"],
                &dir_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: "windows-runner".into(),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::CliOption,
                    target_table: "cfg(windows)".into()
                },
            }),
        );

        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-gnu", TargetFeatures::Unknown).unwrap(),
                &["target.'cfg(windows)'.runner='windows-runner'"],
                &dir_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: "windows-runner".into(),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::CliOption,
                    target_table: "cfg(windows)".into()
                },
            }),
        );

        // cfg(unix) doesn't match this platform.
        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-msvc", TargetFeatures::Unknown).unwrap(),
                &["target.'cfg(unix)'.runner='unix-runner'"],
                &dir_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: dir_path.join("../parent-wine"),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::File(dir_path.join(".cargo/config")),
                    target_table: "x86_64-pc-windows-msvc".into()
                },
            }),
        );

        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-gnu", TargetFeatures::Unknown).unwrap(),
                &["target.'cfg(unix)'.runner='unix-runner'"],
                &dir_path,
                &dir_path,
            ),
            None,
        );

        // Config is followed from left to right.
        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-msvc", TargetFeatures::Unknown).unwrap(),
                &[
                    "target.'cfg(windows)'.runner='windows-runner'",
                    "target.'cfg(all())'.runner='all-runner'"
                ],
                &dir_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: "windows-runner".into(),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::CliOption,
                    target_table: "cfg(windows)".into()
                },
            }),
        );

        assert_eq!(
            find_config(
                Platform::new("x86_64-pc-windows-msvc", TargetFeatures::Unknown).unwrap(),
                &[
                    "target.'cfg(all())'.runner='./all-runner'",
                    "target.'cfg(windows)'.runner='windows-runner'",
                ],
                &dir_path,
                &dir_path,
            ),
            Some(PlatformRunner {
                runner_binary: dir_path.join("all-runner"),
                args: vec![],
                source: PlatformRunnerSource::CargoConfig {
                    source: CargoConfigSource::CliOption,
                    target_table: "cfg(all())".into()
                },
            }),
        );
    }

    fn setup_temp_dir() -> Result<Utf8TempDir> {
        let dir = camino_tempfile::Builder::new()
            .tempdir()
            .wrap_err("error creating tempdir")?;

        std::fs::create_dir_all(dir.path().join(".cargo"))
            .wrap_err("error creating .cargo subdir")?;
        std::fs::create_dir_all(dir.path().join("foo/bar/.cargo"))
            .wrap_err("error creating foo/bar/.cargo subdir")?;

        std::fs::write(dir.path().join(".cargo/config"), CARGO_CONFIG_CONTENTS)
            .wrap_err("error writing .cargo/config")?;
        std::fs::write(
            dir.path().join("foo/bar/.cargo/config.toml"),
            FOO_BAR_CARGO_CONFIG_CONTENTS,
        )
        .wrap_err("error writing foo/bar/.cargo/config.toml")?;

        Ok(dir)
    }

    fn find_config(
        platform: Platform,
        cli_configs: &[&str],
        cwd: &Utf8Path,
        terminate_search_at: &Utf8Path,
    ) -> Option<PlatformRunner> {
        let configs =
            CargoConfigs::new_with_isolation(cli_configs, cwd, terminate_search_at, Vec::new())
                .unwrap();
        PlatformRunner::find_config(&configs, &platform).unwrap()
    }

    static CARGO_CONFIG_CONTENTS: &str = r#"
    [target.x86_64-pc-windows-msvc]
    runner = "../parent-wine"

    [target.'cfg(unix)']
    runner = "./unix-runner"
    "#;

    static FOO_BAR_CARGO_CONFIG_CONTENTS: &str = r#"
    [target.x86_64-pc-windows-msvc]
    runner = ["wine", "--test-arg"]

    [target.'cfg(windows)']
    runner = "wine2"
    "#;
}