-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild.rs
211 lines (191 loc) · 6.07 KB
/
build.rs
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
use std::{
collections::HashMap,
ffi::{OsStr, OsString},
io,
path::Path,
process::Command,
};
#[cfg(target_family = "unix")]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_family = "windows")]
use std::os::windows::ffi::OsStringExt;
#[derive(Debug)]
struct ConfigVariables {
map: HashMap<String, String>,
}
impl ConfigVariables {
fn get_r_cmd_config(&self, key: &str) -> String {
match self.map.get(key) {
Some(value) => value.to_string(),
None => String::from(""),
}
}
}
// frustratingly, something like the following does not exist in an
// OS-independent way in Rust
#[cfg(target_family = "unix")]
fn byte_array_to_os_string(bytes: &[u8]) -> OsString {
let os_str = OsStr::from_bytes(bytes);
os_str.to_os_string()
}
#[link(name = "kernel32")]
#[cfg(target_family = "windows")]
extern "system" {
#[link_name = "GetConsoleCP"]
fn get_console_code_page() -> u32;
#[link_name = "MultiByteToWideChar"]
fn multi_byte_to_wide_char(
CodePage: u32,
dwFlags: u32,
lpMultiByteStr: *const u8,
cbMultiByte: i32,
lpWideCharStr: *mut u16,
cchWideChar: i32,
) -> i32;
}
// convert bytes to wide-encoded characters on Windows
// from: https://stackoverflow.com/a/40456495/4975218
#[cfg(target_family = "windows")]
fn wide_from_console_string(bytes: &[u8]) -> Vec<u16> {
assert!(bytes.len() < std::i32::MAX as usize);
let mut wide;
let mut len;
unsafe {
let cp = get_console_code_page();
len = multi_byte_to_wide_char(
cp,
0,
bytes.as_ptr() as *const u8,
bytes.len() as i32,
std::ptr::null_mut(),
0,
);
wide = Vec::with_capacity(len as usize);
len = multi_byte_to_wide_char(
cp,
0,
bytes.as_ptr() as *const u8,
bytes.len() as i32,
wide.as_mut_ptr(),
len,
);
wide.set_len(len as usize);
}
wide
}
#[cfg(target_family = "windows")]
fn byte_array_to_os_string(bytes: &[u8]) -> OsString {
// first, use Windows API to convert to wide encoded
let wide = wide_from_console_string(bytes);
// then, use `std::os::windows::ffi::OsStringExt::from_wide()`
OsString::from_wide(&wide)
}
/// Runs the command `R RHOME` and returns the trimmed output if successful.
/// Panics with a meaningful error message if the command fails.
fn get_r_home() -> String {
// Attempt to run the command `R RHOME`
let output = Command::new("R").arg("RHOME").output(); // Capture the command's output
match output {
Ok(output) if output.status.success() => {
// Convert stdout to a String and trim it
String::from_utf8(output.stdout)
.expect("Invalid UTF-8 in RHOME output")
.trim()
.to_string()
}
Ok(output) => {
eprintln!(
"Error: Command `R RHOME` failed with status: {}\nStderr: {}",
output.status,
String::from_utf8_lossy(&output.stderr)
);
panic!("Failed to detect RHOME using `R RHOME`. Is R installed and in your PATH?");
}
Err(err) => {
panic!(
"Failed to execute `R RHOME`: {}. Is R installed and in your PATH?",
err
);
}
}
}
// Execute an R CMD config and return the captured output
fn r_cmd_config<S: AsRef<OsStr>>(r_binary: S) -> io::Result<OsString> {
let out = Command::new(r_binary)
.args(&["CMD", "config", "--all"])
.output()?;
// if there are any errors we print them out, helps with debugging
if !out.stderr.is_empty() {
println!(
"> {}",
byte_array_to_os_string(&out.stderr)
.as_os_str()
.to_string_lossy()
);
}
Ok(byte_array_to_os_string(&out.stdout))
}
fn build_r_cmd_configs() -> ConfigVariables {
let r_binary = format!(r"{}/bin/R", get_r_home());
let r_configs = r_cmd_config(r_binary);
let mut rcmd_config_map = HashMap::new();
match r_configs {
Ok(configs) => {
let input = configs.as_os_str().to_string_lossy();
for line in input.lines() {
// Ignore lines beyond comment marker
if line.starts_with("##") {
break;
}
let parts: Vec<_> = line.split('=').map(str::trim).collect();
if let [name, value] = parts.as_slice() {
rcmd_config_map.insert(name.to_string(), value.to_string());
}
}
}
_ => (),
}
// Return the struct
ConfigVariables {
map: rcmd_config_map,
}
}
fn get_libs_and_paths(strings: Vec<String>) -> (Vec<String>, Vec<String>) {
let mut paths: Vec<String> = Vec::new();
let mut libs: Vec<String> = Vec::new();
for s in &strings {
let parts: Vec<&str> = s.split_whitespace().collect();
for part in parts {
if part.starts_with("-L") {
paths.push(part[2..].to_string());
} else if part.starts_with("-l") {
libs.push(part[2..].to_string());
}
}
}
(paths, libs)
}
fn main() {
let r_configs = build_r_cmd_configs();
let (lib_paths, libs) = get_libs_and_paths(
[
r_configs.get_r_cmd_config("BLAS_LIBS"),
r_configs.get_r_cmd_config("LAPACK_LIBS"),
r_configs.get_r_cmd_config("FLIBS"),
]
.to_vec(),
);
for path in lib_paths.iter() {
// Some R builds (e.g. homebrew) contain hardwired gfortran12
// paths, which may or may not exist if one has upgraded
// gfortran. So filter out non-existent ones, so that cargo
// doesn't complain.
if Path::new(path).exists() {
println!("cargo:rustc-link-search={}", path);
}
}
for lib in libs.iter() {
println!("cargo:rustc-link-lib=dylib={}", lib);
}
println!("cargo:rerun-if-changed=build.rs");
}