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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;

use cargo_metadata::{Metadata, MetadataCommand};
use failure::{bail, err_msg, format_err, Error, ResultExt};
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
use toml;

use crate::build_context::BridgeModel;
use crate::cargo_toml::CargoTomlMetadata;
use crate::cargo_toml::CargoTomlMetadataPyo3Pack;
use crate::BuildContext;
use crate::CargoToml;
use crate::Manylinux;
use crate::Metadata21;
use crate::PythonInterpreter;
use crate::Target;

/// High level API for building wheels from a crate which is also used for the CLI
#[derive(Debug, Serialize, Deserialize, StructOpt, Clone, Eq, PartialEq)]
#[serde(default)]
pub struct BuildOptions {
    // The {n} are workarounds for https://github.com/TeXitoi/structopt/issues/163
    /// Control the platform tag on linux.
    ///
    /// - `1`: Use the manylinux1 tag and check for compliance{n}
    /// - `1-unchecked`: Use the manylinux1 tag without checking for compliance{n}
    /// - `2010`: Use the manylinux2010 tag and check for compliance{n}
    /// - `2010-unchecked`: Use the manylinux1 tag without checking for compliance{n}
    /// - `off`: Use the native linux tag (off)
    ///
    /// This option is ignored on all non-linux platforms
    #[structopt(
        long,
        raw(
            possible_values = r#"&["1", "1-unchecked", "2010", "2010-unchecked", "off"]"#,
            case_insensitive = "true",
            default_value = r#""1""#
        )
    )]
    pub manylinux: Manylinux,
    #[structopt(short, long)]
    /// The python versions to build wheels for, given as the names of the
    /// interpreters. Uses autodiscovery if not explicitly set.
    pub interpreter: Vec<String>,
    /// Which kind of bindings to use. Possible values are pyo3, rust-cpython, cffi and bin
    #[structopt(short, long)]
    pub bindings: Option<String>,
    #[structopt(
        short = "m",
        long = "manifest-path",
        parse(from_os_str),
        default_value = "Cargo.toml",
        name = "PATH"
    )]
    /// The path to the Cargo.toml
    pub manifest_path: PathBuf,
    /// The directory to store the built wheels in. Defaults to a new "wheels"
    /// directory in the project's target directory
    #[structopt(short, long, parse(from_os_str))]
    pub out: Option<PathBuf>,
    /// [deprecated, use --manylinux instead] Don't check for manylinux compliance
    #[structopt(long = "skip-auditwheel")]
    pub skip_auditwheel: bool,
    /// The --target option for cargo
    #[structopt(long, name = "TRIPLE")]
    pub target: Option<String>,
    /// Extra arguments that will be passed to cargo as `cargo rustc [...] [arg1] [arg2] --`
    ///
    /// Use as `--cargo-extra-args="--my-arg"`
    #[structopt(long = "cargo-extra-args")]
    pub cargo_extra_args: Vec<String>,
    /// Extra arguments that will be passed to rustc as `cargo rustc [...] -- [arg1] [arg2]`
    ///
    /// Use as `--rustc-extra-args="--my-arg"`
    #[structopt(long = "rustc-extra-args")]
    pub rustc_extra_args: Vec<String>,
}

impl Default for BuildOptions {
    fn default() -> Self {
        BuildOptions {
            manylinux: Manylinux::Manylinux1,
            interpreter: vec![],
            bindings: None,
            manifest_path: PathBuf::from("Cargo.toml"),
            out: None,
            skip_auditwheel: false,
            target: None,
            cargo_extra_args: Vec::new(),
            rustc_extra_args: Vec::new(),
        }
    }
}

