| 1 |
use crate::auditwheel::{AuditWheelMode, PlatformTag}; |
| 2 |
use crate::bridge::{Abi3Version, PyO3Crate}; |
| 3 |
use crate::compile::{CompileTarget, LIB_CRATE_TYPES}; |
| 4 |
use crate::compression::CompressionOptions; |
| 5 |
use crate::cross_compile::{find_sysconfigdata, parse_sysconfigdata}; |
| 6 |
use crate::project_layout::ProjectResolver; |
| 7 |
use crate::pyproject_toml::ToolMaturin; |
| 8 |
use crate::python_interpreter::{InterpreterConfig, InterpreterKind}; |
| 9 |
use crate::target::{detect_arch_from_python, is_arch_supported_by_pypi}; |
| 10 |
use crate::{BridgeModel, BuildContext, PyO3, PythonInterpreter, Target}; |
| 11 |
use anyhow::{bail, format_err, Context, Result}; |
| 12 |
use cargo_metadata::{CrateType, PackageId, TargetKind}; |
| 13 |
use cargo_metadata::{Metadata, Node}; |
| 14 |
use cargo_options::heading; |
| 15 |
use pep440_rs::VersionSpecifiers; |
| 16 |
use serde::{Deserialize, Serialize}; |
| 17 |
use std::collections::{HashMap, HashSet}; |
| 18 |
use std::env; |
| 19 |
use std::ops::{Deref, DerefMut}; |
| 20 |
use std::path::PathBuf; |
| 21 |
use std::str::FromStr; |
| 22 |
use tracing::{debug, instrument}; |
| 23 |
|
| 24 |
// This is used for `BridgeModel::PyO3`. |
| 25 |
// These should be treated almost identically but must be correctly identified |
| 26 |
// as one or the other in logs. pyo3-ffi is ordered first because it is newer |
| 27 |
// and more restrictive. |
| 28 |
const PYO3_BINDING_CRATES: [PyO3Crate; 2] = [PyO3Crate::PyO3Ffi, PyO3Crate::PyO3]; |
| 29 |
|
| 30 |
/// A Rust target triple or a virtual target triple. |
| 31 |
#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)] |
| 32 |
pub enum TargetTriple { |
| 33 |
/// The virtual `universal2-apple-darwin` target triple, build a fat binary of |
| 34 |
/// `aarch64-apple-darwin` and `x86_64-apple-darwin`. |
| 35 |
Universal2, |
| 36 |
/// Any target triple supported by Rust. |
| 37 |
/// |
| 38 |
/// It's not guaranteed that the value exists, it's passed verbatim to Cargo. |
| 39 |
Regular(String), |
| 40 |
} |
| 41 |
|
| 42 |
impl FromStr for TargetTriple { |
| 43 |
// TODO: Use the never type once stabilized |
| 44 |
type Err = String; |
| 45 |
|
| 46 |
fn from_str(triple: &str) -> std::result::Result<Self, Self::Err> { |
| 47 |
match triple { |
| 48 |
"universal2-apple-darwin" => Ok(TargetTriple::Universal2), |
| 49 |
triple => Ok(TargetTriple::Regular(triple.to_string())), |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
/// Cargo options for the build process |
| 55 |
#[derive(Debug, Default, Serialize, Deserialize, clap::Parser, Clone, Eq, PartialEq)] |
| 56 |
#[serde(default, rename_all = "kebab-case")] |
| 57 |
pub struct CargoOptions { |
| 58 |
/// Do not print cargo log messages |
| 59 |
#[arg(short = 'q', long)] |
| 60 |
pub quiet: bool, |
| 61 |
|
| 62 |
/// Number of parallel jobs, defaults to # of CPUs |
| 63 |
#[arg(short = 'j', long, value_name = "N", help_heading = heading::COMPILATION_OPTIONS)] |
| 64 |
pub jobs: Option<usize>, |
| 65 |
|
| 66 |
/// Build artifacts with the specified Cargo profile |
| 67 |
#[arg(long, value_name = "PROFILE-NAME", help_heading = heading::COMPILATION_OPTIONS)] |
| 68 |
pub profile: Option<String>, |
| 69 |
|
| 70 |
/// Space or comma separated list of features to activate |
| 71 |
#[arg( |
| 72 |
short = 'F', |
| 73 |
long, |
| 74 |
action = clap::ArgAction::Append, |
| 75 |
help_heading = heading::FEATURE_SELECTION, |
| 76 |
)] |
| 77 |
pub features: Vec<String>, |
| 78 |
|
| 79 |
/// Activate all available features |
| 80 |
#[arg(long, help_heading = heading::FEATURE_SELECTION)] |
| 81 |
pub all_features: bool, |
| 82 |
|
| 83 |
/// Do not activate the `default` feature |
| 84 |
#[arg(long, help_heading = heading::FEATURE_SELECTION)] |
| 85 |
pub no_default_features: bool, |
| 86 |
|
| 87 |
/// Build for the target triple |
| 88 |
#[arg( |
| 89 |
long, |
| 90 |
value_name = "TRIPLE", |
| 91 |
env = "CARGO_BUILD_TARGET", |
| 92 |
help_heading = heading::COMPILATION_OPTIONS, |
| 93 |
)] |
| 94 |
pub target: Option<TargetTriple>, |
| 95 |
|
| 96 |
/// Directory for all generated artifacts |
| 97 |
#[arg(long, value_name = "DIRECTORY", help_heading = heading::COMPILATION_OPTIONS)] |
| 98 |
pub target_dir: Option<PathBuf>, |
| 99 |
|
| 100 |
/// Path to Cargo.toml |
| 101 |
#[arg(short = 'm', long, value_name = "PATH", help_heading = heading::MANIFEST_OPTIONS)] |
| 102 |
pub manifest_path: Option<PathBuf>, |
| 103 |
|
| 104 |
/// Ignore `rust-version` specification in packages |
| 105 |
#[arg(long)] |
| 106 |
pub ignore_rust_version: bool, |
| 107 |
|
| 108 |
/// Use verbose output (-vv very verbose/build.rs output) |
| 109 |
// Note that this duplicates the global option, but clap seems to be fine with that. |
| 110 |
#[arg(short = 'v', long, action = clap::ArgAction::Count)] |
| 111 |
pub verbose: u8, |
| 112 |
|
| 113 |
/// Coloring: auto, always, never |
| 114 |
#[arg(long, value_name = "WHEN")] |
| 115 |
pub color: Option<String>, |
| 116 |
|
| 117 |
/// Require Cargo.lock and cache are up to date |
| 118 |
#[arg(long, help_heading = heading::MANIFEST_OPTIONS)] |
| 119 |
pub frozen: bool, |
| 120 |
|
| 121 |
/// Require Cargo.lock is up to date |
| 122 |
#[arg(long, help_heading = heading::MANIFEST_OPTIONS)] |
| 123 |
pub locked: bool, |
| 124 |
|
| 125 |
/// Run without accessing the network |
| 126 |
#[arg(long, help_heading = heading::MANIFEST_OPTIONS)] |
| 127 |
pub offline: bool, |
| 128 |
|
| 129 |
/// Override a configuration value (unstable) |
| 130 |
#[arg(long, value_name = "KEY=VALUE", action = clap::ArgAction::Append)] |
| 131 |
pub config: Vec<String>, |
| 132 |
|
| 133 |
/// Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details |
| 134 |
#[arg(short = 'Z', value_name = "FLAG", action = clap::ArgAction::Append)] |
| 135 |
pub unstable_flags: Vec<String>, |
| 136 |
|
| 137 |
/// Timing output formats (unstable) (comma separated): html, json |
| 138 |
#[arg( |
| 139 |
long, |
| 140 |
value_name = "FMTS", |
| 141 |
value_delimiter = ',', |
| 142 |
require_equals = true, |
| 143 |
help_heading = heading::COMPILATION_OPTIONS, |
| 144 |
)] |
| 145 |
pub timings: Option<Vec<String>>, |
| 146 |
|
| 147 |
/// Outputs a future incompatibility report at the end of the build (unstable) |
| 148 |
#[arg(long)] |
| 149 |
pub future_incompat_report: bool, |
| 150 |
|
| 151 |
/// Rustc flags |
| 152 |
#[arg(num_args = 0.., trailing_var_arg = true)] |
| 153 |
pub args: Vec<String>, |
| 154 |
} |
| 155 |
|
| 156 |
/// High level API for building wheels from a crate which is also used for the CLI |
| 157 |
#[derive(Debug, Default, Serialize, Deserialize, clap::Parser, Clone, Eq, PartialEq)] |
| 158 |
#[serde(default)] |
| 159 |
pub struct BuildOptions { |
| 160 |
/// Control the platform tag and PyPI compatibility. |
| 161 |
/// |
| 162 |
/// This options offers both fine-grained control over the linux libc tag and a more automatic |
| 163 |
/// PyPI-compatibility option. |
| 164 |
/// |
| 165 |
/// The `pypi` option applies on all platforms and ensure that only tags that can be uploaded to |
| 166 |
/// PyPI are used. The linux-specific options are `manylinux` tags (for example |
| 167 |
/// `manylinux2014`/`manylinux_2_24`) or `musllinux` tags (for example `musllinux_1_2`), |
| 168 |
/// and `linux` for the native linux tag. They are ignored on non-linux platforms. |
| 169 |
/// |
| 170 |
/// Note that `manylinux1` and `manylinux2010` are unsupported by the rust compiler. |
| 171 |
/// Wheels with the native `linux` tag will be rejected by pypi, |
| 172 |
/// unless they are separately validated by `auditwheel`. |
| 173 |
/// |
| 174 |
/// The default is the lowest compatible `manylinux` tag, or plain `linux` if nothing matched. |
| 175 |
#[arg( |
| 176 |
id = "compatibility", |
| 177 |
long = "compatibility", |
| 178 |
alias = "manylinux", |
| 179 |
num_args = 0.., |
| 180 |
action = clap::ArgAction::Append |
| 181 |
)] |
| 182 |
pub platform_tag: Vec<PlatformTag>, |
| 183 |
|
| 184 |
/// The python versions to build wheels for, given as the executables of |
| 185 |
/// interpreters such as `python3.9` or `/usr/bin/python3.8`. |
| 186 |
#[arg(short, long, num_args = 0.., action = clap::ArgAction::Append)] |
| 187 |
pub interpreter: Vec<PathBuf>, |
| 188 |
|
| 189 |
/// Find interpreters from the host machine |
| 190 |
#[arg(short = 'f', long, conflicts_with = "interpreter")] |
| 191 |
pub find_interpreter: bool, |
| 192 |
|
| 193 |
/// Which kind of bindings to use. |
| 194 |
#[arg(short, long, value_parser = ["pyo3", "pyo3-ffi", "cffi", "uniffi", "bin"])] |
| 195 |
pub bindings: Option<String>, |
| 196 |
|
| 197 |
/// The directory to store the built wheels in. Defaults to a new "wheels" |
| 198 |
/// directory in the project's target directory |
| 199 |
#[arg(short, long)] |
| 200 |
pub out: Option<PathBuf>, |
| 201 |
|
| 202 |
/// Audit wheel for manylinux compliance |
| 203 |
#[arg(long, conflicts_with = "skip_auditwheel")] |
| 204 |
pub auditwheel: Option<AuditWheelMode>, |
| 205 |
|
| 206 |
/// Don't check for manylinux compliance |
| 207 |
#[arg(long, hide = true)] |
| 208 |
pub skip_auditwheel: bool, |
| 209 |
|
| 210 |
/// For manylinux targets, use zig to ensure compliance for the chosen manylinux version |
| 211 |
/// |
| 212 |
/// Default to manylinux2014/manylinux_2_17 if you do not specify an `--compatibility` |
| 213 |
/// |
| 214 |
/// Make sure you installed zig with `pip install maturin[zig]` |
| 215 |
#[cfg(feature = "zig")] |
| 216 |
#[arg(long)] |
| 217 |
pub zig: bool, |
| 218 |
|
| 219 |
/// Cargo build options |
| 220 |
#[command(flatten)] |
| 221 |
pub cargo: CargoOptions, |
| 222 |
|
| 223 |
/// Wheel compression options |
| 224 |
#[command(flatten)] |
| 225 |
pub compression: CompressionOptions, |
| 226 |
} |
| 227 |
|
| 228 |
impl Deref for BuildOptions { |
| 229 |
type Target = CargoOptions; |
| 230 |
|
| 231 |
fn deref(&self) -> &Self::Target { |
| 232 |
&self.cargo |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
impl DerefMut for BuildOptions { |
| 237 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 238 |
&mut self.cargo |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
impl BuildOptions { |
| 243 |
/// Finds the appropriate amount for python versions for each [BridgeModel]. |
| 244 |
fn find_interpreters( |
| 245 |
&self, |
| 246 |
bridge: &BridgeModel, |
| 247 |
interpreter: &[PathBuf], |
| 248 |
target: &Target, |
| 249 |
requires_python: Option<&VersionSpecifiers>, |
| 250 |
generate_import_lib: bool, |
| 251 |
) -> Result<Vec<PythonInterpreter>> { |
| 252 |
match bridge { |
| 253 |
BridgeModel::PyO3(PyO3 { abi3, .. }) | BridgeModel::Bin(Some(PyO3 { abi3, .. })) => { |
| 254 |
match abi3 { |
| 255 |
None | Some(Abi3Version::CurrentPython) => { |
| 256 |
let mut interpreters = Vec::new(); |
| 257 |
if let Some(config_file) = env::var_os("PYO3_CONFIG_FILE") { |
| 258 |
let interpreter_config = |
| 259 |
InterpreterConfig::from_pyo3_config(config_file.as_ref(), target) |
| 260 |
.context("Invalid PYO3_CONFIG_FILE")?; |
| 261 |
interpreters.push(PythonInterpreter::from_config(interpreter_config)); |
| 262 |
} else if target.cross_compiling() { |
| 263 |
if let Some(cross_lib_dir) = env::var_os("PYO3_CROSS_LIB_DIR") { |
| 264 |
let host_interpreters = find_interpreter_in_host( |
| 265 |
bridge, |
| 266 |
interpreter, |
| 267 |
target, |
| 268 |
requires_python, |
| 269 |
)?; |
| 270 |
let host_python = &host_interpreters[0]; |
| 271 |
eprintln!( |
| 272 |
"🐍 Using host {host_python} for cross-compiling preparation" |
| 273 |
); |
| 274 |
// pyo3 |
| 275 |
env::set_var("PYO3_PYTHON", &host_python.executable); |
| 276 |
// legacy pyo3 versions |
| 277 |
env::set_var("PYTHON_SYS_EXECUTABLE", &host_python.executable); |
| 278 |
|
| 279 |
let sysconfig_path = |
| 280 |
find_sysconfigdata(cross_lib_dir.as_ref(), target)?; |
| 281 |
env::set_var( |
| 282 |
"MATURIN_PYTHON_SYSCONFIGDATA_DIR", |
| 283 |
sysconfig_path.parent().unwrap(), |
| 284 |
); |
| 285 |
|
| 286 |
let sysconfig_data = |
| 287 |
parse_sysconfigdata(host_python, sysconfig_path)?; |
| 288 |
let major = sysconfig_data |
| 289 |
.get("version_major") |
| 290 |
.context("version_major is not defined")? |
| 291 |
.parse::<usize>() |
| 292 |
.context("Could not parse value of version_major")?; |
| 293 |
let minor = sysconfig_data |
| 294 |
.get("version_minor") |
| 295 |
.context("version_minor is not defined")? |
| 296 |
.parse::<usize>() |
| 297 |
.context("Could not parse value of version_minor")?; |
| 298 |
let abiflags = sysconfig_data |
| 299 |
.get("ABIFLAGS") |
| 300 |
.map(ToString::to_string) |
| 301 |
.unwrap_or_default(); |
| 302 |
let gil_disabled = sysconfig_data |
| 303 |
.get("Py_GIL_DISABLED") |
| 304 |
.map(|x| x == "1") |
| 305 |
.unwrap_or_default(); |
| 306 |
let ext_suffix = sysconfig_data |
| 307 |
.get("EXT_SUFFIX") |
| 308 |
.context("syconfig didn't define an `EXT_SUFFIX` ಠ_ಠ")?; |
| 309 |
let soabi = sysconfig_data.get("SOABI"); |
| 310 |
let interpreter_kind = soabi |
| 311 |
.and_then(|tag| { |
| 312 |
if tag.starts_with("pypy") { |
| 313 |
Some(InterpreterKind::PyPy) |
| 314 |
} else if tag.starts_with("cpython") { |
| 315 |
Some(InterpreterKind::CPython) |
| 316 |
} else if tag.starts_with("graalpy") { |
| 317 |
Some(InterpreterKind::GraalPy) |
| 318 |
} else { |
| 319 |
None |
| 320 |
} |
| 321 |
}) |
| 322 |
.context("unsupported Python interpreter")?; |
| 323 |
interpreters.push(PythonInterpreter { |
| 324 |
config: InterpreterConfig { |
| 325 |
major, |
| 326 |
minor, |
| 327 |
interpreter_kind, |
| 328 |
abiflags, |
| 329 |
ext_suffix: ext_suffix.to_string(), |
| 330 |
pointer_width: None, |
| 331 |
gil_disabled, |
| 332 |
}, |
| 333 |
executable: PathBuf::new(), |
| 334 |
platform: None, |
| 335 |
runnable: false, |
| 336 |
implementation_name: interpreter_kind |
| 337 |
.to_string() |
| 338 |
.to_ascii_lowercase(), |
| 339 |
soabi: soabi.cloned(), |
| 340 |
}); |
| 341 |
} else { |
| 342 |
if interpreter.is_empty() && !self.find_interpreter { |
| 343 |
bail!("Couldn't find any python interpreters. Please specify at least one with -i"); |
| 344 |
} |
| 345 |
for interp in interpreter { |
| 346 |
// If `-i` looks like a file path, check if it's a valid interpreter |
| 347 |
if interp.components().count() > 1 |
| 348 |
&& PythonInterpreter::check_executable( |
| 349 |
interp, target, bridge, |
| 350 |
)? |
| 351 |
.is_none() |
| 352 |
{ |
| 353 |
bail!( |
| 354 |
"{} is not a valid python interpreter", |
| 355 |
interp.display() |
| 356 |
); |
| 357 |
} |
| 358 |
} |
| 359 |
interpreters = find_interpreter_in_sysconfig( |
| 360 |
bridge, |
| 361 |
interpreter, |
| 362 |
target, |
| 363 |
requires_python, |
| 364 |
)?; |
| 365 |
if interpreters.is_empty() { |
| 366 |
bail!( |
| 367 |
"Couldn't find any python interpreters from '{}'. Please check that both major and minor python version have been specified in -i/--interpreter.", |
| 368 |
interpreter |
| 369 |
.iter() |
| 370 |
.map(|p| p.display().to_string()) |
| 371 |
.collect::<Vec<_>>() |
| 372 |
.join(", ") |
| 373 |
); |
| 374 |
} |
| 375 |
} |
| 376 |
} else { |
| 377 |
interpreters = |
| 378 |
find_interpreter(bridge, interpreter, target, requires_python)?; |
| 379 |
} |
| 380 |
|
| 381 |
let interpreters_str = interpreters |
| 382 |
.iter() |
| 383 |
.map(ToString::to_string) |
| 384 |
.collect::<Vec<String>>() |
| 385 |
.join(", "); |
| 386 |
eprintln!("🐍 Found {interpreters_str}"); |
| 387 |
|
| 388 |
Ok(interpreters) |
| 389 |
} |
| 390 |
Some(Abi3Version::Version(major, minor)) => { |
| 391 |
let found_interpreters = |
| 392 |
find_interpreter_in_host(bridge, interpreter, target, requires_python) |
| 393 |
.or_else(|err| { |
| 394 |
// Can only use sysconfig-derived interpreter on windows if generating the import lib |
| 395 |
if target.is_windows() && !generate_import_lib { |
| 396 |
return Err(err.context("Need a Python interpreter to compile for Windows without PyO3's `generate-import-lib` feature")); |
| 397 |
} |
| 398 |
|
| 399 |
let interps = |
| 400 |
find_interpreter_in_sysconfig(bridge, interpreter, target, requires_python) |
| 401 |
.unwrap_or_default(); |
| 402 |
if interps.is_empty() && !self.interpreter.is_empty() { |
| 403 |
// Print error when user supplied `--interpreter` option |
| 404 |
Err(err) |
| 405 |
} else { |
| 406 |
Ok(interps) |
| 407 |
} |
| 408 |
})?; |
| 409 |
|
| 410 |
if target.is_windows() { |
| 411 |
// On windows we might need a Python executable to locate a base prefix for |
| 412 |
// linker args, if we're not using PyO3's `generate-import-lib` feature. |
| 413 |
if env::var_os("PYO3_CROSS_LIB_DIR").is_some() { |
| 414 |
// PYO3_CROSS_LIB_DIR should point to the `libs` directory inside base_prefix |
| 415 |
// when cross compiling, so we fake a python interpreter matching it |
| 416 |
eprintln!("⚠️ Cross-compiling is poorly supported"); |
| 417 |
Ok(vec![PythonInterpreter { |
| 418 |
config: InterpreterConfig { |
| 419 |
major: *major as usize, |
| 420 |
minor: *minor as usize, |
| 421 |
interpreter_kind: InterpreterKind::CPython, |
| 422 |
abiflags: "".to_string(), |
| 423 |
ext_suffix: ".pyd".to_string(), |
| 424 |
pointer_width: None, |
| 425 |
gil_disabled: false, |
| 426 |
}, |
| 427 |
executable: PathBuf::new(), |
| 428 |
platform: None, |
| 429 |
runnable: false, |
| 430 |
implementation_name: "cpython".to_string(), |
| 431 |
soabi: None, |
| 432 |
}]) |
| 433 |
} else if let Some(config_file) = env::var_os("PYO3_CONFIG_FILE") { |
| 434 |
let interpreter_config = InterpreterConfig::from_pyo3_config( |
| 435 |
config_file.as_ref(), |
| 436 |
target, |
| 437 |
) |
| 438 |
.context("Invalid PYO3_CONFIG_FILE")?; |
| 439 |
Ok(vec![PythonInterpreter::from_config(interpreter_config)]) |
| 440 |
} else if generate_import_lib { |
| 441 |
eprintln!("🐍 Not using a specific python interpreter (automatically generating windows import library)"); |
| 442 |
let mut found_interpreters = found_interpreters; |
| 443 |
// fake a python interpreter if none directly found |
| 444 |
if found_interpreters.is_empty() { |
| 445 |
found_interpreters.push(PythonInterpreter { |
| 446 |
config: InterpreterConfig { |
| 447 |
major: *major as usize, |
| 448 |
minor: *minor as usize, |
| 449 |
interpreter_kind: InterpreterKind::CPython, |
| 450 |
abiflags: "".to_string(), |
| 451 |
ext_suffix: ".pyd".to_string(), |
| 452 |
pointer_width: None, |
| 453 |
gil_disabled: false, |
| 454 |
}, |
| 455 |
executable: PathBuf::new(), |
| 456 |
platform: None, |
| 457 |
runnable: false, |
| 458 |
implementation_name: "cpython".to_string(), |
| 459 |
soabi: None, |
| 460 |
}) |
| 461 |
} |
| 462 |
Ok(found_interpreters) |
| 463 |
} else { |
| 464 |
if found_interpreters.is_empty() { |
| 465 |
bail!("Failed to find any python interpreter"); |
| 466 |
} |
| 467 |
Ok(found_interpreters) |
| 468 |
} |
| 469 |
} else { |
| 470 |
eprintln!("🐍 Not using a specific python interpreter"); |
| 471 |
if self.interpreter.is_empty() { |
| 472 |
// Fake one to make `BuildContext::build_wheels` happy for abi3 when no cpython/pypy found on host |
| 473 |
// The python interpreter config doesn't matter, as it's not used for anything |
| 474 |
Ok(vec![PythonInterpreter { |
| 475 |
config: InterpreterConfig { |
| 476 |
major: *major as usize, |
| 477 |
minor: *minor as usize, |
| 478 |
interpreter_kind: InterpreterKind::CPython, |
| 479 |
abiflags: "".to_string(), |
| 480 |
ext_suffix: "".to_string(), |
| 481 |
pointer_width: None, |
| 482 |
gil_disabled: false, |
| 483 |
}, |
| 484 |
executable: PathBuf::new(), |
| 485 |
platform: None, |
| 486 |
runnable: false, |
| 487 |
implementation_name: "cpython".to_string(), |
| 488 |
soabi: None, |
| 489 |
}]) |
| 490 |
} else if target.cross_compiling() { |
| 491 |
let mut interps = Vec::with_capacity(found_interpreters.len()); |
| 492 |
let mut pypys = Vec::new(); |
| 493 |
for interp in found_interpreters { |
| 494 |
if interp.interpreter_kind.is_pypy() { |
| 495 |
pypys.push(PathBuf::from(format!( |
| 496 |
"pypy{}.{}", |
| 497 |
interp.major, interp.minor |
| 498 |
))); |
| 499 |
} else { |
| 500 |
interps.push(interp); |
| 501 |
} |
| 502 |
} |
| 503 |
// cross compiling to PyPy with abi3 feature enabled, |
| 504 |
// we cannot use host pypy so switch to bundled sysconfig instead |
| 505 |
if !pypys.is_empty() { |
| 506 |
interps.extend(find_interpreter_in_sysconfig( |
| 507 |
bridge, |
| 508 |
&pypys, |
| 509 |
target, |
| 510 |
requires_python, |
| 511 |
)?) |
| 512 |
} |
| 513 |
if interps.is_empty() { |
| 514 |
bail!("Failed to find any python interpreter"); |
| 515 |
} |
| 516 |
Ok(interps) |
| 517 |
} else { |
| 518 |
if found_interpreters.is_empty() { |
| 519 |
bail!("Failed to find any python interpreter"); |
| 520 |
} |
| 521 |
Ok(found_interpreters) |
| 522 |
} |
| 523 |
} |
| 524 |
} |
| 525 |
} |
| 526 |
} |
| 527 |
BridgeModel::Cffi => { |
| 528 |
let interpreter = |
| 529 |
find_single_python_interpreter(bridge, interpreter, target, "cffi")?; |
| 530 |
eprintln!("🐍 Using {interpreter} to generate the cffi bindings"); |
| 531 |
Ok(vec![interpreter]) |
| 532 |
} |
| 533 |
BridgeModel::Bin(None) | BridgeModel::UniFfi => Ok(vec![]), |
| 534 |
} |
| 535 |
} |
| 536 |
|
| 537 |
/// Tries to fill the missing metadata for a BuildContext by querying cargo and python |
| 538 |
#[instrument(skip_all)] |
| 539 |
pub fn into_build_context(self) -> BuildContextBuilder { |
| 540 |
BuildContextBuilder::new(self) |
| 541 |
} |
| 542 |
} |
| 543 |
|
| 544 |
#[derive(Debug)] |
| 545 |
pub struct BuildContextBuilder { |
| 546 |
build_options: BuildOptions, |
| 547 |
release: bool, |
| 548 |
strip: bool, |
| 549 |
editable: bool, |
| 550 |
sdist_only: bool, |
| 551 |
} |
| 552 |
|
| 553 |
impl BuildContextBuilder { |
| 554 |
fn new(build_options: BuildOptions) -> Self { |
| 555 |
Self { |
| 556 |
build_options, |
| 557 |
release: false, |
| 558 |
strip: false, |
| 559 |
editable: false, |
| 560 |
sdist_only: false, |
| 561 |
} |
| 562 |
} |
| 563 |
|
| 564 |
pub fn release(mut self, release: bool) -> Self { |
| 565 |
self.release = release; |
| 566 |
self |
| 567 |
} |
| 568 |
|
| 569 |
pub fn strip(mut self, strip: bool) -> Self { |
| 570 |
self.strip = strip; |
| 571 |
self |
| 572 |
} |
| 573 |
|
| 574 |
pub fn editable(mut self, editable: bool) -> Self { |
| 575 |
self.editable = editable; |
| 576 |
self |
| 577 |
} |
| 578 |
|
| 579 |
pub fn sdist_only(mut self, sdist_only: bool) -> Self { |
| 580 |
self.sdist_only = sdist_only; |
| 581 |
self |
| 582 |
} |
| 583 |
|
| 584 |
pub fn build(self) -> Result<BuildContext> { |
| 585 |
let Self { |
| 586 |
build_options, |
| 587 |
release, |
| 588 |
strip, |
| 589 |
editable, |
| 590 |
sdist_only, |
| 591 |
} = self; |
| 592 |
build_options.compression.validate(); |
| 593 |
let ProjectResolver { |
| 594 |
project_layout, |
| 595 |
cargo_toml_path, |
| 596 |
cargo_toml, |
| 597 |
pyproject_toml_path, |
| 598 |
pyproject_toml, |
| 599 |
module_name, |
| 600 |
metadata24, |
| 601 |
mut cargo_options, |
| 602 |
cargo_metadata, |
| 603 |
mut pyproject_toml_maturin_options, |
| 604 |
} = ProjectResolver::resolve( |
| 605 |
build_options.manifest_path.clone(), |
| 606 |
build_options.cargo.clone(), |
| 607 |
)?; |
| 608 |
let pyproject = pyproject_toml.as_ref(); |
| 609 |
|
| 610 |
let bridge = find_bridge( |
| 611 |
&cargo_metadata, |
| 612 |
build_options.bindings.as_deref().or_else(|| { |
| 613 |
pyproject.and_then(|x| { |
| 614 |
if x.bindings().is_some() { |
| 615 |
pyproject_toml_maturin_options.push("bindings"); |
| 616 |
} |
| 617 |
x.bindings() |
| 618 |
}) |
| 619 |
}), |
| 620 |
)?; |
| 621 |
debug!("Resolved bridge model: {:?}", bridge); |
| 622 |
|
| 623 |
if !bridge.is_bin() && project_layout.extension_name.contains('-') { |
| 624 |
bail!( |
| 625 |
"The module name must not contain a minus `-` \ |
| 626 |
(Make sure you have set an appropriate [lib] name or \ |
| 627 |
[tool.maturin] module-name in your pyproject.toml)" |
| 628 |
); |
| 629 |
} |
| 630 |
|
| 631 |
let mut target_triple = build_options.target.clone(); |
| 632 |
|
| 633 |
let mut universal2 = target_triple == Some(TargetTriple::Universal2); |
| 634 |
// Also try to determine universal2 from ARCHFLAGS environment variable |
| 635 |
if target_triple.is_none() { |
| 636 |
if let Ok(arch_flags) = env::var("ARCHFLAGS") { |
| 637 |
let arches: HashSet<&str> = arch_flags |
| 638 |
.split("-arch") |
| 639 |
.filter_map(|x| { |
| 640 |
let x = x.trim(); |
| 641 |
if x.is_empty() { |
| 642 |
None |
| 643 |
} else { |
| 644 |
Some(x) |
| 645 |
} |
| 646 |
}) |
| 647 |
.collect(); |
| 648 |
match (arches.contains("x86_64"), arches.contains("arm64")) { |
| 649 |
(true, true) => universal2 = true, |
| 650 |
(true, false) => { |
| 651 |
target_triple = |
| 652 |
Some(TargetTriple::Regular("x86_64-apple-darwin".to_string())) |
| 653 |
} |
| 654 |
(false, true) => { |
| 655 |
target_triple = |
| 656 |
Some(TargetTriple::Regular("aarch64-apple-darwin".to_string())) |
| 657 |
} |
| 658 |
(false, false) => {} |
| 659 |
} |
| 660 |
}; |
| 661 |
} |
| 662 |
if universal2 { |
| 663 |
// Ensure that target_triple is valid. This is necessary to properly |
| 664 |
// infer the platform tags when cross-compiling from Linux. |
| 665 |
target_triple = Some(TargetTriple::Regular("aarch64-apple-darwin".to_string())); |
| 666 |
} |
| 667 |
|
| 668 |
let mut target = Target::from_target_triple(target_triple.as_ref())?; |
| 669 |
if !target.user_specified && !universal2 { |
| 670 |
if let Some(interpreter) = build_options.interpreter.first() { |
| 671 |
if let Some(detected_target) = detect_arch_from_python(interpreter, &target) { |
| 672 |
target = Target::from_target_triple(Some(&detected_target))?; |
| 673 |
} |
| 674 |
} |
| 675 |
} |
| 676 |
|
| 677 |
let wheel_dir = match build_options.out { |
| 678 |
Some(ref dir) => dir.clone(), |
| 679 |
None => PathBuf::from(&cargo_metadata.target_directory).join("wheels"), |
| 680 |
}; |
| 681 |
|
| 682 |
let generate_import_lib = is_generating_import_lib(&cargo_metadata)?; |
| 683 |
let interpreter = if sdist_only && env::var_os("MATURIN_TEST_PYTHON").is_none() { |
| 684 |
// We don't need a python interpreter to build sdist only |
| 685 |
Vec::new() |
| 686 |
} else { |
| 687 |
resolve_interpreters( |
| 688 |
&build_options, |
| 689 |
&bridge, |
| 690 |
&target, |
| 691 |
metadata24.requires_python.as_ref(), |
| 692 |
generate_import_lib, |
| 693 |
)? |
| 694 |
}; |
| 695 |
|
| 696 |
if cargo_options.args.is_empty() { |
| 697 |
// if not supplied on command line, try pyproject.toml |
| 698 |
let tool_maturin = pyproject.and_then(|p| p.maturin()); |
| 699 |
if let Some(args) = tool_maturin.and_then(|x| x.rustc_args.as_ref()) { |
| 700 |
cargo_options.args.extend(args.iter().cloned()); |
| 701 |
pyproject_toml_maturin_options.push("rustc-args"); |
| 702 |
} |
| 703 |
} |
| 704 |
|
| 705 |
let strip = pyproject.map(|x| x.strip()).unwrap_or_default() || strip; |
| 706 |
let skip_auditwheel = pyproject.map(|x| x.skip_auditwheel()).unwrap_or_default() |
| 707 |
|| build_options.skip_auditwheel; |
| 708 |
let auditwheel = build_options |
| 709 |
.auditwheel |
| 710 |
.or_else(|| pyproject.and_then(|x| x.auditwheel())) |
| 711 |
.unwrap_or(if skip_auditwheel { |
| 712 |
AuditWheelMode::Skip |
| 713 |
} else { |
| 714 |
AuditWheelMode::Repair |
| 715 |
}); |
| 716 |
|
| 717 |
// Check if PyPI validation is needed before we move platform_tag |
| 718 |
let pypi_validation = matches!(&build_options.platform_tag[..], [PlatformTag::Pypi]); |
| 719 |
|
| 720 |
let platform_tags = if build_options.platform_tag.is_empty() { |
| 721 |
#[cfg(feature = "zig")] |
| 722 |
let use_zig = build_options.zig; |
| 723 |
#[cfg(not(feature = "zig"))] |
| 724 |
let use_zig = false; |
| 725 |
let compatibility = pyproject |
| 726 |
.and_then(|x| { |
| 727 |
if x.compatibility().is_some() { |
| 728 |
pyproject_toml_maturin_options.push("compatibility"); |
| 729 |
} |
| 730 |
x.compatibility() |
| 731 |
}) |
| 732 |
.or(if use_zig { |
| 733 |
if target.is_musl_libc() { |
| 734 |
// Zig bundles musl 1.2 |
| 735 |
Some(PlatformTag::Musllinux { major: 1, minor: 2 }) |
| 736 |
} else { |
| 737 |
// With zig we can compile to any glibc version that we want, so we pick the lowest |
| 738 |
// one supported by the rust compiler |
| 739 |
Some(target.get_minimum_manylinux_tag()) |
| 740 |
} |
| 741 |
} else { |
| 742 |
// Defaults to musllinux_1_2 for musl target if it's not bin bindings |
| 743 |
if target.is_musl_libc() && !bridge.is_bin() { |
| 744 |
Some(PlatformTag::Musllinux { major: 1, minor: 2 }) |
| 745 |
} else { |
| 746 |
None |
| 747 |
} |
| 748 |
}); |
| 749 |
if let Some(platform_tag) = compatibility { |
| 750 |
vec![platform_tag] |
| 751 |
} else { |
| 752 |
Vec::new() |
| 753 |
} |
| 754 |
} else if let [PlatformTag::Pypi] = &build_options.platform_tag[..] { |
| 755 |
// Avoid building for architectures we already know aren't allowed on PyPI |
| 756 |
if !is_arch_supported_by_pypi(&target) { |
| 757 |
bail!("Target {} architecture is not supported by PyPI", target); |
| 758 |
} |
| 759 |
// The defaults are already targeting PyPI: manylinux on linux, |
| 760 |
// and the native tag on windows and mac |
| 761 |
Vec::new() |
| 762 |
} else if build_options.platform_tag.iter().all(|tag| !tag.is_pypi()) { |
| 763 |
// All non-PyPI tags - use as-is |
| 764 |
build_options.platform_tag |
| 765 |
} else { |
| 766 |
bail!("The 'pypi' compatibility option cannot be combined with other platform tags"); |
| 767 |
}; |
| 768 |
|
| 769 |
for platform_tag in &platform_tags { |
| 770 |
if !platform_tag.is_supported() { |
| 771 |
eprintln!("⚠️ Warning: {platform_tag} is unsupported by the Rust compiler."); |
| 772 |
} else if platform_tag.is_musllinux() && !target.is_musl_libc() { |
| 773 |
eprintln!("⚠️ Warning: {target} is not compatible with {platform_tag}."); |
| 774 |
} |
| 775 |
} |
| 776 |
|
| 777 |
validate_bridge_type(&bridge, &target, &platform_tags)?; |
| 778 |
|
| 779 |
// linux tag can not be mixed with manylinux and musllinux tags |
| 780 |
if platform_tags.len() > 1 && platform_tags.iter().any(|tag| !tag.is_portable()) { |
| 781 |
bail!("Cannot mix linux and manylinux/musllinux platform tags",); |
| 782 |
} |
| 783 |
|
| 784 |
if !pyproject_toml_maturin_options.is_empty() { |
| 785 |
eprintln!( |
| 786 |
"📡 Using build options {} from pyproject.toml", |
| 787 |
pyproject_toml_maturin_options.join(", ") |
| 788 |
); |
| 789 |
} |
| 790 |
|
| 791 |
let target_dir = build_options |
| 792 |
.cargo |
| 793 |
.target_dir |
| 794 |
.clone() |
| 795 |
.unwrap_or_else(|| cargo_metadata.target_directory.clone().into_std_path_buf()); |
| 796 |
|
| 797 |
let config_targets = pyproject.and_then(|x| x.targets()); |
| 798 |
let compile_targets = |
| 799 |
filter_cargo_targets(&cargo_metadata, bridge, config_targets.as_deref())?; |
| 800 |
if compile_targets.is_empty() { |
| 801 |
bail!("No Cargo targets to build, please check your bindings configuration in pyproject.toml."); |
| 802 |
} |
| 803 |
|
| 804 |
let crate_name = cargo_toml.package.name; |
| 805 |
Ok(BuildContext { |
| 806 |
target, |
| 807 |
compile_targets, |
| 808 |
project_layout, |
| 809 |
pyproject_toml_path, |
| 810 |
pyproject_toml, |
| 811 |
metadata24, |
| 812 |
crate_name, |
| 813 |
module_name, |
| 814 |
manifest_path: cargo_toml_path, |
| 815 |
target_dir, |
| 816 |
out: wheel_dir, |
| 817 |
release, |
| 818 |
strip, |
| 819 |
auditwheel, |
| 820 |
#[cfg(feature = "zig")] |
| 821 |
zig: build_options.zig, |
| 822 |
platform_tag: platform_tags, |
| 823 |
interpreter, |
| 824 |
cargo_metadata, |
| 825 |
universal2, |
| 826 |
editable, |
| 827 |
cargo_options, |
| 828 |
compression: build_options.compression, |
| 829 |
pypi_validation, |
| 830 |
}) |
| 831 |
} |
| 832 |
} |
| 833 |
|
| 834 |
fn resolve_interpreters( |
| 835 |
build_options: &BuildOptions, |
| 836 |
bridge: &BridgeModel, |
| 837 |
target: &Target, |
| 838 |
requires_python: Option<&VersionSpecifiers>, |
| 839 |
generate_import_lib: bool, |
| 840 |
) -> Result<Vec<PythonInterpreter>> { |
| 841 |
let interpreter = if build_options.find_interpreter { |
| 842 |
// Auto-detect interpreters |
| 843 |
build_options.find_interpreters( |
| 844 |
bridge, |
| 845 |
&[], |
| 846 |
target, |
| 847 |
requires_python, |
| 848 |
generate_import_lib, |
| 849 |
)? |
| 850 |
} else { |
| 851 |
// User given list of interpreters |
| 852 |
let interpreter = if build_options.interpreter.is_empty() && !target.cross_compiling() { |
| 853 |
if cfg!(test) { |
| 854 |
match env::var_os("MATURIN_TEST_PYTHON") { |
| 855 |
Some(python) => vec![python.into()], |
| 856 |
None => vec![target.get_python()], |
| 857 |
} |
| 858 |
} else { |
| 859 |
let python = if bridge.is_pyo3() { |
| 860 |
std::env::var("PYO3_PYTHON") |
| 861 |
.ok() |
| 862 |
.map(PathBuf::from) |
| 863 |
.unwrap_or_else(|| target.get_python()) |
| 864 |
} else { |
| 865 |
target.get_python() |
| 866 |
}; |
| 867 |
vec![python] |
| 868 |
} |
| 869 |
} else { |
| 870 |
// XXX: False positive clippy warning |
| 871 |
#[allow(clippy::redundant_clone)] |
| 872 |
build_options.interpreter.clone() |
| 873 |
}; |
| 874 |
build_options.find_interpreters(bridge, &interpreter, target, None, generate_import_lib)? |
| 875 |
}; |
| 876 |
Ok(interpreter) |
| 877 |
} |
| 878 |
|
| 879 |
/// Checks for bridge/platform type edge cases |
| 880 |
fn validate_bridge_type( |
| 881 |
bridge: &BridgeModel, |
| 882 |
target: &Target, |
| 883 |
platform_tags: &[PlatformTag], |
| 884 |
) -> Result<()> { |
| 885 |
match bridge { |
| 886 |
BridgeModel::Bin(None) => { |
| 887 |
// Only support two different kind of platform tags when compiling to musl target without any binding crates |
| 888 |
if platform_tags.iter().any(|tag| tag.is_musllinux()) && !target.is_musl_libc() { |
| 889 |
bail!( |
| 890 |
"Cannot mix musllinux and manylinux platform tags when compiling to {}", |
| 891 |
target.target_triple() |
| 892 |
); |
| 893 |
} |
| 894 |
|
| 895 |
#[allow(clippy::comparison_chain)] |
| 896 |
if platform_tags.len() > 2 { |
| 897 |
bail!( |
| 898 |
"Expected only one or two platform tags but found {}", |
| 899 |
platform_tags.len() |
| 900 |
); |
| 901 |
} else if platform_tags.len() == 2 { |
| 902 |
// The two platform tags can't be the same kind |
| 903 |
let tag_types = platform_tags |
| 904 |
.iter() |
| 905 |
.map(|tag| tag.is_musllinux()) |
| 906 |
.collect::<HashSet<_>>(); |
| 907 |
if tag_types.len() == 1 { |
| 908 |
bail!( |
| 909 |
"Expected only one platform tag but found {}", |
| 910 |
platform_tags.len() |
| 911 |
); |
| 912 |
} |
| 913 |
} |
| 914 |
} |
| 915 |
_ => { |
| 916 |
if platform_tags.len() > 1 { |
| 917 |
bail!( |
| 918 |
"Expected only one platform tag but found {}", |
| 919 |
platform_tags.len() |
| 920 |
); |
| 921 |
} |
| 922 |
} |
| 923 |
} |
| 924 |
Ok(()) |
| 925 |
} |
| 926 |
|
| 927 |
fn filter_cargo_targets( |
| 928 |
cargo_metadata: &Metadata, |
| 929 |
bridge: BridgeModel, |
| 930 |
config_targets: Option<&[crate::pyproject_toml::CargoTarget]>, |
| 931 |
) -> Result<Vec<CompileTarget>> { |
| 932 |
let root_pkg = cargo_metadata.root_package().unwrap(); |
| 933 |
let resolved_features = cargo_metadata |
| 934 |
.resolve |
| 935 |
.as_ref() |
| 936 |
.and_then(|resolve| resolve.nodes.iter().find(|node| node.id == root_pkg.id)) |
| 937 |
.map(|node| node.features.clone()) |
| 938 |
.unwrap_or_default(); |
| 939 |
let mut targets: Vec<_> = root_pkg |
| 940 |
.targets |
| 941 |
.iter() |
| 942 |
.filter(|target| match bridge { |
| 943 |
BridgeModel::Bin(_) => { |
| 944 |
let is_bin = target.is_bin(); |
| 945 |
if target.required_features.is_empty() { |
| 946 |
is_bin |
| 947 |
} else { |
| 948 |
// Check all required features are enabled for this bin target |
| 949 |
is_bin |
| 950 |
&& target |
| 951 |
.required_features |
| 952 |
.iter() |
| •953 |
.all(|f| resolved_features.iter().any(|rf| rf.as_str() == f.as_str())) |
| 954 |
} |
| 955 |
} |
| 956 |
_ => target.crate_types.contains(&CrateType::CDyLib), |
| 957 |
}) |
| 958 |
.map(|target| CompileTarget { |
| 959 |
target: target.clone(), |
| 960 |
bridge_model: bridge.clone(), |
| 961 |
}) |
| 962 |
.collect(); |
| 963 |
if targets.is_empty() && !bridge.is_bin() { |
| 964 |
// No `crate-type = ["cdylib"]` in `Cargo.toml` |
| 965 |
// Let's try compile one of the target with `--crate-type cdylib` |
| 966 |
let lib_target = root_pkg.targets.iter().find(|target| { |
| 967 |
target |
| 968 |
.crate_types |
| 969 |
.iter() |
| 970 |
.any(|crate_type| LIB_CRATE_TYPES.contains(crate_type)) |
| 971 |
}); |
| 972 |
if let Some(target) = lib_target { |
| 973 |
targets.push(CompileTarget { |
| 974 |
target: target.clone(), |
| 975 |
bridge_model: bridge, |
| 976 |
}); |
| 977 |
} |
| 978 |
} |
| 979 |
|
| 980 |
// Filter targets by config_targets |
| 981 |
if let Some(config_targets) = config_targets { |
| 982 |
targets.retain(|CompileTarget { target, .. }| { |
| 983 |
config_targets.iter().any(|config_target| { |
| 984 |
let name_eq = config_target.name == target.name; |
| 985 |
match &config_target.kind { |
| 986 |
Some(kind) => name_eq && target.crate_types.contains(&CrateType::from(*kind)), |
| 987 |
None => name_eq, |
| 988 |
} |
| 989 |
}) |
| 990 |
}); |
| 991 |
if targets.is_empty() { |
| 992 |
bail!( |
| 993 |
"No Cargo targets matched by `package.metadata.maturin.targets`, please check your `Cargo.toml`" |
| 994 |
); |
| 995 |
} else { |
| 996 |
let target_names = targets |
| 997 |
.iter() |
| 998 |
.map(|CompileTarget { target, .. }| target.name.as_str()) |
| 999 |
.collect::<Vec<_>>(); |
| 1000 |
eprintln!( |
| 1001 |
"🎯 Found {} Cargo targets in `Cargo.toml`: {}", |
| 1002 |
targets.len(), |
| 1003 |
target_names.join(", ") |
| 1004 |
); |
| 1005 |
} |
| 1006 |
} |
| 1007 |
|
| 1008 |
Ok(targets) |
| 1009 |
} |
| 1010 |
|
| 1011 |
/// pyo3 supports building abi3 wheels if the unstable-api feature is not selected |
| 1012 |
fn has_abi3(deps: &HashMap<&str, &Node>) -> Result<Option<Abi3Version>> { |
| 1013 |
for &lib in PYO3_BINDING_CRATES.iter() { |
| 1014 |
let lib = lib.as_str(); |
| 1015 |
if let Some(pyo3_crate) = deps.get(lib) { |
| 1016 |
// Find the minimal abi3 python version. If there is none, abi3 hasn't been selected |
| 1017 |
// This parser abi3-py{major}{minor} and returns the minimal (major, minor) tuple |
| •1018 |
let abi3_selected = pyo3_crate.features.iter().any(|x| x.as_str() == "abi3"); |
| 1019 |
|
| 1020 |
let min_abi3_version = pyo3_crate |
| 1021 |
.features |
| 1022 |
.iter() |
| 1023 |
.filter(|x| x.starts_with("abi3-py") && x.len() >= "abi3-pyxx".len()) |
| 1024 |
.map(|x| { |
| 1025 |
Ok(( |
| 1026 |
(x.as_bytes()[7] as char).to_string().parse::<u8>()?, |
| 1027 |
x[8..].parse::<u8>()?, |
| 1028 |
)) |
| 1029 |
}) |
| 1030 |
.collect::<Result<Vec<(u8, u8)>>>() |
| 1031 |
.context(format!("Bogus {lib} cargo features"))? |
| 1032 |
.into_iter() |
| 1033 |
.min(); |
| 1034 |
match min_abi3_version { |
| 1035 |
Some((major, minor)) => return Ok(Some(Abi3Version::Version(major, minor))), |
| 1036 |
None if abi3_selected => return Ok(Some(Abi3Version::CurrentPython)), |
| 1037 |
None => {} |
| 1038 |
} |
| 1039 |
} |
| 1040 |
} |
| 1041 |
Ok(None) |
| 1042 |
} |
| 1043 |
|
| 1044 |
/// pyo3 0.16.4+ supports building abi3 wheels without a working Python interpreter for Windows |
| 1045 |
/// when `generate-import-lib` feature is enabled |
| 1046 |
fn is_generating_import_lib(cargo_metadata: &Metadata) -> Result<bool> { |
| 1047 |
let resolve = cargo_metadata |
| 1048 |
.resolve |
| 1049 |
.as_ref() |
| 1050 |
.context("Expected cargo to return metadata with resolve")?; |
| 1051 |
for &lib in PYO3_BINDING_CRATES.iter().rev() { |
| 1052 |
let lib = lib.as_str(); |
| 1053 |
let pyo3_packages = resolve |
| 1054 |
.nodes |
| 1055 |
.iter() |
| 1056 |
.filter(|package| cargo_metadata[&package.id].name.as_str() == lib) |
| 1057 |
.collect::<Vec<_>>(); |
| 1058 |
match pyo3_packages.as_slice() { |
| 1059 |
[pyo3_crate] => { |
| 1060 |
let generate_import_lib = pyo3_crate |
| 1061 |
.features |
| 1062 |
.iter() |
| •1063 |
.any(|x| x.as_str() == "generate-import-lib" || x.as_str() == "generate-abi3-import-lib"); |
| 1064 |
return Ok(generate_import_lib); |
| 1065 |
} |
| 1066 |
_ => continue, |
| 1067 |
} |
| 1068 |
} |
| 1069 |
Ok(false) |
| 1070 |
} |
| 1071 |
|
| 1072 |
/// Tries to determine the bindings type from dependency |
| 1073 |
fn find_pyo3_bindings( |
| 1074 |
deps: &HashMap<&str, &Node>, |
| 1075 |
packages: &HashMap<&str, &cargo_metadata::Package>, |
| 1076 |
) -> anyhow::Result<Option<PyO3>> { |
| 1077 |
use crate::bridge::PyO3MetadataRaw; |
| 1078 |
|
| 1079 |
if deps.get("pyo3").is_some() { |
| 1080 |
let pyo3_metadata = match packages.get("pyo3-ffi") { |
| 1081 |
Some(pyo3_ffi) => pyo3_ffi.metadata.clone(), |
| 1082 |
None => { |
| 1083 |
// Old versions of pyo3 does not depend on pyo3-ffi, |
| 1084 |
// thus does not have the metadata |
| 1085 |
serde_json::Value::Null |
| 1086 |
} |
| 1087 |
}; |
| 1088 |
let metadata = match serde_json::from_value::<Option<PyO3MetadataRaw>>(pyo3_metadata) { |
| 1089 |
Ok(Some(metadata)) => Some(metadata.try_into()?), |
| 1090 |
Ok(None) | Err(_) => None, |
| 1091 |
}; |
| 1092 |
let version = packages["pyo3"].version.clone(); |
| 1093 |
Ok(Some(PyO3 { |
| 1094 |
crate_name: PyO3Crate::PyO3, |
| 1095 |
version, |
| 1096 |
abi3: None, |
| 1097 |
metadata, |
| 1098 |
})) |
| 1099 |
} else if deps.get("pyo3-ffi").is_some() { |
| 1100 |
let package = &packages["pyo3-ffi"]; |
| 1101 |
let version = package.version.clone(); |
| 1102 |
let metadata = |
| 1103 |
match serde_json::from_value::<Option<PyO3MetadataRaw>>(package.metadata.clone()) { |
| 1104 |
Ok(Some(metadata)) => Some(metadata.try_into()?), |
| 1105 |
Ok(None) | Err(_) => None, |
| 1106 |
}; |
| 1107 |
Ok(Some(PyO3 { |
| 1108 |
crate_name: PyO3Crate::PyO3Ffi, |
| 1109 |
version, |
| 1110 |
abi3: None, |
| 1111 |
metadata, |
| 1112 |
})) |
| 1113 |
} else { |
| 1114 |
Ok(None) |
| 1115 |
} |
| 1116 |
} |
| 1117 |
|
| 1118 |
/// Return a map with all (transitive) dependencies of the *current* crate. |
| 1119 |
/// This is different from `metadata.resolve`, which also includes packages |
| 1120 |
/// that are used in the same workspace, but on which the current crate does not depend. |
| 1121 |
fn current_crate_dependencies(cargo_metadata: &Metadata) -> Result<HashMap<&str, &Node>> { |
| 1122 |
let resolve = cargo_metadata |
| 1123 |
.resolve |
| 1124 |
.as_ref() |
| 1125 |
.context("Expected to get a dependency graph from cargo")?; |
| 1126 |
let root = resolve |
| 1127 |
.root |
| 1128 |
.as_ref() |
| 1129 |
.context("expected to get a root package")?; |
| 1130 |
let nodes: HashMap<&PackageId, &Node> = |
| 1131 |
resolve.nodes.iter().map(|node| (&node.id, node)).collect(); |
| 1132 |
|
| 1133 |
// Walk the dependency tree to get all (in)direct children. |
| 1134 |
let mut dep_ids = HashSet::with_capacity(nodes.len()); |
| 1135 |
let mut todo = Vec::from([root]); |
| 1136 |
while let Some(id) = todo.pop() { |
| 1137 |
for dep in nodes[id].deps.iter() { |
| 1138 |
if dep_ids.contains(&dep.pkg) { |
| 1139 |
continue; |
| 1140 |
} |
| 1141 |
dep_ids.insert(&dep.pkg); |
| 1142 |
todo.push(&dep.pkg); |
| 1143 |
} |
| 1144 |
} |
| 1145 |
|
| 1146 |
Ok(nodes |
| 1147 |
.into_iter() |
| 1148 |
.filter_map(|(id, node)| { |
| 1149 |
dep_ids |
| 1150 |
.contains(&id) |
| 1151 |
.then_some((cargo_metadata[id].name.as_ref(), node)) |
| 1152 |
}) |
| 1153 |
.collect()) |
| 1154 |
} |
| 1155 |
|
| 1156 |
/// Tries to determine the [BridgeModel] for the target crate |
| 1157 |
pub fn find_bridge(cargo_metadata: &Metadata, bridge: Option<&str>) -> Result<BridgeModel> { |
| 1158 |
let deps = current_crate_dependencies(cargo_metadata)?; |
| 1159 |
let packages: HashMap<&str, &cargo_metadata::Package> = cargo_metadata |
| 1160 |
.packages |
| 1161 |
.iter() |
| 1162 |
.filter_map(|pkg| { |
| 1163 |
let name = &pkg.name; |
| •1164 |
if name.as_str() == "pyo3" || name.as_str() == "pyo3-ffi" || name.as_str() == "cpython" || name.as_str() == "uniffi" { |
| 1165 |
Some((name.as_ref(), pkg)) |
| 1166 |
} else { |
| 1167 |
None |
| 1168 |
} |
| 1169 |
}) |
| 1170 |
.collect(); |
| 1171 |
let root_package = cargo_metadata |
| 1172 |
.root_package() |
| 1173 |
.context("Expected cargo to return metadata with root_package")?; |
| 1174 |
let targets: Vec<_> = root_package |
| 1175 |
.targets |
| 1176 |
.iter() |
| 1177 |
.filter(|target| { |
| 1178 |
target.kind.iter().any(|kind| { |
| 1179 |
!matches!( |
| 1180 |
kind, |
| 1181 |
TargetKind::Bench |
| 1182 |
| TargetKind::CustomBuild |
| 1183 |
| TargetKind::Example |
| 1184 |
| TargetKind::ProcMacro |
| 1185 |
| TargetKind::Test |
| 1186 |
) |
| 1187 |
}) |
| 1188 |
}) |
| 1189 |
.flat_map(|target| target.crate_types.iter().cloned()) |
| 1190 |
.collect(); |
| 1191 |
|
| 1192 |
let bridge = if let Some(bindings) = bridge { |
| 1193 |
if bindings == "cffi" { |
| 1194 |
BridgeModel::Cffi |
| 1195 |
} else if bindings == "uniffi" { |
| 1196 |
BridgeModel::UniFfi |
| 1197 |
} else if bindings == "bin" { |
| 1198 |
let bindings = find_pyo3_bindings(&deps, &packages)?; |
| 1199 |
BridgeModel::Bin(bindings) |
| 1200 |
} else { |
| 1201 |
let bindings = find_pyo3_bindings(&deps, &packages)?.context("unknown binding type")?; |
| 1202 |
BridgeModel::PyO3(bindings) |
| 1203 |
} |
| 1204 |
} else if let Some(bindings) = find_pyo3_bindings(&deps, &packages)? { |
| 1205 |
if !targets.contains(&CrateType::CDyLib) && targets.contains(&CrateType::Bin) { |
| 1206 |
BridgeModel::Bin(Some(bindings)) |
| 1207 |
} else { |
| 1208 |
BridgeModel::PyO3(bindings) |
| 1209 |
} |
| 1210 |
} else if deps.contains_key("uniffi") { |
| 1211 |
BridgeModel::UniFfi |
| 1212 |
} else if targets.contains(&CrateType::CDyLib) { |
| 1213 |
BridgeModel::Cffi |
| 1214 |
} else if targets.contains(&CrateType::Bin) { |
| 1215 |
BridgeModel::Bin(find_pyo3_bindings(&deps, &packages)?) |
| 1216 |
} else { |
| 1217 |
bail!("Couldn't detect the binding type; Please specify them with --bindings/-b") |
| 1218 |
}; |
| 1219 |
|
| 1220 |
if !bridge.is_pyo3() { |
| 1221 |
eprintln!("🔗 Found {bridge} bindings"); |
| 1222 |
return Ok(bridge); |
| 1223 |
} |
| 1224 |
|
| 1225 |
for &lib in PYO3_BINDING_CRATES.iter() { |
| 1226 |
if !bridge.is_bin() && bridge.is_pyo3_crate(lib) { |
| 1227 |
let lib_name = lib.as_str(); |
| 1228 |
let pyo3_node = deps[lib_name]; |
| •1229 |
if !pyo3_node.features.iter().any(|f| f.as_str() == "extension-module") { |
| 1230 |
let version = cargo_metadata[&pyo3_node.id].version.to_string(); |
| 1231 |
eprintln!( |
| 1232 |
"⚠️ Warning: You're building a library without activating {lib}'s \ |
| 1233 |
`extension-module` feature. \ |
| 1234 |
See https://pyo3.rs/v{version}/building-and-distribution.html#the-extension-module-feature" |
| 1235 |
); |
| 1236 |
} |
| 1237 |
|
| 1238 |
return if let Some(abi3_version) = has_abi3(&deps)? { |
| 1239 |
eprintln!("🔗 Found {lib} bindings with abi3 support"); |
| 1240 |
let pyo3 = bridge.pyo3().expect("should be pyo3 bindings"); |
| 1241 |
let bindings = PyO3 { |
| 1242 |
crate_name: lib, |
| 1243 |
version: pyo3.version.clone(), |
| 1244 |
abi3: Some(abi3_version), |
| 1245 |
metadata: pyo3.metadata.clone(), |
| 1246 |
}; |
| 1247 |
Ok(BridgeModel::PyO3(bindings)) |
| 1248 |
} else { |
| 1249 |
eprintln!("🔗 Found {lib} bindings"); |
| 1250 |
Ok(bridge) |
| 1251 |
}; |
| 1252 |
} |
| 1253 |
} |
| 1254 |
|
| 1255 |
Ok(bridge) |
| 1256 |
} |
| 1257 |
|
| 1258 |
/// Shared between cffi and pyo3-abi3 |
| 1259 |
fn find_single_python_interpreter( |
| 1260 |
bridge: &BridgeModel, |
| 1261 |
interpreter: &[PathBuf], |
| 1262 |
target: &Target, |
| 1263 |
bridge_name: &str, |
| 1264 |
) -> Result<PythonInterpreter> { |
| 1265 |
let err_message = "Failed to find a python interpreter"; |
| 1266 |
|
| 1267 |
let executable = if interpreter.is_empty() { |
| 1268 |
target.get_python() |
| 1269 |
} else if interpreter.len() == 1 { |
| 1270 |
interpreter[0].clone() |
| 1271 |
} else { |
| 1272 |
bail!( |
| 1273 |
"You can only specify one python interpreter for {}", |
| 1274 |
bridge_name |
| 1275 |
); |
| 1276 |
}; |
| 1277 |
|
| 1278 |
let interpreter = PythonInterpreter::check_executable(executable, target, bridge) |
| 1279 |
.context(format_err!(err_message))? |
| 1280 |
.ok_or_else(|| format_err!(err_message))?; |
| 1281 |
Ok(interpreter) |
| 1282 |
} |
| 1283 |
|
| 1284 |
/// Find python interpreters in host machine first, |
| 1285 |
/// fallback to bundled sysconfig if not found in host machine |
| 1286 |
fn find_interpreter( |
| 1287 |
bridge: &BridgeModel, |
| 1288 |
interpreter: &[PathBuf], |
| 1289 |
target: &Target, |
| 1290 |
requires_python: Option<&VersionSpecifiers>, |
| 1291 |
) -> Result<Vec<PythonInterpreter>> { |
| 1292 |
let mut found_interpreters = Vec::new(); |
| 1293 |
if !interpreter.is_empty() { |
| 1294 |
let mut missing = Vec::new(); |
| 1295 |
for interp in interpreter { |
| 1296 |
match PythonInterpreter::check_executable(interp.clone(), target, bridge)? { |
| 1297 |
Some(interp) => found_interpreters.push(interp), |
| 1298 |
None => missing.push(interp.clone()), |
| 1299 |
} |
| 1300 |
} |
| 1301 |
if !missing.is_empty() { |
| 1302 |
let sysconfig_interps = |
| 1303 |
find_interpreter_in_sysconfig(bridge, &missing, target, requires_python)?; |
| 1304 |
found_interpreters.extend(sysconfig_interps); |
| 1305 |
} |
| 1306 |
} else { |
| 1307 |
found_interpreters = PythonInterpreter::find_all(target, bridge, requires_python) |
| 1308 |
.context("Finding python interpreters failed")?; |
| 1309 |
}; |
| 1310 |
|
| 1311 |
if found_interpreters.is_empty() { |
| 1312 |
if interpreter.is_empty() { |
| 1313 |
if let Some(requires_python) = requires_python { |
| 1314 |
bail!("Couldn't find any python interpreters with version {}. Please specify at least one with -i", requires_python); |
| 1315 |
} else { |
| 1316 |
bail!("Couldn't find any python interpreters. Please specify at least one with -i"); |
| 1317 |
} |
| 1318 |
} else { |
| 1319 |
let interps_str = interpreter |
| 1320 |
.iter() |
| 1321 |
.map(|path| format!("'{}'", path.display())) |
| 1322 |
.collect::<Vec<_>>() |
| 1323 |
.join(", "); |
| 1324 |
bail!( |
| 1325 |
"Couldn't find any python interpreters from {}.", |
| 1326 |
interps_str |
| 1327 |
); |
| 1328 |
} |
| 1329 |
} |
| 1330 |
Ok(found_interpreters) |
| 1331 |
} |
| 1332 |
|
| 1333 |
/// Find python interpreters in the host machine |
| 1334 |
fn find_interpreter_in_host( |
| 1335 |
bridge: &BridgeModel, |
| 1336 |
interpreter: &[PathBuf], |
| 1337 |
target: &Target, |
| 1338 |
requires_python: Option<&VersionSpecifiers>, |
| 1339 |
) -> Result<Vec<PythonInterpreter>> { |
| 1340 |
let interpreters = if !interpreter.is_empty() { |
| 1341 |
PythonInterpreter::check_executables(interpreter, target, bridge)? |
| 1342 |
} else { |
| 1343 |
PythonInterpreter::find_all(target, bridge, requires_python) |
| 1344 |
.context("Finding python interpreters failed")? |
| 1345 |
}; |
| 1346 |
|
| 1347 |
if interpreters.is_empty() { |
| 1348 |
if let Some(requires_python) = requires_python { |
| 1349 |
bail!("Couldn't find any python interpreters with {}. Please specify at least one with -i", requires_python); |
| 1350 |
} else { |
| 1351 |
bail!("Couldn't find any python interpreters. Please specify at least one with -i"); |
| 1352 |
} |
| 1353 |
} |
| 1354 |
Ok(interpreters) |
| 1355 |
} |
| 1356 |
|
| 1357 |
/// Find python interpreters in the bundled sysconfig |
| 1358 |
fn find_interpreter_in_sysconfig( |
| 1359 |
bridge: &BridgeModel, |
| 1360 |
interpreter: &[PathBuf], |
| 1361 |
target: &Target, |
| 1362 |
requires_python: Option<&VersionSpecifiers>, |
| 1363 |
) -> Result<Vec<PythonInterpreter>> { |
| 1364 |
if interpreter.is_empty() { |
| 1365 |
return Ok(PythonInterpreter::find_by_target( |
| 1366 |
target, |
| 1367 |
requires_python, |
| 1368 |
Some(bridge), |
| 1369 |
)); |
| 1370 |
} |
| 1371 |
let mut interpreters = Vec::new(); |
| 1372 |
for interp in interpreter { |
| 1373 |
let python = interp.display().to_string(); |
| 1374 |
let (python_impl, python_ver, abiflags) = if let Some(ver) = python.strip_prefix("pypy") { |
| 1375 |
( |
| 1376 |
InterpreterKind::PyPy, |
| 1377 |
ver.strip_prefix('-').unwrap_or(ver), |
| 1378 |
"", |
| 1379 |
) |
| 1380 |
} else if let Some(ver) = python.strip_prefix("graalpy") { |
| 1381 |
( |
| 1382 |
InterpreterKind::GraalPy, |
| 1383 |
ver.strip_prefix('-').unwrap_or(ver), |
| 1384 |
"", |
| 1385 |
) |
| 1386 |
} else if let Some(ver) = python.strip_prefix("python") { |
| 1387 |
// Also accept things like `python3.13t` for free-threaded python |
| 1388 |
let (ver, abiflags) = maybe_free_threaded(ver.strip_prefix('-').unwrap_or(ver)); |
| 1389 |
(InterpreterKind::CPython, ver, abiflags) |
| 1390 |
} else if python |
| 1391 |
.chars() |
| 1392 |
.next() |
| 1393 |
.map(|c| c.is_ascii_digit()) |
| 1394 |
.unwrap_or(false) |
| 1395 |
{ |
| 1396 |
// Eg: -i 3.9 without interpreter kind, assume it's CPython |
| 1397 |
let (ver, abiflags) = maybe_free_threaded(&python); |
| 1398 |
(InterpreterKind::CPython, ver, abiflags) |
| 1399 |
} else { |
| 1400 |
// if interpreter not known |
| 1401 |
if std::path::Path::new(&python).is_file() { |
| 1402 |
bail!("Python interpreter should be a kind of interpreter (e.g. 'python3.8' or 'pypy3.9') when cross-compiling, got path to interpreter: {}", python); |
| 1403 |
} else { |
| 1404 |
bail!("Unsupported Python interpreter for cross-compilation: {}; supported interpreters are pypy, graalpy, and python (cpython)", python); |
| 1405 |
} |
| 1406 |
}; |
| 1407 |
if python_ver.is_empty() { |
| 1408 |
continue; |
| 1409 |
} |
| 1410 |
let (ver_major, ver_minor) = python_ver |
| 1411 |
.split_once('.') |
| 1412 |
.context("Invalid python interpreter version")?; |
| 1413 |
let ver_major = ver_major.parse::<usize>().with_context(|| { |
| 1414 |
format!("Invalid python interpreter major version '{ver_major}', expect a digit") |
| 1415 |
})?; |
| 1416 |
let ver_minor = ver_minor.parse::<usize>().with_context(|| { |
| 1417 |
format!("Invalid python interpreter minor version '{ver_minor}', expect a digit") |
| 1418 |
})?; |
| 1419 |
|
| 1420 |
if (ver_major, ver_minor) < (3, 13) && abiflags == "t" { |
| 1421 |
bail!("Free-threaded Python interpreter is only supported on 3.13 and later."); |
| 1422 |
} |
| 1423 |
|
| 1424 |
let sysconfig = InterpreterConfig::lookup_one(target, python_impl, (ver_major, ver_minor), abiflags) |
| 1425 |
.with_context(|| { |
| 1426 |
format!("Failed to find a {python_impl} {ver_major}.{ver_minor} interpreter in known sysconfig") |
| 1427 |
})?; |
| 1428 |
debug!( |
| 1429 |
"Found {} {}.{}{} in bundled sysconfig", |
| 1430 |
sysconfig.interpreter_kind, sysconfig.major, sysconfig.minor, sysconfig.abiflags |
| 1431 |
); |
| 1432 |
interpreters.push(PythonInterpreter::from_config(sysconfig.clone())); |
| 1433 |
} |
| 1434 |
Ok(interpreters) |
| 1435 |
} |
| 1436 |
|
| 1437 |
fn maybe_free_threaded(python_ver: &str) -> (&str, &str) { |
| 1438 |
if let Some(ver) = python_ver.strip_suffix('t') { |
| 1439 |
(ver, "t") |
| 1440 |
} else { |
| 1441 |
(python_ver, "") |
| 1442 |
} |
| 1443 |
} |
| 1444 |
|
| 1445 |
/// We need to pass the global flags to cargo metadata |
| 1446 |
/// (https://github.com/PyO3/maturin/issues/211 and https://github.com/PyO3/maturin/issues/472), |
| 1447 |
/// but we can't pass all the extra args, as e.g. `--target` isn't supported, so this tries to |
| 1448 |
/// extract the arguments for cargo metadata or convert them to suitable forms |
| 1449 |
/// instead. |
| 1450 |
/// |
| 1451 |
/// There are flags (without value) and options (with value). The options value be passed |
| 1452 |
/// in the same string as its name or in the next one. For this naive parsing logic, we |
| 1453 |
/// assume that the value is in the next argument if the argument string equals the name, |
| 1454 |
/// otherwise it's in the same argument and the next argument is unrelated. |
| 1455 |
pub(crate) fn extract_cargo_metadata_args(cargo_options: &CargoOptions) -> Result<Vec<String>> { |
| 1456 |
let mut cargo_metadata_extra_args = vec![]; |
| 1457 |
if cargo_options.frozen { |
| 1458 |
cargo_metadata_extra_args.push("--frozen".to_string()); |
| 1459 |
} |
| 1460 |
if cargo_options.locked { |
| 1461 |
cargo_metadata_extra_args.push("--locked".to_string()); |
| 1462 |
} |
| 1463 |
if cargo_options.offline { |
| 1464 |
cargo_metadata_extra_args.push("--offline".to_string()); |
| 1465 |
} |
| 1466 |
for feature in &cargo_options.features { |
| 1467 |
cargo_metadata_extra_args.push("--features".to_string()); |
| 1468 |
cargo_metadata_extra_args.push(feature.clone()); |
| 1469 |
} |
| 1470 |
if cargo_options.all_features { |
| 1471 |
cargo_metadata_extra_args.push("--all-features".to_string()); |
| 1472 |
} |
| 1473 |
if cargo_options.no_default_features { |
| 1474 |
cargo_metadata_extra_args.push("--no-default-features".to_string()); |
| 1475 |
} |
| 1476 |
// Target makes a difference during dependency resolving: cargo-fetch don't |
| 1477 |
// bother with unnecessary dependencies on the given triple, but without |
| 1478 |
// any target information supplied to cargo-metadata, it may consider them |
| 1479 |
// necessary, which could fail the build with --offline supplied at the |
| 1480 |
// same time. |
| 1481 |
// |
| 1482 |
// cargo-metadata does support --filter-platform to narrow the dependency |
| 1483 |
// graph since 1.40, thus let's convert --target to it to make sure |
| 1484 |
// cargo-metadata resolves the dependency as expected. |
| 1485 |
if let Some(target) = &cargo_options.target { |
| 1486 |
match target { |
| 1487 |
TargetTriple::Universal2 => { |
| 1488 |
cargo_metadata_extra_args.extend([ |
| 1489 |
"--filter-platform".to_string(), |
| 1490 |
"aarch64-apple-darwin".to_string(), |
| 1491 |
"--filter-platform".to_string(), |
| 1492 |
"x86_64-apple-darwin".to_string(), |
| 1493 |
]); |
| 1494 |
} |
| 1495 |
TargetTriple::Regular(target) => { |
| 1496 |
cargo_metadata_extra_args.push("--filter-platform".to_string()); |
| 1497 |
cargo_metadata_extra_args.push(target.clone()); |
| 1498 |
} |
| 1499 |
} |
| 1500 |
} |
| 1501 |
for opt in &cargo_options.unstable_flags { |
| 1502 |
cargo_metadata_extra_args.push("-Z".to_string()); |
| 1503 |
cargo_metadata_extra_args.push(opt.clone()); |
| 1504 |
} |
| 1505 |
Ok(cargo_metadata_extra_args) |
| 1506 |
} |
| 1507 |
|
| 1508 |
impl CargoOptions { |
| 1509 |
/// Convert the Cargo options into a Cargo invocation. |
| 1510 |
pub fn into_rustc_options(self, target_triple: Option<String>) -> cargo_options::Rustc { |
| 1511 |
cargo_options::Rustc { |
| 1512 |
common: cargo_options::CommonOptions { |
| 1513 |
quiet: self.quiet, |
| 1514 |
jobs: self.jobs, |
| 1515 |
profile: self.profile, |
| 1516 |
features: self.features, |
| 1517 |
all_features: self.all_features, |
| 1518 |
no_default_features: self.no_default_features, |
| 1519 |
target: if let Some(target) = target_triple { |
| 1520 |
vec![target] |
| 1521 |
} else { |
| 1522 |
Vec::new() |
| 1523 |
}, |
| 1524 |
target_dir: self.target_dir, |
| 1525 |
verbose: self.verbose, |
| 1526 |
color: self.color, |
| 1527 |
frozen: self.frozen, |
| 1528 |
locked: self.locked, |
| 1529 |
offline: self.offline, |
| 1530 |
config: self.config, |
| 1531 |
unstable_flags: self.unstable_flags, |
| 1532 |
timings: self.timings, |
| 1533 |
..Default::default() |
| 1534 |
}, |
| 1535 |
manifest_path: self.manifest_path, |
| 1536 |
ignore_rust_version: self.ignore_rust_version, |
| 1537 |
future_incompat_report: self.future_incompat_report, |
| 1538 |
args: self.args, |
| 1539 |
..Default::default() |
| 1540 |
} |
| 1541 |
} |
| 1542 |
} |
| 1543 |
|
| 1544 |
impl CargoOptions { |
| 1545 |
/// Merge options from pyproject.toml |
| 1546 |
pub fn merge_with_pyproject_toml(&mut self, tool_maturin: ToolMaturin) -> Vec<&'static str> { |
| 1547 |
let mut args_from_pyproject = Vec::new(); |
| 1548 |
|
| 1549 |
if self.manifest_path.is_none() && tool_maturin.manifest_path.is_some() { |
| 1550 |
self.manifest_path.clone_from(&tool_maturin.manifest_path); |
| 1551 |
args_from_pyproject.push("manifest-path"); |
| 1552 |
} |
| 1553 |
|
| 1554 |
if self.profile.is_none() && tool_maturin.profile.is_some() { |
| 1555 |
self.profile.clone_from(&tool_maturin.profile); |
| 1556 |
args_from_pyproject.push("profile"); |
| 1557 |
} |
| 1558 |
|
| 1559 |
if let Some(features) = tool_maturin.features { |
| 1560 |
if self.features.is_empty() { |
| 1561 |
self.features = features; |
| 1562 |
args_from_pyproject.push("features"); |
| 1563 |
} |
| 1564 |
} |
| 1565 |
|
| 1566 |
if let Some(all_features) = tool_maturin.all_features { |
| 1567 |
if !self.all_features { |
| 1568 |
self.all_features = all_features; |
| 1569 |
args_from_pyproject.push("all-features"); |
| 1570 |
} |
| 1571 |
} |
| 1572 |
|
| 1573 |
if let Some(no_default_features) = tool_maturin.no_default_features { |
| 1574 |
if !self.no_default_features { |
| 1575 |
self.no_default_features = no_default_features; |
| 1576 |
args_from_pyproject.push("no-default-features"); |
| 1577 |
} |
| 1578 |
} |
| 1579 |
|
| 1580 |
if let Some(frozen) = tool_maturin.frozen { |
| 1581 |
if !self.frozen { |
| 1582 |
self.frozen = frozen; |
| 1583 |
args_from_pyproject.push("frozen"); |
| 1584 |
} |
| 1585 |
} |
| 1586 |
|
| 1587 |
if let Some(locked) = tool_maturin.locked { |
| 1588 |
if !self.locked { |
| 1589 |
self.locked = locked; |
| 1590 |
args_from_pyproject.push("locked"); |
| 1591 |
} |
| 1592 |
} |
| 1593 |
|
| 1594 |
if let Some(config) = tool_maturin.config { |
| 1595 |
if self.config.is_empty() { |
| 1596 |
self.config = config; |
| 1597 |
args_from_pyproject.push("config"); |
| 1598 |
} |
| 1599 |
} |
| 1600 |
|
| 1601 |
if let Some(unstable_flags) = tool_maturin.unstable_flags { |
| 1602 |
if self.unstable_flags.is_empty() { |
| 1603 |
self.unstable_flags = unstable_flags; |
| 1604 |
args_from_pyproject.push("unstable-flags"); |
| 1605 |
} |
| 1606 |
} |
| 1607 |
|
| 1608 |
args_from_pyproject |
| 1609 |
} |
| 1610 |
} |
| 1611 |
|
| 1612 |
#[cfg(test)] |
| 1613 |
mod test { |
| 1614 |
use cargo_metadata::MetadataCommand; |
| 1615 |
use pretty_assertions::assert_eq; |
| 1616 |
use std::path::Path; |
| 1617 |
|
| 1618 |
use super::*; |
| 1619 |
|
| 1620 |
#[test] |
| 1621 |
fn test_find_bridge_pyo3() { |
| 1622 |
let pyo3_mixed = MetadataCommand::new() |
| 1623 |
.manifest_path(Path::new("test-crates/pyo3-mixed").join("Cargo.toml")) |
| 1624 |
.exec() |
| 1625 |
.unwrap(); |
| 1626 |
|
| 1627 |
assert!(matches!( |
| 1628 |
find_bridge(&pyo3_mixed, None), |
| 1629 |
Ok(BridgeModel::PyO3 { .. }) |
| 1630 |
)); |
| 1631 |
assert!(matches!( |
| 1632 |
find_bridge(&pyo3_mixed, Some("pyo3")), |
| 1633 |
Ok(BridgeModel::PyO3 { .. }) |
| 1634 |
)); |
| 1635 |
} |
| 1636 |
|
| 1637 |
#[test] |
| 1638 |
fn test_find_bridge_pyo3_abi3() { |
| 1639 |
use crate::bridge::{PyO3Metadata, PyO3VersionMetadata}; |
| 1640 |
|
| 1641 |
let pyo3_pure = MetadataCommand::new() |
| 1642 |
.manifest_path(Path::new("test-crates/pyo3-pure").join("Cargo.toml")) |
| 1643 |
.exec() |
| 1644 |
.unwrap(); |
| 1645 |
|
| 1646 |
let bridge = BridgeModel::PyO3(PyO3 { |
| 1647 |
crate_name: PyO3Crate::PyO3, |
| 1648 |
version: semver::Version::new(0, 25, 0), |
| 1649 |
abi3: Some(Abi3Version::Version(3, 7)), |
| 1650 |
metadata: Some(PyO3Metadata { |
| 1651 |
cpython: PyO3VersionMetadata { |
| 1652 |
min_minor: 7, |
| 1653 |
max_minor: 14, |
| 1654 |
}, |
| 1655 |
pypy: PyO3VersionMetadata { |
| 1656 |
min_minor: 9, |
| 1657 |
max_minor: 11, |
| 1658 |
}, |
| 1659 |
}), |
| 1660 |
}); |
| 1661 |
assert_eq!(find_bridge(&pyo3_pure, None).unwrap(), bridge); |
| 1662 |
assert_eq!(find_bridge(&pyo3_pure, Some("pyo3")).unwrap(), bridge); |
| 1663 |
} |
| 1664 |
|
| 1665 |
#[test] |
| 1666 |
fn test_find_bridge_pyo3_feature() { |
| 1667 |
let pyo3_pure = MetadataCommand::new() |
| 1668 |
.manifest_path(Path::new("test-crates/pyo3-feature").join("Cargo.toml")) |
| 1669 |
.exec() |
| 1670 |
.unwrap(); |
| 1671 |
|
| 1672 |
assert!(find_bridge(&pyo3_pure, None).is_err()); |
| 1673 |
|
| 1674 |
let pyo3_pure = MetadataCommand::new() |
| 1675 |
.manifest_path(Path::new("test-crates/pyo3-feature").join("Cargo.toml")) |
| 1676 |
.other_options(vec!["--features=pyo3".to_string()]) |
| 1677 |
.exec() |
| 1678 |
.unwrap(); |
| 1679 |
|
| 1680 |
assert!(matches!( |
| 1681 |
find_bridge(&pyo3_pure, None).unwrap(), |
| 1682 |
BridgeModel::PyO3 { .. } |
| 1683 |
)); |
| 1684 |
} |
| 1685 |
|
| 1686 |
#[test] |
| 1687 |
fn test_find_bridge_cffi() { |
| 1688 |
let cffi_pure = MetadataCommand::new() |
| 1689 |
.manifest_path(Path::new("test-crates/cffi-pure").join("Cargo.toml")) |
| 1690 |
.exec() |
| 1691 |
.unwrap(); |
| 1692 |
|
| 1693 |
assert_eq!( |
| 1694 |
find_bridge(&cffi_pure, Some("cffi")).unwrap(), |
| 1695 |
BridgeModel::Cffi |
| 1696 |
); |
| 1697 |
assert_eq!(find_bridge(&cffi_pure, None).unwrap(), BridgeModel::Cffi); |
| 1698 |
|
| 1699 |
assert!(find_bridge(&cffi_pure, Some("pyo3")).is_err()); |
| 1700 |
} |
| 1701 |
|
| 1702 |
#[test] |
| 1703 |
fn test_find_bridge_bin() { |
| 1704 |
let hello_world = MetadataCommand::new() |
| 1705 |
.manifest_path(Path::new("test-crates/hello-world").join("Cargo.toml")) |
| 1706 |
.exec() |
| 1707 |
.unwrap(); |
| 1708 |
|
| 1709 |
assert_eq!( |
| 1710 |
find_bridge(&hello_world, Some("bin")).unwrap(), |
| 1711 |
BridgeModel::Bin(None) |
| 1712 |
); |
| 1713 |
assert_eq!( |
| 1714 |
find_bridge(&hello_world, None).unwrap(), |
| 1715 |
BridgeModel::Bin(None) |
| 1716 |
); |
| 1717 |
|
| 1718 |
assert!(find_bridge(&hello_world, Some("pyo3")).is_err()); |
| 1719 |
|
| 1720 |
let pyo3_bin = MetadataCommand::new() |
| 1721 |
.manifest_path(Path::new("test-crates/pyo3-bin").join("Cargo.toml")) |
| 1722 |
.exec() |
| 1723 |
.unwrap(); |
| 1724 |
assert!(matches!( |
| 1725 |
find_bridge(&pyo3_bin, Some("bin")).unwrap(), |
| 1726 |
BridgeModel::Bin(Some(_)) |
| 1727 |
)); |
| 1728 |
assert!(matches!( |
| 1729 |
find_bridge(&pyo3_bin, None).unwrap(), |
| 1730 |
BridgeModel::Bin(Some(_)) |
| 1731 |
)); |
| 1732 |
} |
| 1733 |
|
| 1734 |
#[test] |
| 1735 |
fn test_old_extra_feature_args() { |
| 1736 |
let cargo_extra_args = CargoOptions { |
| 1737 |
no_default_features: true, |
| 1738 |
features: vec!["a".to_string(), "c".to_string()], |
| 1739 |
target: Some(TargetTriple::Regular( |
| 1740 |
"x86_64-unknown-linux-musl".to_string(), |
| 1741 |
)), |
| 1742 |
..Default::default() |
| 1743 |
}; |
| 1744 |
let cargo_metadata_extra_args = extract_cargo_metadata_args(&cargo_extra_args).unwrap(); |
| 1745 |
assert_eq!( |
| 1746 |
cargo_metadata_extra_args, |
| 1747 |
vec![ |
| 1748 |
"--features", |
| 1749 |
"a", |
| 1750 |
"--features", |
| 1751 |
"c", |
| 1752 |
"--no-default-features", |
| 1753 |
"--filter-platform", |
| 1754 |
"x86_64-unknown-linux-musl", |
| 1755 |
] |
| 1756 |
); |
| 1757 |
} |
| 1758 |
|
| 1759 |
#[test] |
| 1760 |
fn test_extract_cargo_metadata_args() { |
| 1761 |
let args = CargoOptions { |
| 1762 |
locked: true, |
| 1763 |
features: vec!["my-feature".to_string(), "other-feature".to_string()], |
| 1764 |
target: Some(TargetTriple::Regular( |
| 1765 |
"x86_64-unknown-linux-musl".to_string(), |
| 1766 |
)), |
| 1767 |
unstable_flags: vec!["unstable-options".to_string()], |
| 1768 |
..Default::default() |
| 1769 |
}; |
| 1770 |
|
| 1771 |
let expected = vec![ |
| 1772 |
"--locked", |
| 1773 |
"--features", |
| 1774 |
"my-feature", |
| 1775 |
"--features", |
| 1776 |
"other-feature", |
| 1777 |
"--filter-platform", |
| 1778 |
"x86_64-unknown-linux-musl", |
| 1779 |
"-Z", |
| 1780 |
"unstable-options", |
| 1781 |
]; |
| 1782 |
|
| 1783 |
assert_eq!(extract_cargo_metadata_args(&args).unwrap(), expected); |
| 1784 |
} |
| 1785 |
} |