Debian Codegraph @

third_party/rust/cargo-platform/examples/matches.rs

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