impl BuildOptions {
    /// Tries to fill the missing metadata for a BuildContext by querying cargo and python
    pub fn into_build_context(self, release: bool, strip: bool) -> Result<BuildContext, Error> {
        let manifest_file = self
            .manifest_path
            .canonicalize()
            .context(format_err!("Can't find {}", self.manifest_path.display()))?;

        if !self.manifest_path.is_file() {
            bail!("{} must be a path to a Cargo.toml", manifest_file.display());
        };
        let contents = fs::read_to_string(&manifest_file).context(format!(
            "Can't read Cargo.toml at {}",
            manifest_file.display(),
        ))?;
        let cargo_toml: CargoToml = toml::from_str(&contents).context(format!(
            "Failed to parse Cargo.toml at {}",
            manifest_file.display()
        ))?;

        let manifest_dir = manifest_file.parent().unwrap().to_path_buf();
        let metadata21 = Metadata21::from_cargo_toml(&cargo_toml, &manifest_dir)
            .context("Failed to parse Cargo.toml into python metadata")?;
        let scripts = match cargo_toml.package.metadata {
            Some(CargoTomlMetadata {
                pyo3_pack:
                    Some(CargoTomlMetadataPyo3Pack {
                        scripts: Some(ref scripts),
                        ..
                    }),
            }) => scripts.clone(),
            _ => HashMap::new(),
        };

        // If the package name contains minuses, you must declare a module with
        // underscores as lib name
        let module_name = cargo_toml
            .lib
            .clone()
            .and_then(|lib| lib.name)
            .unwrap_or_else(|| cargo_toml.package.name.clone())
            .to_owned();

        let target = Target::from_target_triple(self.target.clone())?;

        // Failure fails here since cargo_metadata does some weird stuff on their side
        let cargo_metadata = MetadataCommand::new()
            .manifest_path(&self.manifest_path)
            .exec()
            .map_err(|e| format_err!("Cargo metadata failed: {}", e))?;

        let wheel_dir = match self.out {
            Some(ref dir) => dir.clone(),
            None => PathBuf::from(&cargo_metadata.target_directory).join("wheels"),
        };

        let bridge = find_bridge(&cargo_metadata, self.bindings.as_ref().map(|x| &**x))?;

        if bridge != BridgeModel::Bin && module_name.contains('-') {
            bail!(
                "The module name must not contains a minus \
                 (Make sure you have set an appropriate [lib] name in your Cargo.toml)"
            );
        }

        let interpreter = find_interpreter(&bridge, &self.interpreter, &target)?;

        let mut cargo_extra_args = split_extra_args(&self.cargo_extra_args)?;
        if let Some(target) = self.target {
            cargo_extra_args.extend_from_slice(&["--target".to_string(), target]);
        }

        let rustc_extra_args = split_extra_args(&self.rustc_extra_args)?;

        let manylinux = if self.skip_auditwheel {
            eprintln!("⚠ --skip-auditwheel is deprecated, use --manylinux=1-unchecked");
            Manylinux::Manylinux1Unchecked
        } else {
            self.manylinux
        };

        Ok(BuildContext {
            target,
            bridge,
            metadata21,
            scripts,
            module_name,
            manifest_path: self.manifest_path,
            out: wheel_dir,
            release,
            strip,
            manylinux,
            cargo_extra_args,
            rustc_extra_args,
            interpreter,
            cargo_metadata,
        })
    }
}

/// Tries to determine the [BridgeModel] for the target crate
pub fn find_bridge(cargo_metadata: &Metadata, bridge: Option<&str>) -> Result<BridgeModel, Error> {
    let deps: HashSet<String> = cargo_metadata
        .resolve
        .clone()
        .unwrap()
        .nodes
        .iter()
        .map(|node| cargo_metadata[&node.id].name.clone())
        .collect();

    if let Some(bindings) = bridge {
        if bindings == "cffi" {
            Ok(BridgeModel::Cffi)
        } else if bindings == "bin" {
            Ok(BridgeModel::Bin)
        } else {
            if !deps.contains(bindings) {
                bail!(
                    "The bindings crate {} was not found in the dependencies list",
                    bindings
                );
            }

            Ok(BridgeModel::Bindings(bindings.to_string()))
        }
    } else if deps.contains("pyo3") {
        println!("🔗 Found pyo3 bindings");
        Ok(BridgeModel::Bindings("pyo3".to_string()))
    } else if deps.contains("cpython") {
        println!("🔗 Found rust-cpython bindings");
        Ok(BridgeModel::Bindings("rust_cpython".to_string()))
    } else {
        bail!("Couldn't find any bindings; Please specify them with -b")
    }
}

