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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//! A build dependency for running `cmake` to build a native library
//!
//! This crate provides some necessary boilerplate and shim support for running
//! the system `cmake` command to build a native library. It will add
//! appropriate cflags for building code to link into Rust, handle cross
//! compilation, and use the necessary generator for the platform being
//! targeted.
//!
//! The builder-style configuration allows for various variables and such to be
//! passed down into the build as well.
//!
//! ## Installation
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [build-dependencies]
//! cmake = "0.1"
//! ```
//!
//! ## Examples
//!
//! ```no_run
//! use cmake;
//!
//! // Builds the project in the directory located in `libfoo`, installing it
//! // into $OUT_DIR
//! let dst = cmake::build("libfoo");
//!
//! println!("cargo:rustc-link-search=native={}", dst.display());
//! println!("cargo:rustc-link-lib=static=foo");
//! ```
//!
//! ```no_run
//! use cmake::Config;
//!
//! let dst = Config::new("libfoo")
//!                  .define("FOO", "BAR")
//!                  .cflag("-foo")
//!                  .build();
//! println!("cargo:rustc-link-search=native={}", dst.display());
//! println!("cargo:rustc-link-lib=static=foo");
//! ```

#![deny(missing_docs)]

extern crate gcc;

use std::env;
use std::ffi::{OsString, OsStr};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Builder style configuration for a pending CMake build.
pub struct Config {
    path: PathBuf,
    cflags: OsString,
    defines: Vec<(OsString, OsString)>,
    deps: Vec<String>,
}

/// Builds the native library rooted at `path` with the default cmake options.
/// This will return the directory in which the library was installed.
///
/// # Examples
///
/// ```no_run
/// use cmake;
///
/// // Builds the project in the directory located in `libfoo`, installing it
/// // into $OUT_DIR
/// let dst = cmake::build("libfoo");
///
/// println!("cargo:rustc-link-search=native={}", dst.display());
/// println!("cargo:rustc-link-lib=static=foo");
/// ```
///
pub fn build<P: AsRef<Path>>(path: P) -> PathBuf {
    Config::new(path.as_ref()).build()
}

impl Config {
    /// Creates a new blank set of configuration to build the project specified
    /// at the path `path`.
    pub fn new<P: AsRef<Path>>(path: P) -> Config {
        Config {
            path: path.as_ref().to_path_buf(),
            cflags: OsString::new(),
            defines: Vec::new(),
            deps: Vec::new(),
        }
    }

    /// Adds a custom flag to pass down to the compiler, supplementing those
    /// that this library already passes.
    pub fn cflag<P: AsRef<OsStr>>(&mut self, flag: P) -> &mut Config {
        self.cflags.push(" ");
        self.cflags.push(flag.as_ref());
        self
    }

    /// Adds a new `-D` flag to pass to cmake during the generation step.
    pub fn define<K, V>(&mut self, k: K, v: V) -> &mut Config
        where K: AsRef<OsStr>, V: AsRef<OsStr>
    {
        self.defines.push((k.as_ref().to_owned(), v.as_ref().to_owned()));
        self
    }

    /// Registers a dependency for this compilation on the native library built
    /// by Cargo previously.
    ///
    /// This registration will modify the `CMAKE_PREFIX_PATH` environment
    /// variable for the build system generation step.
    pub fn register_dep(&mut self, dep: &str) -> &mut Config {
        self.deps.push(dep.to_string());
        self
    }

