blob: 8e5d717c29c5fdc395c47282441c57ae438244a1 [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()?;
David Tolnay015c5e82020-01-26 16:31:48 -080047 let mut outer = target_dir.parent().unwrap();
David Tolnay7db73692019-10-20 14:51:12 -040048 let original = original.canonicalize()?;
David Tolnay015c5e82020-01-26 16:31:48 -080049 loop {
50 if let Ok(suffix) = original.strip_prefix(outer) {
51 return Ok(suffix.to_owned());
52 }
53 match outer.parent() {
54 Some(parent) => outer = parent,
55 None => return Ok(original.components().skip(1).collect()),
56 }
57 }
David Tolnay7db73692019-10-20 14:51:12 -040058}
59
60pub(crate) fn out_with_extension(path: &Path, ext: &str) -> Result<PathBuf> {
61 let mut file_name = path.file_name().unwrap().to_owned();
62 file_name.push(ext);
63
64 let out_dir = out_dir()?;
65 let rel = relative_to_parent_of_target_dir(path)?;
66 Ok(out_dir.join(rel).with_file_name(file_name))
67}
68
69fn target_dir() -> Result<PathBuf> {
70 let mut dir = out_dir()?.canonicalize()?;
71 loop {
72 if dir.ends_with("target") {
73 return Ok(dir);
74 }
75 if !dir.pop() {
76 return Err(Error::TargetDir);
77 }
78 }
79}