/// Finds the appropriate amount for python versions for each [BridgeModel].
///
/// This means all for bindings, one for cffi and zero for bin.
pub fn find_interpreter(
    bridge: &BridgeModel,
    interpreter: &[String],
    target: &Target,
) -> Result<Vec<PythonInterpreter>, Error> {
    Ok(match bridge {
        BridgeModel::Bindings(_) => {
            let interpreter = if !interpreter.is_empty() {
                PythonInterpreter::check_executables(&interpreter, &target)?
            } else {
                PythonInterpreter::find_all(&target)?
            };

            if interpreter.is_empty() {
                bail!("Couldn't find any python interpreters. Please specify at least one with -i");
            }

            println!(
                "🐍 Found {}",
                interpreter
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<String>>()
                    .join(", ")
            );

            interpreter
        }
        BridgeModel::Cffi => {
            let executable = if interpreter.is_empty() {
                target.get_python()
            } else if interpreter.len() == 1 {
                PathBuf::from(interpreter[0].clone())
            } else {
                bail!("You can only specify one python interpreter for cffi compilation");
            };
            let err_message = "Failed to find python interpreter for generating cffi bindings";

            let interpreter = PythonInterpreter::check_executable(executable, &target)
                .context(err_msg(err_message))?
                .ok_or_else(|| err_msg(err_message))?;

            println!("🐍 Using {} to generate the cffi bindings", interpreter);

            vec![interpreter]
        }
        BridgeModel::Bin => vec![],
    })
}

/// Helper function that calls shlex on all extra args given
fn split_extra_args(given_args: &[String]) -> Result<Vec<String>, Error> {
    let mut splitted_args = vec![];
    for arg in given_args {
        match shlex::split(&arg) {
            Some(split) => splitted_args.extend(split),
            None => {
                bail!(
                    "Couldn't split argument from `--cargo-extra-args`: '{}'",
                    arg
                );
            }
        }
    }
    Ok(splitted_args)
}

#[cfg(test)]
mod test {
    use std::path::Path;

    use super::*;

    #[test]
    fn test_find_bridge_pyo3() {
        let get_fourtytwo = MetadataCommand::new()
            .manifest_path(&Path::new("get-fourtytwo").join("Cargo.toml"))
            .exec()
            .unwrap();

        assert!(match find_bridge(&get_fourtytwo, None).unwrap() {
            BridgeModel::Bindings(_) => true,
            _ => false,
        });

        assert!(match find_bridge(&get_fourtytwo, Some("pyo3")).unwrap() {
            BridgeModel::Bindings(_) => true,
            _ => false,
        });

        assert!(find_bridge(&get_fourtytwo, Some("rust-cpython")).is_err());
    }

    #[test]
    fn test_find_bridge_cffi() {
        let points = MetadataCommand::new()
            .manifest_path(&Path::new("points").join("Cargo.toml"))
            .exec()
            .unwrap();

        assert_eq!(
            find_bridge(&points, Some("cffi")).unwrap(),
            BridgeModel::Cffi
        );

        assert!(find_bridge(&points, Some("rust-cpython")).is_err());
        assert!(find_bridge(&points, Some("pyo3")).is_err());
    }

    #[test]
    fn test_find_bridge_bin() {
        let hello_world = MetadataCommand::new()
            .manifest_path(&Path::new("hello-world").join("Cargo.toml"))
            .exec()
            .unwrap();

        assert_eq!(
            find_bridge(&hello_world, Some("bin")).unwrap(),
            BridgeModel::Bin
        );

        assert!(find_bridge(&hello_world, None).is_err());
        assert!(find_bridge(&hello_world, Some("rust-cpython")).is_err());
        assert!(find_bridge(&hello_world, Some("pyo3")).is_err());
    }

    #[test]
    fn test_argument_splitting() {
        let mut options = BuildOptions::default();
        options.cargo_extra_args.push("--features foo".to_string());
        options.bindings = Some("bin".to_string());
        let context = options.into_build_context(false, false).unwrap();
        assert_eq!(context.cargo_extra_args, vec!["--features", "foo"])
    }
}