| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame^] | 1 | use crate::error::{Error, Result}; |
| 2 | use std::env; |
| 3 | use std::fs; |
| 4 | use std::os; |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | |
| 7 | fn out_dir() -> Result<PathBuf> { |
| 8 | env::var_os("OUT_DIR") |
| 9 | .map(PathBuf::from) |
| 10 | .ok_or(Error::MissingOutDir) |
| 11 | } |
| 12 | |
| 13 | pub(crate) fn cc_build() -> cc::Build { |
| 14 | try_cc_build().unwrap_or_default() |
| 15 | } |
| 16 | |
| 17 | fn 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. |
| 28 | pub(crate) fn symlink_header(path: &Path, original: &Path) { |
| 29 | let _ = try_symlink_header(path, original); |
| 30 | } |
| 31 | |
| 32 | fn 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 | |
| 45 | fn 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 | |
| 53 | pub(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 | |
| 62 | fn 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 | } |