    /// Run this configuration, compiling the library with all the configured
    /// options.
    ///
    /// This will run both the build system generator command as well as the
    /// command to build the library.
    pub fn build(&mut self) -> PathBuf {
        let target = env::var("TARGET").unwrap();
        let msvc = target.contains("msvc");

        let dst = PathBuf::from(&env::var("OUT_DIR").unwrap());
        let _ = fs::create_dir(&dst.join("build"));

        // Build up the CFLAGS that we're going to use
        let mut cflags = env::var_os("CFLAGS").unwrap_or(OsString::new());
        cflags.push(" ");
        cflags.push(&self.cflags);
        if !msvc {
            cflags.push(" -ffunction-sections");
            cflags.push(" -fdata-sections");

            if target.contains("i686") {
                cflags.push(" -m32");
            } else if target.contains("x86_64") {
                cflags.push(" -m64");
            }
            if !target.contains("i686") {
                cflags.push(" -fPIC");
            }
        }

        // Add all our dependencies to our cmake paths
        let mut cmake_prefix_path = Vec::new();
        for dep in &self.deps {
            if let Some(root) = env::var_os(&format!("DEP_{}_ROOT", dep)) {
                cmake_prefix_path.push(PathBuf::from(root));
            }
        }
        let system_prefix = env::var_os("CMAKE_PREFIX_PATH")
                                .unwrap_or(OsString::new());
        cmake_prefix_path.extend(env::split_paths(&system_prefix)
                                     .map(|s| s.to_owned()));
        let cmake_prefix_path = env::join_paths(&cmake_prefix_path).unwrap();

        // Build up the first cmake command to build the build system.
        let mut cmd = Command::new("cmake");
        cmd.arg(env::current_dir().unwrap().join(&self.path))
           .current_dir(&dst.join("build"));
        if target.contains("windows-gnu") {
            // On MinGW we need to coerce cmake to not generate a visual studio
            // build system but instead use makefiles that MinGW can use to
            // build.
            cmd.arg("-G").arg("Unix Makefiles");
        } else if msvc {
            // If we're on MSVC we need to be sure to use the right generator or
            // otherwise we won't get 32/64 bit correct automatically.
            cmd.arg("-G").arg(self.visual_studio_generator(&target));
        }
        let profile = match &env::var("PROFILE").unwrap()[..] {
            "bench" | "release" => "Release",
            _ if msvc => "Release", // currently we need to always use the same CRT
            _ => "Debug",
        };
        for &(ref k, ref v) in &self.defines {
            let mut os = OsString::from("-D");
            os.push(k);
            os.push("=");
            os.push(v);
            cmd.arg(os);
        }
        let mut dstflag = OsString::from("-DCMAKE_INSTALL_PREFIX=");
        dstflag.push(&dst);
        let mut cflagsflag = OsString::from("-DCMAKE_C_FLAGS=");
        cflagsflag.push(&cflags);
        run(cmd.arg(&format!("-DCMAKE_BUILD_TYPE={}", profile))
               .arg(dstflag)
               .arg(cflagsflag)
               .env("CMAKE_PREFIX_PATH", cmake_prefix_path), "cmake");

        // And build!
        run(Command::new("cmake")
                    .arg("--build").arg(".")
                    .arg("--target").arg("install")
                    .arg("--config").arg(profile)
                    .current_dir(&dst.join("build")), "cmake");

        println!("cargo:root={}", dst.display());
        return dst
    }

    fn visual_studio_generator(&self, target: &str) -> String {
        // TODO: need a better way of scraping the VS install...
        let candidate = format!("{:?}", gcc::windows_registry::find(target,
                                                                    "cl.exe"));
        let base = if candidate.contains("12.0") {
            "Visual Studio 12 2013"
        } else if candidate.contains("14.0") {
            "Visual Studio 14 2015"
        } else {
            panic!("couldn't determine visual studio generator")
        };

        if target.contains("i686") {
            base.to_string()
        } else if target.contains("x86_64") {
            format!("{} Win64", base)
        } else {
            panic!("unsupported msvc target: {}", target);
        }
    }
}

fn run(cmd: &mut Command, program: &str) {
    println!("running: {:?}", cmd);
    let status = match cmd.status() {
        Ok(status) => status,
        Err(ref e) if e.kind() == ErrorKind::NotFound => {
            fail(&format!("failed to execute command: {}\nis `{}` not installed?",
                          e, program));
        }
        Err(e) => fail(&format!("failed to execute command: {}", e)),
    };
    if !status.success() {
        fail(&format!("command did not execute successfully, got: {}", status));
    }
}

fn fail(s: &str) -> ! {
    panic!("\n{}\n\nbuild script failed, must exit now", s)
}