Skip to content

Instantly share code, notes, and snippets.

@hkoba
Created September 22, 2019 13:01
Show Gist options
  • Save hkoba/49090777a6ac4b9e57f55575e0ce74b5 to your computer and use it in GitHub Desktop.
Save hkoba/49090777a6ac4b9e57f55575e0ce74b5 to your computer and use it in GitHub Desktop.
A rust example to read perl's build configuration
use std::process::Command;
use std::collections::HashMap;
use std::result::Result;
use regex::Regex;
fn perl_config(configs: Vec<&str>) -> Result<String, String> {
let mut cmd = Command::new("perl");
cmd.arg("-wle");
cmd.arg(r#"
use strict;
use Config;
print join "\t", $_, ($Config{$_} // '') for @ARGV;
"#
);
for cf in configs.iter() {
cmd.arg(cf);
}
let out = cmd.output().expect("perl Config outputs");
if out.stderr.len() > 0 {
return Err(String::from_utf8(out.stderr).unwrap());
}
Ok(String::from_utf8(out.stdout).unwrap())
}
fn perl_config_dict(configs: Vec<&str>) -> Result<HashMap<String, String>, String> {
let config = perl_config(configs)?;
let lines = config.lines().map(String::from).collect();
Ok(lines_to_hashmap(lines))
}
fn lines_to_hashmap(lines: Vec<String>) -> HashMap<String,String> {
let mut dict = HashMap::new();
for line in lines.iter() {
let kv: Vec<String> = line.splitn(2, '\t').map(String::from).collect();
if kv.len() == 2 {
dict.insert(kv[0].clone(), kv[1].clone());
}
}
dict
}
fn main() {
let config = perl_config_dict(vec![
"ccflags",
"useithreads",
"usemultiplicity",
"PERL_VERSION",
"PERL_API_VERSION",
]).unwrap();
println!("config = {:?}", config);
let re_includes_and_defines = Regex::new(r"^-[ID]").unwrap();
let ccflags: Vec<String> = config.get("ccflags").unwrap().split_whitespace()
.map(String::from)
.filter(|s| re_includes_and_defines.is_match(s)).collect();
println!("ccflags = {:?}", ccflags);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment