summaryrefslogtreecommitdiffstats
path: root/vendor/cargo-platform/examples/matches.rs
blob: 1b438fb110a3fc367e4b6146ba366c0554575191 (plain)
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
//! This example demonstrates how to filter a Platform based on the current
//! host target.

use cargo_platform::{Cfg, Platform};
use std::process::Command;
use std::str::FromStr;

static EXAMPLES: &[&str] = &[
    "cfg(windows)",
    "cfg(unix)",
    "cfg(target_os=\"macos\")",
    "cfg(target_os=\"linux\")",
    "cfg(any(target_arch=\"x86\", target_arch=\"x86_64\"))",
];

fn main() {
    let target = get_target();
    let cfgs = get_cfgs();
    println!("host target={} cfgs:", target);
    for cfg in &cfgs {
        println!("  {}", cfg);
    }
    let mut examples: Vec<&str> = EXAMPLES.iter().copied().collect();
    examples.push(target.as_str());
    for example in examples {
        let p = Platform::from_str(example).unwrap();
        println!("{:?} matches: {:?}", example, p.matches(&target, &cfgs));
    }
}

fn get_target() -> String {
    let output = Command::new("rustc")
        .arg("-Vv")
        .output()
        .expect("rustc failed to run");
    let stdout = String::from_utf8(output.stdout).unwrap();
    for line in stdout.lines() {
        if let Some(line) = line.strip_prefix("host: ") {
            return String::from(line);
        }
    }
    panic!("Failed to find host: {}", stdout);
}

fn get_cfgs() -> Vec<Cfg> {
    let output = Command::new("rustc")
        .arg("--print=cfg")
        .output()
        .expect("rustc failed to run");
    let stdout = String::from_utf8(output.stdout).unwrap();
    stdout
        .lines()
        .map(|line| Cfg::from_str(line).unwrap())
        .collect()
}