blob: 866d377498a22b736ba91d9a262f1b185f56a5ff [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use crate::error::{Error, Result};
2use std::env;
3use std::fs;
4use std::os;
5use std::path::{Path, PathBuf};
6
7fn out_dir() -> Result<PathBuf> {
8 env::var_os("OUT_DIR")
9 .map(PathBuf::from)
10 .ok_or(Error::MissingOutDir)
11}
12
13pub(crate) fn cc_build() -> cc::Build {
14 try_cc_build().unwrap_or_default()
15}
16
17fn try_cc_build() -> Result<cc::Build> {
18 let target_dir = target_dir()?;
19
20 let mut build = cc::Build::new();
21 build.include(target_dir.join("cxxbridge"));
22 build.include(target_dir.parent().unwrap());
23 Ok(build)
24}
25
26// Symlink the header file into a predictable place. The header generated from
27// path/to/mod.rs gets linked to targets/cxxbridge/path/to/mod.h.
28pub(crate) fn symlink_header(path: &Path, original: &Path) {
29 let _ = try_symlink_header(path, original);
30}
31
32fn try_symlink_header(path: &Path, original: &Path) -> Result<()> {
33 let suffix = relative_to_parent_of_target_dir(original)?;
34 let dst = target_dir()?.join("cxxbridge").join(suffix);
35
36 fs::create_dir_all(dst.parent().unwrap())?;
37 #[cfg(unix)]
38 os::unix::fs::symlink(path, dst)?;
39 #[cfg(windows)]
40 os::windows::fs::symlink_file(path, dst)?;
41
42 Ok(())
43}
44
45fn relative_to_parent_of_target_dir(original: &Path) -> Result<PathBuf> {
46 let target_dir = target_dir()?;
47 let parent_of_target_dir = target_dir.parent().unwrap();
48 let original = original.canonicalize()?;
49 let suffix = original.strip_prefix(parent_of_target_dir)?;
50 Ok(suffix.to_owned())
51}
52
53pub(crate) fn out_with_extension(path: &Path, ext: &str) -> Result<PathBuf> {
54 let mut file_name = path.file_name().unwrap().to_owned();
55 file_name.push(ext);
56
57 let out_dir = out_dir()?;
58 let rel = relative_to_parent_of_target_dir(path)?;
59 Ok(out_dir.join(rel).with_file_name(file_name))
60}
61
62fn target_dir() -> Result<PathBuf> {
63 let mut dir = out_dir()?.canonicalize()?;
64 loop {
65 if dir.ends_with("target") {
66 return Ok(dir);
67 }
68 if !dir.pop() {
69 return Err(Error::TargetDir);
70 }
71 }
72}