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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use cmake::Config;

use std::{
    env, fmt, fs,
    path::{Path, PathBuf},
};

pub fn source_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("vendor")
}

// Returns Ok(()) is file was renamed,
// Returns Err(()) otherwise.
fn rename_libzmq_in_dir<D, N>(dir: D, new_name: N) -> Result<(), ()>
where
    D: AsRef<Path>,
    N: AsRef<Path>,
{
    let dir = dir.as_ref();
    let new_name = new_name.as_ref();

    for entry in fs::read_dir(dir).unwrap() {
        let file_name = entry.unwrap().file_name();
        if file_name.to_string_lossy().starts_with("libzmq") {
            fs::rename(dir.join(file_name), dir.join(new_name)).unwrap();
            return Ok(());
        }
    }

    Err(())
}

#[derive(Debug, Clone)]
pub struct Artifacts {
    include_dir: PathBuf,
    lib_dir: PathBuf,
    out_dir: PathBuf,
    pkg_config_dir: PathBuf,
    libs: Vec<Lib>,
}

impl Artifacts {
    pub fn include_dir(&self) -> &Path {
        &self.include_dir
    }

    pub fn lib_dir(&self) -> &Path {
        &self.lib_dir
    }
    pub fn pkg_config_dir(&self) -> &Path {
        &self.pkg_config_dir
    }

    pub fn out_dir(&self) -> &Path {
        &self.out_dir
    }

    pub fn libs(&self) -> &[Lib] {
        &self.libs
    }

    pub fn print_cargo_metadata(&self) {
        println!("cargo:rustc-link-search=native={}", self.lib_dir.display());
        for lib in self.libs.iter() {
            println!("cargo:rustc-link-lib={}{}", lib.link_type, lib.name);
        }
        println!("cargo:include={}", self.include_dir.display());
        println!("cargo:lib={}", self.lib_dir.display());
        println!("cargo:out={}", self.out_dir.display());
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum LinkType {
    Dynamic,
    Static,
    Unspecified,
}

impl fmt::Display for LinkType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            LinkType::Dynamic => write!(f, "dylib="),
            LinkType::Static => write!(f, "static="),
            LinkType::Unspecified => write!(f, ""),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum BuildType {
    Release,
    Debug,
}

#[derive(Debug, Clone)]
pub struct Lib {
    name: String,
    link_type: LinkType,
}

impl Lib {
    fn new<S>(name: S, link_type: LinkType) -> Self
    where
        S: Into<String>,
    {
        let name = name.into();

        Self { name, link_type }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn link_type(&self) -> LinkType {
        self.link_type
    }
}

#[derive(Debug, Clone)]
pub struct Build {
    enable_draft: bool,
    build_debug: bool,
    link_static: bool,
    perf_tool: bool,
}

impl Build {
    pub fn new() -> Self {
        Self {
            enable_draft: false,
            build_debug: false,
            link_static: false,
            perf_tool: false,
        }
    }

    /// Build & link statically instead of dynamically.
    pub fn link_static(&mut self, enabled: bool) -> &mut Self {
        self.link_static = enabled;
        self
    }

    /// Build the debug version of the lib.
    pub fn build_debug(&mut self, enabled: bool) -> &mut Self {
        self.build_debug = enabled;
        self
    }

    /// Enable the DRAFT API.
    pub fn enable_draft(&mut self, enabled: bool) -> &mut Self {
        self.enable_draft = enabled;
        self
    }

    pub fn perf_tool(&mut self, enabled: bool) -> &mut Self {
        self.perf_tool = enabled;
        self
    }

    pub fn build(&mut self) -> Artifacts {
        let mut config = Config::new(source_dir());

        config
            // For the LIBDIR to always be `lib`.
            .define("CMAKE_INSTALL_LIBDIR", "lib")
            // `libzmq` uses C99 but doesn't specify it.
            .define("CMAKE_C_STANDARD", "99")
            .define("ZMQ_BUILD_TESTS", "OFF");

        if self.enable_draft {
            config.define("ENABLE_DRAFTS", "ON");
        } else {
            config.define("ENABLE_DRAFTS", "OFF");
        }

        if self.build_debug {
            config.define("CMAKE_BUILD_TYPE", "Debug");
        } else {
            config.define("CMAKE_BUILD_TYPE", "Release");
        }

        if self.perf_tool {
            config.define("WITH_PERF_TOOL", "ON");
        } else {
            config.define("WITH_PERF_TOOL", "OFF");
        }

        let mut libs = vec![];

        let target = env::var("TARGET").unwrap();

        let link_type = {
            if self.link_static {
                config
                    .define("BUILD_SHARED", "OFF")
                    .define("BUILD_STATIC", "ON");

                if target.contains("msvc") {
                    config.cflag("-DZMQ_STATIC");
                }

                LinkType::Static
            } else {
                config
                    .define("BUILD_SHARED", "ON")
                    .define("BUILD_STATIC", "OFF");

                LinkType::Dynamic
            }
        };

        if target.contains("msvc") && link_type == LinkType::Dynamic {
            panic!("dynamic compilation is currently not supported on windows");
        }

        libs.push(Lib::new("zmq", link_type));

        if target.contains("apple")
            || target.contains("freebsd")
            || target.contains("openbsd")
        {
            libs.push(Lib::new("c++", LinkType::Dynamic));
        } else if target.contains("linux") {
            libs.push(Lib::new("stdc++", LinkType::Dynamic));
        } else if target.contains("msvc") {
            libs.push(Lib::new("iphlpapi", LinkType::Dynamic));
        }

        if target.contains("msvc") {
            // We need to explicitly disable `/GL` flag, otherwise
            // we get linkage error.
            config.cxxflag("/GL-");
            // Fix warning C4530: "C++ exception handler used, but unwind
            // semantics are not enabled. Specify /EHsc"
            config.cxxflag("/EHsc");
        }

        let out_dir = config.build();
        let lib_dir = out_dir.join("lib");
        let include_dir = out_dir.join("include");
        let pkg_config_dir = lib_dir.join("pkgconfig");

        // On windows we need to rename the static compiled lib
        // since its name is unpredictable.
        if target.contains("msvc") {
            if let Err(_) = rename_libzmq_in_dir(&lib_dir, "zmq.lib") {
                panic!("unable to find compiled `libzmq` lib");
            }
        }

        Artifacts {
            out_dir,
            lib_dir,
            include_dir,
            pkg_config_dir,
            libs,
        }
    }
}

impl Default for Build {
    fn default() -> Self {
        Self::new()
    }
}