matches/
matches.rs

1//! This example demonstrates how to filter a Platform based on the current
2//! host target.
3
4#![allow(clippy::print_stdout)]
5
6use cargo_platform::{Cfg, Platform};
7use std::process::Command;
8use std::str::FromStr;
9
10static EXAMPLES: &[&str] = &[
11    "cfg(windows)",
12    "cfg(unix)",
13    "cfg(target_os=\"macos\")",
14    "cfg(target_os=\"linux\")",
15    "cfg(any(target_arch=\"x86\", target_arch=\"x86_64\"))",
16];
17
18fn main() {
19    let target = get_target();
20    let cfgs = get_cfgs();
21    println!("host target={} cfgs:", target);
22    for cfg in &cfgs {
23        println!("  {}", cfg);
24    }
25    let mut examples: Vec<&str> = EXAMPLES.iter().copied().collect();
26    examples.push(target.as_str());
27    for example in examples {
28        let p = Platform::from_str(example).unwrap();
29        println!("{:?} matches: {:?}", example, p.matches(&target, &cfgs));
30    }
31}
32
33fn get_target() -> String {
34    let output = Command::new("rustc")
35        .arg("-Vv")
36        .output()
37        .expect("rustc failed to run");
38    let stdout = String::from_utf8(output.stdout).unwrap();
39    for line in stdout.lines() {
40        if let Some(line) = line.strip_prefix("host: ") {
41            return String::from(line);
42        }
43    }
44    panic!("Failed to find host: {}", stdout);
45}
46
47fn get_cfgs() -> Vec<Cfg> {
48    let output = Command::new("rustc")
49        .arg("--print=cfg")
50        .output()
51        .expect("rustc failed to run");
52    let stdout = String::from_utf8(output.stdout).unwrap();
53    stdout
54        .lines()
55        .map(|line| Cfg::from_str(line).unwrap())
56        .collect()
57}