-
-
Notifications
You must be signed in to change notification settings - Fork 304
/
Copy pathbuild_context.rs
1294 lines (1194 loc) · 48.1 KB
/
build_context.rs
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::auditwheel::{get_policy_and_libs, patchelf, relpath, AuditWheelMode};
use crate::auditwheel::{PlatformTag, Policy};
use crate::build_options::CargoOptions;
use crate::compile::{warn_missing_py_init, CompileTarget};
use crate::module_writer::{
add_data, write_bin, write_bindings_module, write_cffi_module, write_python_part,
write_uniffi_module, write_wasm_launcher, WheelWriter,
};
use crate::project_layout::ProjectLayout;
use crate::source_distribution::source_distribution;
use crate::target::{Arch, Os};
use crate::{
compile, pyproject_toml::Format, BridgeModel, BuildArtifact, Metadata24, ModuleWriter,
PyProjectToml, PythonInterpreter, Target,
};
use anyhow::{anyhow, bail, Context, Result};
use cargo_metadata::CrateType;
use cargo_metadata::Metadata;
use fs_err as fs;
use ignore::overrides::{Override, OverrideBuilder};
use indexmap::IndexMap;
use lddtree::Library;
use normpath::PathExt;
use pep508_rs::Requirement;
use platform_info::*;
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashSet};
use std::env;
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use tracing::instrument;
/// Insert wasm launcher scripts as entrypoints and the wasmtime dependency
fn bin_wasi_helper(
artifacts_and_files: &[(&BuildArtifact, String)],
mut metadata24: Metadata24,
) -> Result<Metadata24> {
eprintln!("⚠️ Warning: wasi support is experimental");
// escaped can contain [\w\d.], but i don't know how we'd handle dots correctly here
if metadata24.get_distribution_escaped().contains('.') {
bail!(
"Can't build wasm wheel if there is a dot in the name ('{}')",
metadata24.get_distribution_escaped()
)
}
if !metadata24.entry_points.is_empty() {
bail!("You can't define entrypoints yourself for a binary project");
}
let mut console_scripts = IndexMap::new();
for (_, bin_name) in artifacts_and_files {
let base_name = bin_name
.strip_suffix(".wasm")
.context("No .wasm suffix in wasi binary")?;
console_scripts.insert(
base_name.to_string(),
format!(
"{}.{}:main",
metadata24.get_distribution_escaped(),
base_name.replace('-', "_")
),
);
}
metadata24
.entry_points
.insert("console_scripts".to_string(), console_scripts);
// Add our wasmtime default version if the user didn't provide one
if !metadata24
.requires_dist
.iter()
.any(|requirement| requirement.name.as_ref() == "wasmtime")
{
// Having the wasmtime version hardcoded is not ideal, it's easy enough to overwrite
metadata24
.requires_dist
.push(Requirement::from_str("wasmtime>=11.0.0,<12.0.0").unwrap());
}
Ok(metadata24)
}
/// Contains all the metadata required to build the crate
#[derive(Clone)]
pub struct BuildContext {
/// The platform, i.e. os and pointer width
pub target: Target,
/// List of Cargo targets to compile
pub compile_targets: Vec<CompileTarget>,
/// Whether this project is pure rust or rust mixed with python
pub project_layout: ProjectLayout,
/// The path to pyproject.toml. Required for the source distribution
pub pyproject_toml_path: PathBuf,
/// Parsed pyproject.toml if any
pub pyproject_toml: Option<PyProjectToml>,
/// Python Package Metadata 2.3
pub metadata24: Metadata24,
/// The name of the crate
pub crate_name: String,
/// The name of the module can be distinct from the package name, mostly
/// because package names normally contain minuses while module names
/// have underscores. The package name is part of metadata24
pub module_name: String,
/// The path to the Cargo.toml. Required for the cargo invocations
pub manifest_path: PathBuf,
/// Directory for all generated artifacts
pub target_dir: PathBuf,
/// The directory to store the built wheels in. Defaults to a new "wheels"
/// directory in the project's target directory
pub out: PathBuf,
/// Build artifacts in release mode, with optimizations
pub release: bool,
/// Strip the library for minimum file size
pub strip: bool,
/// Checking the linked libraries for manylinux/musllinux compliance
pub auditwheel: AuditWheelMode,
/// When compiling for manylinux, use zig as linker to ensure glibc version compliance
#[cfg(feature = "zig")]
pub zig: bool,
/// Whether to use the the manylinux/musllinux or use the native linux tag (off)
pub platform_tag: Vec<PlatformTag>,
/// The available python interpreter
pub interpreter: Vec<PythonInterpreter>,
/// Cargo.toml as resolved by [cargo_metadata]
pub cargo_metadata: Metadata,
/// Whether to use universal2 or use the native macOS tag (off)
pub universal2: bool,
/// Build editable wheels
pub editable: bool,
/// Cargo build options
pub cargo_options: CargoOptions,
}
/// The wheel file location and its Python version tag (e.g. `py3`).
///
/// For bindings the version tag contains the Python interpreter version
/// they bind against (e.g. `cp37`).
pub type BuiltWheelMetadata = (PathBuf, String);
impl BuildContext {
/// Checks which kind of bindings we have (pyo3/rust-cypthon or cffi or bin) and calls the
/// correct builder.
#[instrument(skip_all)]
pub fn build_wheels(&self) -> Result<Vec<BuiltWheelMetadata>> {
use itertools::Itertools;
fs::create_dir_all(&self.out)
.context("Failed to create the target directory for the wheels")?;
let wheels = match self.bridge() {
BridgeModel::Bin(None) => self.build_bin_wheel(None)?,
BridgeModel::Bin(Some(..)) => self.build_bin_wheels(&self.interpreter)?,
BridgeModel::PyO3(crate::PyO3 { abi3, .. }) => match abi3 {
Some((major, minor)) => {
let abi3_interps: Vec<_> = self
.interpreter
.iter()
.filter(|interp| interp.has_stable_api())
.cloned()
.collect();
let non_abi3_interps: Vec<_> = self
.interpreter
.iter()
.filter(|interp| !interp.has_stable_api())
.cloned()
.collect();
let mut built_wheels = Vec::new();
if !abi3_interps.is_empty() {
built_wheels.extend(self.build_binding_wheel_abi3(
&abi3_interps,
*major,
*minor,
)?);
}
if !non_abi3_interps.is_empty() {
let interp_names: HashSet<_> = non_abi3_interps
.iter()
.map(|interp| interp.to_string())
.collect();
eprintln!(
"⚠️ Warning: {} does not yet support abi3 so the build artifacts will be version-specific.",
interp_names.iter().join(", ")
);
built_wheels.extend(self.build_binding_wheels(&non_abi3_interps)?);
}
built_wheels
}
None => self.build_binding_wheels(&self.interpreter)?,
},
BridgeModel::Cffi => self.build_cffi_wheel()?,
BridgeModel::UniFfi => self.build_uniffi_wheel()?,
};
Ok(wheels)
}
/// Bridge model
pub fn bridge(&self) -> &BridgeModel {
// FIXME: currently we only allow multiple bin targets so bridges are all the same
&self.compile_targets[0].bridge_model
}
/// Builds a source distribution and returns the same metadata as [BuildContext::build_wheels]
pub fn build_source_distribution(&self) -> Result<Option<BuiltWheelMetadata>> {
fs::create_dir_all(&self.out)
.context("Failed to create the target directory for the source distribution")?;
match self.pyproject_toml.as_ref() {
Some(pyproject) => {
let sdist_path =
source_distribution(self, pyproject, self.excludes(Format::Sdist)?)
.context("Failed to build source distribution")?;
Ok(Some((sdist_path, "source".to_string())))
}
None => Ok(None),
}
}
fn auditwheel(
&self,
artifact: &BuildArtifact,
platform_tag: &[PlatformTag],
python_interpreter: Option<&PythonInterpreter>,
) -> Result<(Policy, Vec<Library>)> {
if matches!(self.auditwheel, AuditWheelMode::Skip) {
return Ok((Policy::default(), Vec::new()));
}
if let Some(python_interpreter) = python_interpreter {
if platform_tag.is_empty()
&& self.target.is_linux()
&& !python_interpreter.support_portable_wheels()
{
eprintln!(
"🐍 Skipping auditwheel because {python_interpreter} does not support manylinux/musllinux wheels"
);
return Ok((Policy::default(), Vec::new()));
}
}
let mut musllinux: Vec<_> = platform_tag
.iter()
.filter(|tag| tag.is_musllinux())
.copied()
.collect();
musllinux.sort();
let mut others: Vec<_> = platform_tag
.iter()
.filter(|tag| !tag.is_musllinux())
.copied()
.collect();
others.sort();
// only bin bindings allow linking to libpython, extension modules must not
let allow_linking_libpython = self.bridge().is_bin();
if self.bridge().is_bin() && !musllinux.is_empty() {
return get_policy_and_libs(
artifact,
Some(musllinux[0]),
&self.target,
allow_linking_libpython,
);
}
let tag = others.first().or_else(|| musllinux.first()).copied();
get_policy_and_libs(artifact, tag, &self.target, allow_linking_libpython)
}
/// Add library search paths in Cargo target directory rpath when building in editable mode
fn add_rpath(&self, artifacts: &[&BuildArtifact]) -> Result<()> {
if self.editable && self.target.is_linux() && !artifacts.is_empty() {
for artifact in artifacts {
if artifact.linked_paths.is_empty() {
continue;
}
let old_rpaths = patchelf::get_rpath(&artifact.path)?;
let mut new_rpaths = old_rpaths.clone();
for path in &artifact.linked_paths {
if !old_rpaths.contains(path) {
new_rpaths.push(path.to_string());
}
}
let new_rpath = new_rpaths.join(":");
if let Err(err) = patchelf::set_rpath(&artifact.path, &new_rpath) {
eprintln!(
"⚠️ Warning: Failed to set rpath for {}: {}",
artifact.path.display(),
err
);
}
}
}
Ok(())
}
fn add_external_libs(
&self,
writer: &mut WheelWriter,
artifacts: &[&BuildArtifact],
ext_libs: &[Vec<Library>],
) -> Result<()> {
if self.editable {
return self.add_rpath(artifacts);
}
if ext_libs.iter().all(|libs| libs.is_empty()) {
return Ok(());
}
if matches!(self.auditwheel, AuditWheelMode::Check) {
eprintln!("🖨️ Your library is not manylinux/musllinux compliant because it requires copying the following libraries:");
for lib in ext_libs.iter().flatten() {
if let Some(path) = lib.realpath.as_ref() {
eprintln!(" {} => {}", lib.name, path.display())
} else {
eprintln!(" {} => not found", lib.name)
};
}
bail!("Can not repair the wheel because `--auditwheel=check` is specified, re-run with `--auditwheel=repair` to copy the libraries.");
}
patchelf::verify_patchelf()?;
// Put external libs to ${module_name}.libs directory
// See https://github.com/pypa/auditwheel/issues/89
let mut libs_dir = self
.project_layout
.python_module
.as_ref()
.and_then(|py| py.file_name().map(|s| s.to_os_string()))
.unwrap_or_else(|| self.module_name.clone().into());
libs_dir.push(".libs");
let libs_dir = PathBuf::from(libs_dir);
writer.add_directory(&libs_dir)?;
let temp_dir = tempfile::tempdir()?;
let mut soname_map = BTreeMap::new();
let mut libs_copied = HashSet::new();
for lib in ext_libs.iter().flatten() {
let lib_path = lib.realpath.clone().with_context(|| {
format!(
"Cannot repair wheel, because required library {} could not be located.",
lib.path.display()
)
})?;
// Generate a new soname with a short hash
let short_hash = &hash_file(&lib_path)?[..8];
let (file_stem, file_ext) = lib.name.split_once('.').unwrap();
let new_soname = if !file_stem.ends_with(&format!("-{short_hash}")) {
format!("{file_stem}-{short_hash}.{file_ext}")
} else {
format!("{file_stem}.{file_ext}")
};
// Copy the original lib to a tmpdir and modify some of its properties
// for example soname and rpath
let dest_path = temp_dir.path().join(&new_soname);
fs::copy(&lib_path, &dest_path)?;
libs_copied.insert(lib_path);
// fs::copy copies permissions as well, and the original
// file may have been read-only
let mut perms = fs::metadata(&dest_path)?.permissions();
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
fs::set_permissions(&dest_path, perms)?;
patchelf::set_soname(&dest_path, &new_soname)?;
if !lib.rpath.is_empty() || !lib.runpath.is_empty() {
patchelf::set_rpath(&dest_path, &libs_dir)?;
}
soname_map.insert(
lib.name.clone(),
(new_soname.clone(), dest_path.clone(), lib.needed.clone()),
);
}
for (artifact, artifact_ext_libs) in artifacts.iter().zip(ext_libs) {
let artifact_deps: HashSet<_> = artifact_ext_libs.iter().map(|lib| &lib.name).collect();
let replacements = soname_map
.iter()
.filter_map(|(k, v)| {
if artifact_deps.contains(k) {
Some((k, v.0.clone()))
} else {
None
}
})
.collect::<Vec<_>>();
if !replacements.is_empty() {
patchelf::replace_needed(&artifact.path, &replacements[..])?;
}
}
// we grafted in a bunch of libraries and modified their sonames, but
// they may have internal dependencies (DT_NEEDED) on one another, so
// we need to update those records so each now knows about the new
// name of the other.
for (new_soname, path, needed) in soname_map.values() {
let mut replacements = Vec::new();
for n in needed {
if soname_map.contains_key(n) {
replacements.push((n, soname_map[n].0.clone()));
}
}
if !replacements.is_empty() {
patchelf::replace_needed(path, &replacements[..])?;
}
writer.add_file_with_permissions(libs_dir.join(new_soname), path, 0o755)?;
}
eprintln!(
"🖨 Copied external shared libraries to package {} directory:",
libs_dir.display()
);
for lib_path in libs_copied {
eprintln!(" {}", lib_path.display());
}
let artifact_dir = match self.bridge() {
// cffi bindings that contains '.' in the module name will be split into directories
BridgeModel::Cffi => self.module_name.split(".").collect::<PathBuf>(),
// For namespace packages the modules the modules resides resides at ${module_name}.so
// where periods are replaced with slashes so for example my.namespace.module would reside
// at my/namespace/module.so
_ if self.module_name.contains(".") => {
let mut path = self.module_name.split(".").collect::<PathBuf>();
path.pop();
path
}
// For other bindings artifact .so file usually resides at ${module_name}/${module_name}.so
_ => PathBuf::from(&self.module_name),
};
for artifact in artifacts {
let mut new_rpaths = patchelf::get_rpath(&artifact.path)?;
// TODO: clean existing rpath entries if it's not pointed to a location within the wheel
// See https://github.com/pypa/auditwheel/blob/353c24250d66951d5ac7e60b97471a6da76c123f/src/auditwheel/repair.py#L160
let new_rpath = Path::new("$ORIGIN").join(relpath(&libs_dir, &artifact_dir));
new_rpaths.push(new_rpath.to_str().unwrap().to_string());
let new_rpath = new_rpaths.join(":");
patchelf::set_rpath(&artifact.path, &new_rpath)?;
}
Ok(())
}
fn add_pth(&self, writer: &mut WheelWriter) -> Result<()> {
if self.editable {
writer.add_pth(&self.project_layout, &self.metadata24)?;
}
Ok(())
}
fn excludes(&self, format: Format) -> Result<Override> {
let project_dir = match self.pyproject_toml_path.normalize() {
Ok(pyproject_toml_path) => pyproject_toml_path.into_path_buf(),
Err(_) => self.manifest_path.normalize()?.into_path_buf(),
};
let mut excludes = OverrideBuilder::new(project_dir.parent().unwrap());
if let Some(pyproject) = self.pyproject_toml.as_ref() {
if let Some(glob_patterns) = &pyproject.exclude() {
for glob in glob_patterns
.iter()
.filter_map(|glob_pattern| glob_pattern.targets(format))
{
excludes.add(glob)?;
}
}
}
// Ignore sdist output files so that we don't include them in the sdist
if matches!(format, Format::Sdist) {
let glob_pattern = format!(
"{}{}{}-*.tar.gz",
self.out.display(),
std::path::MAIN_SEPARATOR,
&self.metadata24.get_distribution_escaped(),
);
excludes.add(&glob_pattern)?;
}
Ok(excludes.build()?)
}
/// Returns the platform part of the tag for the wheel name
pub fn get_platform_tag(&self, platform_tags: &[PlatformTag]) -> Result<String> {
if let Ok(host_platform) = env::var("_PYTHON_HOST_PLATFORM") {
return Ok(host_platform.replace(['.', '-'], "_"));
}
let target = &self.target;
let tag = match (&target.target_os(), &target.target_arch()) {
// Windows
(Os::Windows, Arch::X86) => "win32".to_string(),
(Os::Windows, Arch::X86_64) => "win_amd64".to_string(),
(Os::Windows, Arch::Aarch64) => "win_arm64".to_string(),
// Linux
(Os::Linux, _) => {
let arch = target.get_platform_arch()?;
let mut platform_tags = platform_tags.to_vec();
platform_tags.sort();
let mut tags = vec![];
for platform_tag in platform_tags {
tags.push(format!("{platform_tag}_{arch}"));
for alias in platform_tag.aliases() {
tags.push(format!("{alias}_{arch}"));
}
}
tags.join(".")
}
// macOS
(Os::Macos, Arch::X86_64) | (Os::Macos, Arch::Aarch64) => {
let ((x86_64_major, x86_64_minor), (arm64_major, arm64_minor)) = macosx_deployment_target(env::var("MACOSX_DEPLOYMENT_TARGET").ok().as_deref(), self.universal2)?;
let x86_64_tag = if let Some(deployment_target) = self.pyproject_toml.as_ref().and_then(|x| x.target_config("x86_64-apple-darwin")).and_then(|config| config.macos_deployment_target.as_ref()) {
deployment_target.replace('.', "_")
} else {
format!("{x86_64_major}_{x86_64_minor}")
};
let arm64_tag = if let Some(deployment_target) = self.pyproject_toml.as_ref().and_then(|x| x.target_config("aarch64-apple-darwin")).and_then(|config| config.macos_deployment_target.as_ref()) {
deployment_target.replace('.', "_")
} else {
format!("{arm64_major}_{arm64_minor}")
};
if self.universal2 {
format!(
"macosx_{x86_64_tag}_x86_64.macosx_{arm64_tag}_arm64.macosx_{x86_64_tag}_universal2"
)
} else if target.target_arch() == Arch::Aarch64 {
format!("macosx_{arm64_tag}_arm64")
} else {
format!("macosx_{x86_64_tag}_x86_64")
}
}
// FreeBSD
(Os::FreeBsd, _)
// NetBSD
| (Os::NetBsd, _)
// OpenBSD
| (Os::OpenBsd, _) => {
let release = target.get_platform_release()?;
format!(
"{}_{}_{}",
target.target_os().to_string().to_ascii_lowercase(),
release,
target.target_arch().machine(),
)
}
// DragonFly
(Os::Dragonfly, Arch::X86_64)
// Haiku
| (Os::Haiku, Arch::X86_64) => {
let release = target.get_platform_release()?;
format!(
"{}_{}_{}",
target.target_os().to_string().to_ascii_lowercase(),
release.to_ascii_lowercase(),
"x86_64"
)
}
// Emscripten
(Os::Emscripten, Arch::Wasm32) => {
let release = emscripten_version()?.replace(['.', '-'], "_");
format!("emscripten_{release}_wasm32")
}
(Os::Wasi, Arch::Wasm32) => {
"any".to_string()
}
// osname_release_machine fallback for any POSIX system
(_, _) => {
let info = PlatformInfo::new()
.map_err(|e| anyhow!("Failed to fetch platform information: {e}"))?;
let mut release = info.release().to_string_lossy().replace(['.', '-'], "_");
let mut machine = info.machine().to_string_lossy().replace([' ', '/'], "_");
let mut os = target.target_os().to_string().to_ascii_lowercase();
// See https://github.com/python/cpython/blob/46c8d915715aa2bd4d697482aa051fe974d440e1/Lib/sysconfig.py#L722-L730
if target.target_os() == Os::Solaris || target.target_os() == Os::Illumos {
// Solaris / Illumos
if let Some((major, other)) = release.split_once('_') {
let major_ver: u64 = major.parse().context("illumos major version is not a number")?;
if major_ver >= 5 {
// SunOS 5 == Solaris 2
os = "solaris".to_string();
release = format!("{}_{}", major_ver - 3, other);
machine = format!("{machine}_64bit");
}
}
}
format!(
"{os}_{release}_{machine}"
)
}
};
Ok(tag)
}
/// Returns the tags for the WHEEL file for cffi wheels
pub fn get_py3_tags(&self, platform_tags: &[PlatformTag]) -> Result<Vec<String>> {
let tags = vec![format!(
"py3-none-{}",
self.get_platform_tag(platform_tags)?
)];
Ok(tags)
}
/// Returns the tags for the platform without python version
pub fn get_universal_tags(
&self,
platform_tags: &[PlatformTag],
) -> Result<(String, Vec<String>)> {
let tag = format!(
"py3-none-{platform}",
platform = self.get_platform_tag(platform_tags)?
);
let tags = self.get_py3_tags(platform_tags)?;
Ok((tag, tags))
}
fn write_binding_wheel_abi3(
&self,
artifact: BuildArtifact,
platform_tags: &[PlatformTag],
ext_libs: Vec<Library>,
major: u8,
min_minor: u8,
) -> Result<BuiltWheelMetadata> {
let platform = self.get_platform_tag(platform_tags)?;
let tag = format!("cp{major}{min_minor}-abi3-{platform}");
let mut writer = WheelWriter::new(
&tag,
&self.out,
&self.metadata24,
&[tag.clone()],
self.excludes(Format::Wheel)?,
)?;
self.add_external_libs(&mut writer, &[&artifact], &[ext_libs])?;
write_bindings_module(
&mut writer,
&self.project_layout,
&artifact.path,
self.interpreter.first(),
true,
&self.target,
self.editable,
self.pyproject_toml.as_ref(),
)
.context("Failed to add the files to the wheel")?;
self.add_pth(&mut writer)?;
add_data(
&mut writer,
&self.metadata24,
self.project_layout.data.as_deref(),
)?;
let wheel_path = writer.finish()?;
Ok((wheel_path, format!("cp{major}{min_minor}")))
}
/// For abi3 we only need to build a single wheel and we don't even need a python interpreter
/// for it
pub fn build_binding_wheel_abi3(
&self,
interpreters: &[PythonInterpreter],
major: u8,
min_minor: u8,
) -> Result<Vec<BuiltWheelMetadata>> {
let mut wheels = Vec::new();
// On windows, we have picked an interpreter to set the location of python.lib,
// otherwise it's none
let python_interpreter = interpreters.first();
let artifact = self.compile_cdylib(
python_interpreter,
Some(&self.project_layout.extension_name),
)?;
let (policy, external_libs) =
self.auditwheel(&artifact, &self.platform_tag, python_interpreter)?;
let platform_tags = if self.platform_tag.is_empty() {
vec![policy.platform_tag()]
} else {
self.platform_tag.clone()
};
let (wheel_path, tag) = self.write_binding_wheel_abi3(
artifact,
&platform_tags,
external_libs,
major,
min_minor,
)?;
eprintln!(
"📦 Built wheel for abi3 Python ≥ {}.{} to {}",
major,
min_minor,
wheel_path.display()
);
wheels.push((wheel_path, tag));
Ok(wheels)
}
fn write_binding_wheel(
&self,
python_interpreter: &PythonInterpreter,
artifact: BuildArtifact,
platform_tags: &[PlatformTag],
ext_libs: Vec<Library>,
) -> Result<BuiltWheelMetadata> {
let tag = python_interpreter.get_tag(self, platform_tags)?;
let mut writer = WheelWriter::new(
&tag,
&self.out,
&self.metadata24,
&[tag.clone()],
self.excludes(Format::Wheel)?,
)?;
self.add_external_libs(&mut writer, &[&artifact], &[ext_libs])?;
write_bindings_module(
&mut writer,
&self.project_layout,
&artifact.path,
Some(python_interpreter),
false,
&self.target,
self.editable,
self.pyproject_toml.as_ref(),
)
.context("Failed to add the files to the wheel")?;
self.add_pth(&mut writer)?;
add_data(
&mut writer,
&self.metadata24,
self.project_layout.data.as_deref(),
)?;
let wheel_path = writer.finish()?;
Ok((
wheel_path,
format!("cp{}{}", python_interpreter.major, python_interpreter.minor),
))
}
/// Builds wheels for a Cargo project for all given python versions.
/// Return type is the same as [BuildContext::build_wheels()]
///
/// Defaults to 3.{5, 6, 7, 8, 9} if no python versions are given
/// and silently ignores all non-existent python versions.
///
/// Runs [auditwheel_rs()] if not deactivated
pub fn build_binding_wheels(
&self,
interpreters: &[PythonInterpreter],
) -> Result<Vec<BuiltWheelMetadata>> {
let mut wheels = Vec::new();
for python_interpreter in interpreters {
let artifact = self.compile_cdylib(
Some(python_interpreter),
Some(&self.project_layout.extension_name),
)?;
let (policy, external_libs) =
self.auditwheel(&artifact, &self.platform_tag, Some(python_interpreter))?;
let platform_tags = if self.platform_tag.is_empty() {
vec![policy.platform_tag()]
} else {
self.platform_tag.clone()
};
let (wheel_path, tag) = self.write_binding_wheel(
python_interpreter,
artifact,
&platform_tags,
external_libs,
)?;
eprintln!(
"📦 Built wheel for {} {}.{}{} to {}",
python_interpreter.interpreter_kind,
python_interpreter.major,
python_interpreter.minor,
python_interpreter.abiflags,
wheel_path.display()
);
wheels.push((wheel_path, tag));
}
Ok(wheels)
}
/// Runs cargo build, extracts the cdylib from the output and returns the path to it
///
/// The module name is used to warn about missing a `PyInit_<module name>` function for
/// bindings modules.
pub fn compile_cdylib(
&self,
python_interpreter: Option<&PythonInterpreter>,
extension_name: Option<&str>,
) -> Result<BuildArtifact> {
let artifacts = compile(self, python_interpreter, &self.compile_targets)
.context("Failed to build a native library through cargo")?;
let error_msg = "Cargo didn't build a cdylib. Did you miss crate-type = [\"cdylib\"] \
in the lib section of your Cargo.toml?";
let artifacts = artifacts.first().context(error_msg)?;
let mut artifact = artifacts
.get(&CrateType::CDyLib)
.cloned()
.ok_or_else(|| anyhow!(error_msg,))?;
if let Some(extension_name) = extension_name {
// globin has an issue parsing MIPS64 ELF, see https://github.com/m4b/goblin/issues/274
// But don't fail the build just because we can't emit a warning
let _ = warn_missing_py_init(&artifact.path, extension_name);
}
if self.editable || matches!(self.auditwheel, AuditWheelMode::Skip) {
return Ok(artifact);
}
// auditwheel repair will edit the file, so we need to copy it to avoid errors in reruns
let artifact_path = &artifact.path;
let maturin_build = artifact_path.parent().unwrap().join("maturin");
fs::create_dir_all(&maturin_build)?;
let new_artifact_path = maturin_build.join(artifact_path.file_name().unwrap());
fs::copy(artifact_path, &new_artifact_path)?;
artifact.path = new_artifact_path;
Ok(artifact)
}
fn write_cffi_wheel(
&self,
artifact: BuildArtifact,
platform_tags: &[PlatformTag],
ext_libs: Vec<Library>,
) -> Result<BuiltWheelMetadata> {
let (tag, tags) = self.get_universal_tags(platform_tags)?;
let mut writer = WheelWriter::new(
&tag,
&self.out,
&self.metadata24,
&tags,
self.excludes(Format::Wheel)?,
)?;
self.add_external_libs(&mut writer, &[&artifact], &[ext_libs])?;
write_cffi_module(
&mut writer,
&self.target,
&self.project_layout,
self.manifest_path.parent().unwrap(),
&self.target_dir,
&self.module_name,
&artifact.path,
&self.interpreter[0].executable,
self.editable,
self.pyproject_toml.as_ref(),
)?;
self.add_pth(&mut writer)?;
add_data(
&mut writer,
&self.metadata24,
self.project_layout.data.as_deref(),
)?;
let wheel_path = writer.finish()?;
Ok((wheel_path, "py3".to_string()))
}
/// Builds a wheel with cffi bindings
pub fn build_cffi_wheel(&self) -> Result<Vec<BuiltWheelMetadata>> {
let mut wheels = Vec::new();
let artifact = self.compile_cdylib(None, None)?;
let (policy, external_libs) = self.auditwheel(&artifact, &self.platform_tag, None)?;
let platform_tags = if self.platform_tag.is_empty() {
vec![policy.platform_tag()]
} else {
self.platform_tag.clone()
};
let (wheel_path, tag) = self.write_cffi_wheel(artifact, &platform_tags, external_libs)?;
// Warn if cffi isn't specified in the requirements
if !self
.metadata24
.requires_dist
.iter()
.any(|requirement| requirement.name.as_ref() == "cffi")
{
eprintln!(
"⚠️ Warning: missing cffi package dependency, please add it to pyproject.toml. \
e.g: `dependencies = [\"cffi\"]`. This will become an error."
);
}
eprintln!("📦 Built wheel to {}", wheel_path.display());
wheels.push((wheel_path, tag));
Ok(wheels)
}
fn write_uniffi_wheel(
&self,
artifact: BuildArtifact,
platform_tags: &[PlatformTag],
ext_libs: Vec<Library>,
) -> Result<BuiltWheelMetadata> {
let (tag, tags) = self.get_universal_tags(platform_tags)?;
let mut writer = WheelWriter::new(
&tag,
&self.out,
&self.metadata24,
&tags,
self.excludes(Format::Wheel)?,
)?;
self.add_external_libs(&mut writer, &[&artifact], &[ext_libs])?;
write_uniffi_module(
&mut writer,
&self.project_layout,
self.manifest_path.parent().unwrap(),
&self.target_dir,
&self.module_name,
&artifact.path,
self.target.target_os(),
self.editable,
self.pyproject_toml.as_ref(),
)?;
self.add_pth(&mut writer)?;
add_data(
&mut writer,
&self.metadata24,
self.project_layout.data.as_deref(),
)?;
let wheel_path = writer.finish()?;
Ok((wheel_path, "py3".to_string()))
}
/// Builds a wheel with uniffi bindings
pub fn build_uniffi_wheel(&self) -> Result<Vec<BuiltWheelMetadata>> {
let mut wheels = Vec::new();
let artifact = self.compile_cdylib(None, None)?;
let (policy, external_libs) = self.auditwheel(&artifact, &self.platform_tag, None)?;
let platform_tags = if self.platform_tag.is_empty() {
vec![policy.platform_tag()]
} else {
self.platform_tag.clone()
};
let (wheel_path, tag) = self.write_uniffi_wheel(artifact, &platform_tags, external_libs)?;
eprintln!("📦 Built wheel to {}", wheel_path.display());
wheels.push((wheel_path, tag));
Ok(wheels)
}
fn write_bin_wheel(
&self,
python_interpreter: Option<&PythonInterpreter>,
artifacts: &[BuildArtifact],
platform_tags: &[PlatformTag],
ext_libs: &[Vec<Library>],
) -> Result<BuiltWheelMetadata> {
let (tag, tags) = match (self.bridge(), python_interpreter) {
(BridgeModel::Bin(None), _) => self.get_universal_tags(platform_tags)?,
(BridgeModel::Bin(Some(..)), Some(python_interpreter)) => {
let tag = python_interpreter.get_tag(self, platform_tags)?;
(tag.clone(), vec![tag])
}
_ => unreachable!(),
};
if !self.metadata24.scripts.is_empty() {
bail!("Defining scripts and working with a binary doesn't mix well");
}
let mut artifacts_and_files = Vec::new();
for artifact in artifacts {
// I wouldn't know of any case where this would be the wrong (and neither do
// I know a better alternative)
let bin_name = artifact
.path
.file_name()
.context("Couldn't get the filename from the binary produced by cargo")?
.to_str()
.context("binary produced by cargo has non-utf8 filename")?
.to_string();
// From https://packaging.python.org/en/latest/specifications/entry-points/
// > The name may contain any characters except =, but it cannot start or end with any
// > whitespace character, or start with [. For new entry points, it is recommended to
// > use only letters, numbers, underscores, dots and dashes (regex [\w.-]+).
// All of these rules are already enforced by cargo:
// https://github.com/rust-lang/cargo/blob/58a961314437258065e23cb6316dfc121d96fb71/src/cargo/util/restricted_names.rs#L39-L84
// i.e. we don't need to do any bin name validation here anymore
artifacts_and_files.push((artifact, bin_name))
}
let metadata24 = if self.target.is_wasi() {
bin_wasi_helper(&artifacts_and_files, self.metadata24.clone())?