Debian Codegraph @

src/module_writer.rs

raw
1 //! The wheel format is (mostly) specified in PEP 427
2 use crate::compression::{CompressionMethod, CompressionOptions};
3 use crate::project_layout::ProjectLayout;
4 use crate::target::Os;
5 use crate::{
6 pyproject_toml::Format, BridgeModel, Metadata24, PyProjectToml, PythonInterpreter, Target,
7 };
8 use anyhow::{anyhow, bail, Context, Result};
9 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
10 use base64::Engine;
11 use flate2::write::GzEncoder;
12 use flate2::Compression;
13 use fs_err as fs;
14 #[cfg(unix)]
15 use fs_err::os::unix::fs::OpenOptionsExt;
16 use fs_err::File;
17 #[cfg(unix)]
18 use fs_err::OpenOptions;
19 use ignore::overrides::Override;
20 use ignore::WalkBuilder;
21 use indexmap::IndexMap;
22 use itertools::Itertools;
23 use normpath::PathExt as _;
24 use same_file::is_same_file;
25 use sha2::{Digest, Sha256};
26 use std::collections::HashMap;
27 use std::env;
28 use std::ffi::OsStr;
29 use std::fmt::Write as _;
30 use std::io;
31 use std::io::{Read, Write};
32 #[cfg(unix)]
33 use std::os::unix::fs::PermissionsExt;
34 use std::path::{Path, PathBuf};
35 use std::process::{Command, Output};
36 use std::str;
37 use tempfile::{tempdir, TempDir};
38 use tracing::{debug, instrument};
39 use zip::{self, DateTime, ZipWriter};
40
41 /// Allows writing the module to a wheel or add it directly to the virtualenv
42 pub trait ModuleWriter {
43 /// Adds a directory relative to the module base path
44 fn add_directory(&mut self, path: impl AsRef<Path>) -> Result<()>;
45
46 /// Adds a file with bytes as content in target relative to the module base path.
47 ///
48 /// For generated files, `source` is `None`.
49 fn add_bytes(
50 &mut self,
51 target: impl AsRef<Path>,
52 source: Option<&Path>,
53 bytes: &[u8],
54 ) -> Result<()> {
55 debug!("Adding {}", target.as_ref().display());
56 // 0o644 is the default from the zip crate
57 self.add_bytes_with_permissions(target, source, bytes, 0o644)
58 }
59
60 /// Adds a file with bytes as content in target relative to the module base path while setting
61 /// the given unix permissions
62 ///
63 /// For generated files, `source` is `None`.
64 fn add_bytes_with_permissions(
65 &mut self,
66 target: impl AsRef<Path>,
67 source: Option<&Path>,
68 bytes: &[u8],
69 permissions: u32,
70 ) -> Result<()>;
71
72 /// Copies the source file to the target path relative to the module base path
73 fn add_file(&mut self, target: impl AsRef<Path>, source: impl AsRef<Path>) -> Result<()> {
74 self.add_file_with_permissions(target, source, 0o644)
75 }
76
77 /// Copies the source file the target path relative to the module base path while setting
78 /// the given unix permissions
79 fn add_file_with_permissions(
80 &mut self,
81 target: impl AsRef<Path>,
82 source: impl AsRef<Path>,
83 permissions: u32,
84 ) -> Result<()> {
85 let target = target.as_ref();
86 let source = source.as_ref();
87 debug!("Adding {} from {}", target.display(), source.display());
88
89 let read_failed_context = format!("Failed to read {}", source.display());
90 let mut file = File::open(source).context(read_failed_context.clone())?;
91 let mut buffer = Vec::new();
92 file.read_to_end(&mut buffer).context(read_failed_context)?;
93 self.add_bytes_with_permissions(target, Some(source), &buffer, permissions)
94 .context(format!("Failed to write to {}", target.display()))?;
95 Ok(())
96 }
97 }
98
99 /// A [ModuleWriter] that adds the module somewhere in the filesystem, e.g. in a virtualenv
100 pub struct PathWriter {
101 base_path: PathBuf,
102 record: Vec<(String, String, usize)>,
103 file_tracker: FileTracker,
104 }
105
106 impl PathWriter {
107 /// Creates a [ModuleWriter] that adds the module to the current virtualenv
108 pub fn venv(target: &Target, venv_dir: &Path, bridge: &BridgeModel) -> Result<Self> {
109 let interpreter =
110 PythonInterpreter::check_executable(target.get_venv_python(venv_dir), target, bridge)?
111 .ok_or_else(|| {
112 anyhow!("Expected `python` to be a python interpreter inside a virtualenv ಠ_ಠ")
113 })?;
114
115 let base_path = interpreter.get_venv_site_package(venv_dir, target);
116
117 Ok(PathWriter {
118 base_path,
119 record: Vec::new(),
120 file_tracker: FileTracker::default(),
121 })
122 }
123
124 /// Writes the module to the given path
125 pub fn from_path(path: impl AsRef<Path>) -> Self {
126 Self {
127 base_path: path.as_ref().to_path_buf(),
128 record: Vec::new(),
129 file_tracker: FileTracker::default(),
130 }
131 }
132
133 /// Removes a directory relative to the base path if it exists.
134 ///
135 /// This is to clean up the contents of an older develop call
136 pub fn delete_dir(&self, relative: impl AsRef<Path>) -> Result<()> {
137 let absolute = self.base_path.join(relative);
138 if absolute.exists() {
139 fs::remove_dir_all(&absolute)
140 .context(format!("Failed to remove {}", absolute.display()))?;
141 }
142
143 Ok(())
144 }
145
146 /// Writes the RECORD file after everything else has been written
147 pub fn write_record(self, metadata24: &Metadata24) -> Result<()> {
148 let record_file = self
149 .base_path
150 .join(metadata24.get_dist_info_dir())
151 .join("RECORD");
152 let mut buffer = File::create(&record_file).context(format!(
153 "Failed to create a file at {}",
154 record_file.display()
155 ))?;
156
157 // Sort records for deterministic output
158 let mut sorted_records = self.record.clone();
159 sorted_records.sort_by(|(path_a, _, _), (path_b, _, _)| path_a.cmp(path_b));
160
161 for (filename, hash, len) in sorted_records {
162 buffer
163 .write_all(format!("{filename},sha256={hash},{len}\n").as_bytes())
164 .context(format!(
165 "Failed to write to file at {}",
166 record_file.display()
167 ))?;
168 }
169 // Write the record for the RECORD file itself
170 buffer
171 .write_all(format!("{},,\n", record_file.display()).as_bytes())
172 .context(format!(
173 "Failed to write to file at {}",
174 record_file.display()
175 ))?;
176
177 Ok(())
178 }
179 }
180
181 impl ModuleWriter for PathWriter {
182 fn add_directory(&mut self, path: impl AsRef<Path>) -> Result<()> {
183 let target = self.base_path.join(path);
184 debug!("Adding directory {}", target.display());
185 fs::create_dir_all(target)?;
186 Ok(())
187 }
188
189 fn add_bytes_with_permissions(
190 &mut self,
191 target: impl AsRef<Path>,
192 source: Option<&Path>,
193 bytes: &[u8],
194 #[cfg_attr(target_os = "windows", allow(unused_variables))] permissions: u32,
195 ) -> Result<()> {
196 let path = self.base_path.join(&target);
197
198 if !self.file_tracker.add_file(target.as_ref(), source)? {
199 // Ignore duplicate files.
200 return Ok(());
201 }
202
203 // We only need to set the executable bit on unix
204 let mut file = {
205 #[cfg(target_family = "unix")]
206 {
207 OpenOptions::new()
208 .create(true)
209 .write(true)
210 .truncate(true)
211 .mode(permissions)
212 .open(&path)
213 }
214 #[cfg(target_os = "windows")]
215 {
216 File::create(&path)
217 }
218 }
219 .context(format!("Failed to create a file at {}", path.display()))?;
220
221 file.write_all(bytes)
222 .context(format!("Failed to write to file at {}", path.display()))?;
223
224 let hash = URL_SAFE_NO_PAD.encode(Sha256::digest(bytes));
225 self.record.push((
226 target.as_ref().to_str().unwrap().to_owned(),
227 hash,
228 bytes.len(),
229 ));
230
231 Ok(())
232 }
233 }
234
235 /// A glorified zip builder, mostly useful for writing the record file of a wheel
236 pub struct WheelWriter {
237 zip: ZipWriter<File>,
238 record: Vec<(String, String, usize)>,
239 record_file: PathBuf,
240 wheel_path: PathBuf,
241 file_tracker: FileTracker,
242 excludes: Override,
243 compression: CompressionOptions,
244 }
245 impl CompressionOptions {
246 fn get_file_options(&self) -> zip::write::FileOptions<'_, ()> {
247 let method = if cfg!(feature = "faster-tests") {
248 // Unlike users which can use the develop subcommand, the tests have to go through
249 // packing a zip which pip than has to unpack. This makes this 2-3 times faster
250 CompressionMethod::Stored
251 } else {
252 self.compression_method
253 };
254
255 let mut options =
256 zip::write::SimpleFileOptions::default().compression_method(method.into());
257 // `zip` also has default compression levels, which should match our own, but we pass them
258 // explicitly to ensure consistency. The exception is the `Stored` method, which must have
259 // a `compression_level` of `None`.
260 options = options.compression_level(if method == CompressionMethod::Stored {
261 None
262 } else {
263 Some(self.compression_level.unwrap_or(method.default_level()))
264 });
265 options
266 }
267 }
268
269 impl ModuleWriter for WheelWriter {
270 fn add_directory(&mut self, _path: impl AsRef<Path>) -> Result<()> {
271 Ok(()) // We don't need to create directories in zip archives
272 }
273
274 fn add_bytes_with_permissions(
275 &mut self,
276 target: impl AsRef<Path>,
277 source: Option<&Path>,
278 bytes: &[u8],
279 permissions: u32,
280 ) -> Result<()> {
281 let target = target.as_ref();
282 if self.exclude(target) {
283 return Ok(());
284 }
285
286 if !self.file_tracker.add_file(target, source)? {
287 // Ignore duplicate files.
288 return Ok(());
289 }
290
291 // The zip standard mandates using unix style paths
292 let target = target.to_str().unwrap().replace('\\', "/");
293
294 let mut options = self
295 .compression
296 .get_file_options()
297 .unix_permissions(permissions);
298
299 let mtime = self.mtime().ok();
300 if let Some(mtime) = mtime {
301 options = options.last_modified_time(mtime);
302 }
303
304 self.zip.start_file(target.clone(), options)?;
305 self.zip.write_all(bytes)?;
306
307 let hash = URL_SAFE_NO_PAD.encode(Sha256::digest(bytes));
308 self.record.push((target, hash, bytes.len()));
309
310 Ok(())
311 }
312 }
313
314 impl WheelWriter {
315 /// Create a new wheel file which can be subsequently expanded
316 ///
317 /// Adds the .dist-info directory and the METADATA file in it
318 pub fn new(
319 tag: &str,
320 wheel_dir: &Path,
321 pyproject_dir: &Path,
322 metadata24: &Metadata24,
323 tags: &[String],
324 excludes: Override,
325 compression: CompressionOptions,
326 ) -> Result<WheelWriter> {
327 let wheel_path = wheel_dir.join(format!(
328 "{}-{}-{}.whl",
329 metadata24.get_distribution_escaped(),
330 metadata24.get_version_escaped(),
331 tag
332 ));
333
334 let file = File::create(&wheel_path)?;
335
336 let mut builder = WheelWriter {
337 zip: ZipWriter::new(file),
338 record: Vec::new(),
339 record_file: metadata24.get_dist_info_dir().join("RECORD"),
340 wheel_path,
341 file_tracker: FileTracker::default(),
342 excludes,
343 compression,
344 };
345
346 write_dist_info(&mut builder, pyproject_dir, metadata24, tags)?;
347
348 Ok(builder)
349 }
350
351 /// Add a pth file to wheel root for editable installs
352 pub fn add_pth(
353 &mut self,
354 project_layout: &ProjectLayout,
355 metadata24: &Metadata24,
356 ) -> Result<()> {
357 if project_layout.python_module.is_some() || !project_layout.python_packages.is_empty() {
358 let absolute_path = project_layout
359 .python_dir
360 .normalize()
361 .with_context(|| {
362 format!(
363 "python dir path `{}` does not exist or is invalid",
364 project_layout.python_dir.display()
365 )
366 })?
367 .into_path_buf();
368 if let Some(python_path) = absolute_path.to_str() {
369 let name = metadata24.get_distribution_escaped();
370 let target = format!("{name}.pth");
371 debug!("Adding {} from {}", target, python_path);
372 self.add_bytes(target, None, python_path.as_bytes())?;
373 } else {
374 eprintln!("⚠️ source code path contains non-Unicode sequences, editable installs may not work.");
375 }
376 }
377 Ok(())
378 }
379
380 /// Returns `true` if the given path should be excluded
381 fn exclude(&self, path: impl AsRef<Path>) -> bool {
382 self.excludes.matched(path.as_ref(), false).is_whitelist()
383 }
384
385 /// Returns a DateTime representing the value SOURCE_DATE_EPOCH environment variable
386 /// Note that the earliest timestamp a zip file can represent is 1980-01-01
387 fn mtime(&self) -> Result<DateTime> {
388 let epoch: i64 = env::var("SOURCE_DATE_EPOCH")?.parse()?;
389 let dt = time::OffsetDateTime::from_unix_timestamp(epoch)?;
390 let min_dt = time::Date::from_calendar_date(1980, time::Month::January, 1)
391 .unwrap()
392 .midnight()
393 .assume_offset(time::UtcOffset::UTC);
394 let dt = dt.max(min_dt);
395
396 let dt = DateTime::try_from(dt).map_err(|_| anyhow!("Failed to build zip DateTime"))?;
397 Ok(dt)
398 }
399
400 /// Creates the record file and finishes the zip
401 pub fn finish(mut self) -> Result<PathBuf, io::Error> {
402 let mut options = self.compression.get_file_options();
403 let mtime = self.mtime().ok();
404 if let Some(mtime) = mtime {
405 options = options.last_modified_time(mtime);
406 }
407
408 let record_filename = self.record_file.to_str().unwrap().replace('\\', "/");
409 debug!("Adding {}", record_filename);
410 self.zip.start_file(&record_filename, options)?;
411
412 // Sort records for deterministic output
413 let mut sorted_records = self.record.clone();
414 sorted_records.sort_by(|(path_a, _, _), (path_b, _, _)| path_a.cmp(path_b));
415
416 for (filename, hash, len) in sorted_records {
417 self.zip
418 .write_all(format!("{filename},sha256={hash},{len}\n").as_bytes())?;
419 }
420 // Write the record for the RECORD file itself
421 self.zip
422 .write_all(format!("{record_filename},,\n").as_bytes())?;
423
424 self.zip.finish()?;
425 Ok(self.wheel_path)
426 }
427 }
428
429 /// Creates a .tar.gz archive containing the source distribution
430 pub struct SDistWriter {
431 tar: tar::Builder<GzEncoder<Vec<u8>>>,
432 path: PathBuf,
433 file_tracker: FileTracker,
434 excludes: Override,
435 }
436
437 impl ModuleWriter for SDistWriter {
438 fn add_directory(&mut self, _path: impl AsRef<Path>) -> Result<()> {
439 Ok(())
440 }
441
442 fn add_bytes_with_permissions(
443 &mut self,
444 target: impl AsRef<Path>,
445 source: Option<&Path>,
446 bytes: &[u8],
447 permissions: u32,
448 ) -> Result<()> {
449 let target = target.as_ref();
450 if self.exclude(target) {
451 return Ok(());
452 }
453
454 if !self.file_tracker.add_file(target, source)? {
455 // Ignore duplicate files.
456 return Ok(());
457 }
458
459 let mut header = tar::Header::new_gnu();
460 header.set_size(bytes.len() as u64);
461 header.set_mode(permissions);
462 header.set_cksum();
463 self.tar
464 .append_data(&mut header, target, bytes)
465 .context(format!(
466 "Failed to add {} bytes to sdist as {}",
467 bytes.len(),
468 target.display()
469 ))?;
470 Ok(())
471 }
472
473 fn add_file(&mut self, target: impl AsRef<Path>, source: impl AsRef<Path>) -> Result<()> {
474 let source = source.as_ref();
475 if self.exclude(source) {
476 return Ok(());
477 }
478 let target = target.as_ref();
479 if !self.file_tracker.add_file(target, Some(source))? {
480 // Ignore duplicate files.
481 return Ok(());
482 }
483
484 debug!("Adding {} from {}", target.display(), source.display());
485 self.tar
486 .append_path_with_name(source, target)
487 .context(format!(
488 "Failed to add file from {} to sdist as {}",
489 source.display(),
490 target.display(),
491 ))?;
492 Ok(())
493 }
494 }
495
496 impl SDistWriter {
497 /// Create a source distribution .tar.gz which can be subsequently expanded
498 pub fn new(
499 wheel_dir: impl AsRef<Path>,
500 metadata24: &Metadata24,
501 excludes: Override,
502 ) -> Result<Self, io::Error> {
503 let path = wheel_dir
504 .as_ref()
505 .normalize()?
506 .join(format!(
507 "{}-{}.tar.gz",
508 &metadata24.get_distribution_escaped(),
509 &metadata24.get_version_escaped()
510 ))
511 .into_path_buf();
512
513 let enc = GzEncoder::new(Vec::new(), Compression::default());
514 let tar = tar::Builder::new(enc);
515
516 Ok(Self {
517 tar,
518 path,
519 file_tracker: FileTracker::default(),
520 excludes,
521 })
522 }
523
524 /// Returns `true` if the given path should be excluded
525 fn exclude(&self, path: impl AsRef<Path>) -> bool {
526 self.excludes.matched(path.as_ref(), false).is_whitelist()
527 }
528
529 /// Finished the .tar.gz archive
530 pub fn finish(self) -> Result<PathBuf, io::Error> {
531 let archive = self.tar.into_inner()?;
532 fs::write(&self.path, archive.finish()?)?;
533 Ok(self.path)
534 }
535 }
536
537 /// Keep track of which files we added from where, so we can skip duplicate files and error when
538 /// adding conflicting files.
539 ///
540 /// The wrapped type contains as key the path added to the archive and as value the originating path
541 /// on the file system or `None` for generated files.
542 #[derive(Default)]
543 struct FileTracker(HashMap<PathBuf, Option<PathBuf>>);
544
545 impl FileTracker {
546 /// Returns `true` if the file should be added, `false` if an identical file was already added
547 /// (skip) and an error if a different file was already added.
548 fn add_file(&mut self, target: &Path, source: Option<&Path>) -> Result<bool> {
549 let Some(previous_source) = self
550 .0
551 .insert(target.to_path_buf(), source.map(|path| path.to_path_buf()))
552 else {
553 // The path doesn't exist in the archive yet.
554 return Ok(true);
555 };
556 match (previous_source, source) {
557 (None, None) => {
558 bail!(
559 "Generated file {} was already added, can't add it again",
560 target.display()
561 );
562 }
563 (Some(previous_source), None) => {
564 bail!(
565 "File {} was already added from {}, can't overwrite with generated file",
566 target.display(),
567 previous_source.display()
568 )
569 }
570 (None, Some(source)) => {
571 bail!(
572 "Generated file {} was already added, can't overwrite it with {}",
573 target.display(),
574 source.display()
575 );
576 }
577 (Some(previous_source), Some(source)) => {
578 if is_same_file(source, &previous_source).unwrap_or(false) {
579 // Ignore identical duplicate files
580 Ok(false)
581 } else {
582 bail!(
583 "File {} was already added from {}, can't added it from {}",
584 target.display(),
585 previous_source.display(),
586 source.display()
587 );
588 }
589 }
590 }
591 }
592 }
593
594 fn wheel_file(tags: &[String]) -> Result<String> {
595 let mut wheel_file = format!(
596 "Wheel-Version: 1.0
597 Generator: {name} ({version})
598 Root-Is-Purelib: false
599 ",
600 name = env!("CARGO_PKG_NAME"),
601 version = env!("CARGO_PKG_VERSION"),
602 );
603
604 for tag in tags {
605 writeln!(wheel_file, "Tag: {tag}")?;
606 }
607
608 Ok(wheel_file)
609 }
610
611 /// https://packaging.python.org/specifications/entry-points/
612 fn entry_points_txt(
613 entry_type: &str,
614 entrypoints: &IndexMap<String, String, impl std::hash::BuildHasher>,
615 ) -> String {
616 entrypoints
617 .iter()
618 .fold(format!("[{entry_type}]\n"), |text, (k, v)| {
619 text + k + "=" + v + "\n"
620 })
621 }
622
623 /// Glue code that exposes `lib`.
624 fn cffi_init_file(cffi_module_file_name: &str) -> String {
625 format!(
626 r#"__all__ = ["lib", "ffi"]
627
628 import os
629 from .ffi import ffi
630
631 lib = ffi.dlopen(os.path.join(os.path.dirname(__file__), '{cffi_module_file_name}'))
632 del os
633 "#
634 )
635 }
636
637 /// Wraps some boilerplate around error handling when calling python
638 fn call_python<I, S>(python: &Path, args: I) -> Result<Output>
639 where
640 I: IntoIterator<Item = S>,
641 S: AsRef<OsStr>,
642 {
643 Command::new(python)
644 .args(args)
645 .output()
646 .context(format!("Failed to run python at {:?}", &python))
647 }
648
649 /// Checks if user has provided their own header at `target/header.h`, otherwise
650 /// we run cbindgen to generate one.
651 fn cffi_header(crate_dir: &Path, target_dir: &Path, tempdir: &TempDir) -> Result<PathBuf> {
652 let maybe_header = target_dir.join("header.h");
653
654 if maybe_header.is_file() {
655 eprintln!("💼 Using the existing header at {}", maybe_header.display());
656 Ok(maybe_header)
657 } else {
658 if crate_dir.join("cbindgen.toml").is_file() {
659 eprintln!(
660 "💼 Using the existing cbindgen.toml configuration.\n\
661 💼 Enforcing the following settings:\n \
662 - language = \"C\" \n \
663 - no_includes = true, sys_includes = []\n \
664 (#include is not yet supported by CFFI)\n \
665 - defines = [], include_guard = None, pragma_once = false, cpp_compat = false\n \
666 (#define, #ifdef, etc. is not yet supported by CFFI)\n"
667 );
668 }
669
670 let mut config = cbindgen::Config::from_root_or_default(crate_dir);
671 config.language = cbindgen::Language::C;
672 config.no_includes = true;
673 config.sys_includes = Vec::new();
674 config.defines = HashMap::new();
675 config.include_guard = None;
676 config.pragma_once = false;
677 config.cpp_compat = false;
678
679 let bindings = cbindgen::Builder::new()
680 .with_config(config)
681 .with_crate(crate_dir)
682 .with_language(cbindgen::Language::C)
683 .with_no_includes()
684 .generate()
685 .context("Failed to run cbindgen")?;
686
687 let header = tempdir.as_ref().join("header.h");
688 bindings.write_to_file(&header);
689 debug!("Generated header.h at {}", header.display());
690 Ok(header)
691 }
692 }
693
694 /// Returns the content of what will become ffi.py by invoking cbindgen and cffi
695 ///
696 /// Checks if user has provided their own header at `target/header.h`, otherwise
697 /// we run cbindgen to generate one. Installs cffi if it's missing and we're inside a virtualenv
698 ///
699 /// We're using the cffi recompiler, which reads the header, translates them into instructions
700 /// how to load the shared library without the header and then writes those instructions to a
701 /// file called `ffi.py`. This `ffi.py` will expose an object called `ffi`. This object is used
702 /// in `__init__.py` to load the shared library into a module called `lib`.
703 pub fn generate_cffi_declarations(
704 crate_dir: &Path,
705 target_dir: &Path,
706 python: &Path,
707 ) -> Result<String> {
708 let tempdir = tempdir()?;
709 let header = cffi_header(crate_dir, target_dir, &tempdir)?;
710
711 let ffi_py = tempdir.as_ref().join("ffi.py");
712
713 // Using raw strings is important because on windows there are path like
714 // `C:\Users\JohnDoe\AppData\Local\TEmpl\pip-wheel-asdf1234` where the \U
715 // would otherwise be a broken unicode escape sequence
716 let cffi_invocation = format!(
717 r#"
718 import cffi
719 from cffi import recompiler
720
721 ffi = cffi.FFI()
722 with open(r"{header}") as header:
723 ffi.cdef(header.read())
724 recompiler.make_py_source(ffi, "ffi", r"{ffi_py}")
725 "#,
726 ffi_py = ffi_py.display(),
727 header = header.display(),
728 );
729
730 let output = call_python(python, ["-c", &cffi_invocation])?;
731 let install_cffi = if !output.status.success() {
732 // First, check whether the error was cffi not being installed
733 let last_line = str::from_utf8(&output.stderr)?.lines().last().unwrap_or("");
734 if last_line == "ModuleNotFoundError: No module named 'cffi'" {
735 // Then check whether we're running in a virtualenv.
736 // We don't want to modify any global environment
737 // https://stackoverflow.com/a/42580137/3549270
738 let output = call_python(
739 python,
740 ["-c", "import sys\nprint(sys.base_prefix != sys.prefix)"],
741 )?;
742
743 match str::from_utf8(&output.stdout)?.trim() {
744 "True" => true,
745 "False" => false,
746 _ => {
747 eprintln!(
748 "⚠️ Failed to determine whether python at {:?} is running inside a virtualenv",
749 &python
750 );
751 false
752 }
753 }
754 } else {
755 false
756 }
757 } else {
758 false
759 };
760
761 // If there was success or an error that was not missing cffi, return here
762 if !install_cffi {
763 return handle_cffi_call_result(python, tempdir, &ffi_py, &output);
764 }
765
766 eprintln!("⚠️ cffi not found. Trying to install it");
767 // Call pip through python to don't do the wrong thing when python and pip
768 // are coming from different environments
769 let output = call_python(
770 python,
771 [
772 "-m",
773 "pip",
774 "install",
775 "--disable-pip-version-check",
776 "cffi",
777 ],
778 )?;
779 if !output.status.success() {
780 bail!(
781 "Installing cffi with `{:?} -m pip install cffi` failed: {}\n--- Stdout:\n{}\n--- Stderr:\n{}\n---\nPlease install cffi yourself.",
782 &python,
783 output.status,
784 str::from_utf8(&output.stdout)?,
785 str::from_utf8(&output.stderr)?
786 );
787 }
788 eprintln!("🎁 Installed cffi");
789
790 // Try again
791 let output = call_python(python, ["-c", &cffi_invocation])?;
792 handle_cffi_call_result(python, tempdir, &ffi_py, &output)
793 }
794
795 /// Extracted into a function because this is needed twice
796 fn handle_cffi_call_result(
797 python: &Path,
798 tempdir: TempDir,
799 ffi_py: &Path,
800 output: &Output,
801 ) -> Result<String> {
802 if !output.status.success() {
803 bail!(
804 "Failed to generate cffi declarations using {}: {}\n--- Stdout:\n{}\n--- Stderr:\n{}",
805 python.display(),
806 output.status,
807 str::from_utf8(&output.stdout)?,
808 str::from_utf8(&output.stderr)?,
809 );
810 } else {
811 // Don't swallow warnings
812 io::stderr().write_all(&output.stderr)?;
813
814 let ffi_py_content = fs::read_to_string(ffi_py)?;
815 tempdir.close()?;
816 Ok(ffi_py_content)
817 }
818 }
819
820 // Extract the shared object from a AIX big library archive
821 fn unpack_big_archive(target: &Target, artifact: &Path, temp_dir_path: &Path) -> Result<PathBuf> {
822 // Newer rust generates archived dylibs on AIX, as shared
823 // libraries are typically archived on the platform.
824 if target.cross_compiling() {
825 bail!("can't unpack big archive format while cross_compiling")
826 }
827 debug!("Unpacking archive {}", artifact.display());
828 let mut ar_command = Command::new("ar");
829 ar_command
830 .current_dir(temp_dir_path)
831 .arg("-X64")
832 .arg("x")
833 .arg(artifact);
834 let status = ar_command.status().expect("Failed to run ar");
835 if !status.success() {
836 bail!(r#"ar finished with "{}": `{:?}`"#, status, ar_command,)
837 }
838 let unpacked_artifact = temp_dir_path.join(artifact.with_extension("so").file_name().unwrap());
839 Ok(unpacked_artifact)
840 }
841
842 /// Copies the shared library into the module, which is the only extra file needed with bindings
843 #[allow(clippy::too_many_arguments)]
844 #[instrument(skip_all)]
845 pub fn write_bindings_module(
846 writer: &mut impl ModuleWriter,
847 project_layout: &ProjectLayout,
848 artifact: &Path,
849 python_interpreter: Option<&PythonInterpreter>,
850 is_abi3: bool,
851 target: &Target,
852 editable: bool,
853 pyproject_toml: Option<&PyProjectToml>,
854 ) -> Result<()> {
855 let ext_name = &project_layout.extension_name;
856 let so_filename = if is_abi3 {
857 if target.is_unix() {
858 format!("{ext_name}.abi3.so")
859 } else {
860 match python_interpreter {
861 Some(python_interpreter) if python_interpreter.is_windows_debug() => {
862 format!("{ext_name}_d.pyd")
863 }
864 // Apparently there is no tag for abi3 on windows
865 _ => format!("{ext_name}.pyd"),
866 }
867 }
868 } else {
869 let python_interpreter =
870 python_interpreter.expect("A python interpreter is required for non-abi3 build");
871 python_interpreter.get_library_name(ext_name)
872 };
873
874 let artifact_is_big_ar =
875 target.is_aix() && artifact.extension().unwrap_or(OsStr::new(" ")) == OsStr::new("a");
876 let temp_dir = if artifact_is_big_ar {
877 Some(tempfile::tempdir()?)
878 } else {
879 None
880 };
881 let artifact_buff = if artifact_is_big_ar {
882 Some(unpack_big_archive(
883 target,
884 artifact,
885 temp_dir.as_ref().unwrap().path(),
886 )?)
887 } else {
888 None
889 };
890 let artifact = if artifact_is_big_ar {
891 artifact_buff.as_ref().unwrap()
892 } else {
893 artifact
894 };
895
896 if !editable {
897 write_python_part(writer, project_layout, pyproject_toml)
898 .context("Failed to add the python module to the package")?;
899 }
900 if let Some(python_module) = &project_layout.python_module {
901 if editable {
902 let target = project_layout.rust_module.join(&so_filename);
903 // Remove existing so file to avoid triggering SIGSEV in running process
904 // See https://github.com/PyO3/maturin/issues/758
905 debug!("Removing {}", target.display());
906 let _ = fs::remove_file(&target);
907
908 debug!("Copying {} to {}", artifact.display(), target.display());
909 fs::copy(artifact, &target).context(format!(
910 "Failed to copy {} to {}",
911 artifact.display(),
912 target.display()
913 ))?;
914 } else {
915 let relative = project_layout
916 .rust_module
917 .strip_prefix(python_module.parent().unwrap())
918 .unwrap();
919 writer.add_file_with_permissions(relative.join(&so_filename), artifact, 0o755)?;
920 }
921 } else {
922 let module = PathBuf::from(ext_name);
923 writer.add_directory(&module)?;
924 // Reexport the shared library as if it were the top level module
925 writer.add_bytes(
926 module.join("__init__.py"),
927 None,
928 format!(
929 r#"from .{ext_name} import *
930
931 __doc__ = {ext_name}.__doc__
932 if hasattr({ext_name}, "__all__"):
933 __all__ = {ext_name}.__all__"#
934 )
935 .as_bytes(),
936 )?;
937 let type_stub = project_layout.rust_module.join(format!("{ext_name}.pyi"));
938 if type_stub.exists() {
939 eprintln!("📖 Found type stub file at {ext_name}.pyi");
940 writer.add_file(module.join("__init__.pyi"), type_stub)?;
941 writer.add_bytes(module.join("py.typed"), None, b"")?;
942 }
943 writer.add_file_with_permissions(module.join(so_filename), artifact, 0o755)?;
944 }
945
946 Ok(())
947 }
948
949 /// Creates the cffi module with the shared library, the cffi declarations and the cffi loader
950 #[allow(clippy::too_many_arguments)]
951 pub fn write_cffi_module(
952 writer: &mut impl ModuleWriter,
953 target: &Target,
954 project_layout: &ProjectLayout,
955 crate_dir: &Path,
956 target_dir: &Path,
957 module_name: &str,
958 artifact: &Path,
959 python: &Path,
960 editable: bool,
961 pyproject_toml: Option<&PyProjectToml>,
962 ) -> Result<()> {
963 let cffi_declarations = generate_cffi_declarations(crate_dir, target_dir, python)?;
964
965 if !editable {
966 write_python_part(writer, project_layout, pyproject_toml)
967 .context("Failed to add the python module to the package")?;
968 }
969
970 let cffi_module_file_name = {
971 let extension_name = &project_layout.extension_name;
972 // https://cffi.readthedocs.io/en/stable/embedding.html#issues-about-using-the-so
973 match target.target_os() {
974 Os::Macos => format!("lib{extension_name}.dylib"),
975 Os::Windows => format!("{extension_name}.dll"),
976 _ => format!("lib{extension_name}.so"),
977 }
978 };
979 let module;
980 if let Some(python_module) = &project_layout.python_module {
981 if editable {
982 let base_path = python_module.join(&project_layout.extension_name);
983 fs::create_dir_all(&base_path)?;
984 let target = base_path.join(&cffi_module_file_name);
985 fs::copy(artifact, &target).context(format!(
986 "Failed to copy {} to {}",
987 artifact.display(),
988 target.display()
989 ))?;
990 File::create(base_path.join("__init__.py"))?
991 .write_all(cffi_init_file(&cffi_module_file_name).as_bytes())?;
992 File::create(base_path.join("ffi.py"))?.write_all(cffi_declarations.as_bytes())?;
993 }
994
995 let relative = project_layout
996 .rust_module
997 .strip_prefix(python_module.parent().unwrap())
998 .unwrap();
999 module = relative.join(&project_layout.extension_name);
1000 if !editable {
1001 writer.add_directory(&module)?;
1002 }
1003 } else {
1004 module = PathBuf::from(module_name);
1005 writer.add_directory(&module)?;
1006 let type_stub = project_layout
1007 .rust_module
1008 .join(format!("{module_name}.pyi"));
1009 if type_stub.exists() {
1010 eprintln!("📖 Found type stub file at {module_name}.pyi");
1011 writer.add_file(module.join("__init__.pyi"), type_stub)?;
1012 writer.add_bytes(module.join("py.typed"), None, b"")?;
1013 }
1014 };
1015
1016 if !editable || project_layout.python_module.is_none() {
1017 writer.add_bytes(
1018 module.join("__init__.py"),
1019 None,
1020 cffi_init_file(&cffi_module_file_name).as_bytes(),
1021 )?;
1022 writer.add_bytes(module.join("ffi.py"), None, cffi_declarations.as_bytes())?;
1023 writer.add_file_with_permissions(module.join(&cffi_module_file_name), artifact, 0o755)?;
1024 }
1025
1026 Ok(())
1027 }
1028
1029 /// uniffi.toml
1030 #[derive(Debug, serde::Deserialize)]
1031 struct UniFfiToml {
1032 #[serde(default)]
1033 bindings: HashMap<String, UniFfiBindingsConfig>,
1034 }
1035
1036 /// `bindings` section of uniffi.toml
1037 #[derive(Debug, serde::Deserialize)]
1038 struct UniFfiBindingsConfig {
1039 cdylib_name: Option<String>,
1040 }
1041
1042 #[derive(Debug, Clone)]
1043 struct UniFfiBindings {
1044 names: Vec<String>,
1045 cdylib: String,
1046 path: PathBuf,
1047 }
1048
1049 fn uniffi_bindgen_command(crate_dir: &Path) -> Result<Command> {
1050 let manifest_path = crate_dir.join("Cargo.toml");
1051 let cargo_metadata = cargo_metadata::MetadataCommand::new()
1052 .manifest_path(&manifest_path)
1053 // We don't need to resolve the dependency graph
1054 .no_deps()
1055 .verbose(true)
1056 .exec()?;
1057 let root_pkg = match cargo_metadata.root_package() {
1058 Some(pkg) => Some(pkg),
1059 None => cargo_metadata
1060 .packages
1061 .iter()
1062 .find(|p| p.manifest_path == manifest_path),
1063 };
1064
1065 let has_uniffi_bindgen_target = root_pkg
1066 .map(|pkg| {
1067 pkg.targets
1068 .iter()
1069 .any(|target| target.name == "uniffi-bindgen" && target.is_bin())
1070 })
1071 .unwrap_or(false);
1072 let has_uniffi_bindgen_workspace_package = cargo_metadata.packages.iter().any(|pkg| {
1073 pkg.targets
1074 .iter()
1075 .any(|target| target.name == "uniffi-bindgen" && target.is_bin())
1076 });
1077
1078 let command = if has_uniffi_bindgen_target {
1079 let mut command = Command::new("cargo");
1080 command
1081 .args(["run", "--bin", "uniffi-bindgen", "--manifest-path"])
1082 .arg(manifest_path)
1083 .current_dir(crate_dir)
1084 .env_remove("CARGO_BUILD_TARGET");
1085 command
1086 } else if has_uniffi_bindgen_workspace_package {
1087 let mut command = Command::new("cargo");
1088 command
1089 .args(["run", "--bin", "uniffi-bindgen"])
1090 .current_dir(cargo_metadata.workspace_root)
1091 .env_remove("CARGO_BUILD_TARGET");
1092 command
1093 } else {
1094 let mut command = Command::new("uniffi-bindgen");
1095 command.current_dir(crate_dir);
1096 command
1097 };
1098 Ok(command)
1099 }
1100
1101 fn generate_uniffi_bindings(
1102 crate_dir: &Path,
1103 target_dir: &Path,
1104 module_name: &str,
1105 target_os: Os,
1106 artifact: &Path,
1107 ) -> Result<UniFfiBindings> {
1108 // `binding_dir` must use absolute path because we chdir to `crate_dir`
1109 // when running uniffi-bindgen
1110 let binding_dir = target_dir
1111 .normalize()?
1112 .join(env!("CARGO_PKG_NAME"))
1113 .join("uniffi")
1114 .join(module_name)
1115 .into_path_buf();
1116 fs::create_dir_all(&binding_dir)?;
1117
1118 let pattern = crate_dir.join("src").join("*.udl");
1119 let udls = glob::glob(pattern.to_str().unwrap())?
1120 .map(|p| p.unwrap())
1121 .collect::<Vec<_>>();
1122 let is_library = if udls.is_empty() {
1123 true
1124 } else if udls.len() > 1 {
1125 bail!(
1126 "Multiple UDL files found in {}",
1127 crate_dir.join("src").display()
1128 );
1129 } else {
1130 false
1131 };
1132
1133 let mut cmd = uniffi_bindgen_command(crate_dir)?;
1134 cmd.args([
1135 "generate",
1136 "--no-format",
1137 "--language",
1138 "python",
1139 "--out-dir",
1140 ]);
1141 cmd.arg(&binding_dir);
1142
1143 let config_file = crate_dir.join("uniffi.toml");
1144 let mut cdylib_name = None;
1145 if config_file.is_file() {
1146 let uniffi_toml: UniFfiToml = toml::from_str(&fs::read_to_string(&config_file)?)?;
1147 cdylib_name = uniffi_toml
1148 .bindings
1149 .get("python")
1150 .and_then(|py| py.cdylib_name.clone());
1151 if !is_library {
1152 cmd.arg("--config");
1153 cmd.arg(config_file);
1154 }
1155 }
1156
1157 let py_binding_name = if is_library {
1158 cmd.arg("--library");
1159 cmd.arg(artifact);
1160 let file_stem = artifact.file_stem().unwrap().to_str().unwrap();
1161 file_stem
1162 .strip_prefix("lib")
1163 .unwrap_or(file_stem)
1164 .to_string()
1165 } else {
1166 let udl = &udls[0];
1167 cmd.arg(udl);
1168 udl.file_stem().unwrap().to_str().unwrap().to_string()
1169 };
1170 debug!("Running {:?}", cmd);
1171 let mut child = cmd.spawn().context(
1172 "Failed to run uniffi-bindgen, did you install it? Try `pip install uniffi-bindgen`",
1173 )?;
1174 let exit_status = child.wait().context("Failed to run uniffi-bindgen")?;
1175 if !exit_status.success() {
1176 bail!("Command {:?} failed", cmd);
1177 }
1178
1179 // uniffi bindings hardcoded the extension filenames
1180 let cdylib_name = match cdylib_name {
1181 Some(name) => name,
1182 None => format!("uniffi_{py_binding_name}"),
1183 };
1184 let cdylib = match target_os {
1185 Os::Macos => format!("lib{cdylib_name}.dylib"),
1186 Os::Windows => format!("{cdylib_name}.dll"),
1187 _ => format!("lib{cdylib_name}.so"),
1188 };
1189
1190 let py_bindings = fs::read_dir(&binding_dir)?
1191 .flatten()
1192 .filter(|file| file.path().extension().and_then(std::ffi::OsStr::to_str) == Some("py"))
1193 .map(|file| {
1194 file.path()
1195 .file_stem()
1196 .unwrap()
1197 .to_string_lossy()
1198 .to_string()
1199 })
1200 .collect_vec();
1201
1202 Ok(UniFfiBindings {
1203 names: py_bindings,
1204 cdylib,
1205 path: binding_dir,
1206 })
1207 }
1208
1209 /// Creates the uniffi module with the shared library
1210 #[allow(clippy::too_many_arguments)]
1211 pub fn write_uniffi_module(
1212 writer: &mut impl ModuleWriter,
1213 project_layout: &ProjectLayout,
1214 crate_dir: &Path,
1215 target_dir: &Path,
1216 module_name: &str,
1217 artifact: &Path,
1218 target_os: Os,
1219 editable: bool,
1220 pyproject_toml: Option<&PyProjectToml>,
1221 ) -> Result<()> {
1222 let UniFfiBindings {
1223 names: binding_names,
1224 cdylib,
1225 path: binding_dir,
1226 } = generate_uniffi_bindings(crate_dir, target_dir, module_name, target_os, artifact)?;
1227
1228 let py_init = binding_names
1229 .iter()
1230 .map(|name| format!("from .{name} import * # NOQA\n"))
1231 .collect::<Vec<String>>()
1232 .join("");
1233
1234 if !editable {
1235 write_python_part(writer, project_layout, pyproject_toml)
1236 .context("Failed to add the python module to the package")?;
1237 }
1238
1239 let module;
1240 if let Some(python_module) = &project_layout.python_module {
1241 if editable {
1242 let base_path = python_module.join(&project_layout.extension_name);
1243 fs::create_dir_all(&base_path)?;
1244 let target = base_path.join(&cdylib);
1245 fs::copy(artifact, &target).context(format!(
1246 "Failed to copy {} to {}",
1247 artifact.display(),
1248 target.display()
1249 ))?;
1250
1251 File::create(base_path.join("__init__.py"))?.write_all(py_init.as_bytes())?;
1252
1253 for binding_name in binding_names.iter() {
1254 let target: PathBuf = base_path.join(binding_name).with_extension("py");
1255 fs::copy(binding_dir.join(binding_name).with_extension("py"), &target)
1256 .with_context(|| {
1257 format!("Failed to copy {:?} to {:?}", binding_dir.display(), target)
1258 })?;
1259 }
1260 }
1261
1262 let relative = project_layout
1263 .rust_module
1264 .strip_prefix(python_module.parent().unwrap())
1265 .unwrap();
1266 module = relative.join(&project_layout.extension_name);
1267 if !editable {
1268 writer.add_directory(&module)?;
1269 }
1270 } else {
1271 module = PathBuf::from(module_name);
1272 writer.add_directory(&module)?;
1273 let type_stub = project_layout
1274 .rust_module
1275 .join(format!("{module_name}.pyi"));
1276 if type_stub.exists() {
1277 eprintln!("📖 Found type stub file at {module_name}.pyi");
1278 writer.add_file(module.join("__init__.pyi"), type_stub)?;
1279 writer.add_bytes(module.join("py.typed"), None, b"")?;
1280 }
1281 };
1282
1283 if !editable || project_layout.python_module.is_none() {
1284 writer.add_bytes(module.join("__init__.py"), None, py_init.as_bytes())?;
1285 for binding in binding_names.iter() {
1286 writer.add_file(
1287 module.join(binding).with_extension("py"),
1288 binding_dir.join(binding).with_extension("py"),
1289 )?;
1290 }
1291 writer.add_file_with_permissions(module.join(cdylib), artifact, 0o755)?;
1292 }
1293
1294 Ok(())
1295 }
1296
1297 /// Adds a data directory with a scripts directory with the binary inside it
1298 pub fn write_bin(
1299 writer: &mut impl ModuleWriter,
1300 artifact: &Path,
1301 metadata: &Metadata24,
1302 bin_name: &str,
1303 ) -> Result<()> {
1304 let data_dir = PathBuf::from(format!(
1305 "{}-{}.data",
1306 &metadata.get_distribution_escaped(),
1307 &metadata.version
1308 ))
1309 .join("scripts");
1310
1311 writer.add_directory(&data_dir)?;
1312
1313 // We can't use add_file since we need to mark the file as executable
1314 writer.add_file_with_permissions(data_dir.join(bin_name), artifact, 0o755)?;
1315 Ok(())
1316 }
1317
1318 /// Adds a wrapper script that start the wasm binary through wasmtime.
1319 ///
1320 /// Note that the wasm binary needs to be written separately by [write_bin]
1321 pub fn write_wasm_launcher(
1322 writer: &mut impl ModuleWriter,
1323 metadata: &Metadata24,
1324 bin_name: &str,
1325 ) -> Result<()> {
1326 let entrypoint_script = format!(
1327 r#"from pathlib import Path
1328
1329 from wasmtime import Store, Module, Engine, WasiConfig, Linker
1330
1331 import sysconfig
1332
1333 def main():
1334 # The actual executable
1335 program_location = Path(sysconfig.get_path("scripts")).joinpath("{bin_name}")
1336 # wasmtime-py boilerplate
1337 engine = Engine()
1338 store = Store(engine)
1339 # TODO: is there an option to just get the default of the wasmtime cli here?
1340 wasi = WasiConfig()
1341 wasi.inherit_argv()
1342 wasi.inherit_env()
1343 wasi.inherit_stdout()
1344 wasi.inherit_stderr()
1345 wasi.inherit_stdin()
1346 # TODO: Find a real solution here. Maybe there's an always allow callback?
1347 # Even fancier would be something configurable in pyproject.toml
1348 wasi.preopen_dir(".", ".")
1349 store.set_wasi(wasi)
1350 linker = Linker(engine)
1351 linker.define_wasi()
1352 module = Module.from_file(store.engine, str(program_location))
1353 linking1 = linker.instantiate(store, module)
1354 # TODO: this is taken from https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default
1355 # is this always correct?
1356 start = linking1.exports(store).get("") or linking1.exports(store)["_start"]
1357 start(store)
1358
1359 if __name__ == '__main__':
1360 main()
1361 "#
1362 );
1363
1364 // We can't use add_file since we want to mark the file as executable
1365 let launcher_path = Path::new(&metadata.get_distribution_escaped())
1366 .join(bin_name.replace('-', "_"))
1367 .with_extension("py");
1368 writer.add_bytes_with_permissions(&launcher_path, None, entrypoint_script.as_bytes(), 0o755)?;
1369 Ok(())
1370 }
1371
1372 /// Adds the python part of a mixed project to the writer,
1373 pub fn write_python_part(
1374 writer: &mut impl ModuleWriter,
1375 project_layout: &ProjectLayout,
1376 pyproject_toml: Option<&PyProjectToml>,
1377 ) -> Result<()> {
1378 let python_dir = &project_layout.python_dir;
1379 let mut python_packages = Vec::new();
1380 if let Some(python_module) = project_layout.python_module.as_ref() {
1381 python_packages.push(python_module.to_path_buf());
1382 }
1383 for package in &project_layout.python_packages {
1384 let package_path = python_dir.join(package);
1385 if python_packages.contains(&package_path) {
1386 continue;
1387 }
1388 python_packages.push(package_path);
1389 }
1390
1391 for package in python_packages {
1392 for absolute in WalkBuilder::new(&project_layout.project_root)
1393 .hidden(false)
1394 .parents(false)
1395 .git_global(false)
1396 .git_exclude(false)
1397 .build()
1398 {
1399 let absolute = absolute?.into_path();
1400 if !absolute.starts_with(package.as_path()) {
1401 continue;
1402 }
1403 let relative = absolute.strip_prefix(python_dir).unwrap();
1404 if absolute.is_dir() {
1405 writer.add_directory(relative)?;
1406 } else {
1407 // Ignore native libraries from develop, if any
1408 if let Some(extension) = relative.extension() {
1409 if extension.to_string_lossy() == "so" {
1410 debug!("Ignoring native library {}", relative.display());
1411 continue;
1412 }
1413 }
1414 #[cfg(unix)]
1415 let mode = absolute.metadata()?.permissions().mode();
1416 #[cfg(not(unix))]
1417 let mode = 0o644;
1418 writer
1419 .add_file_with_permissions(relative, &absolute, mode)
1420 .context(format!("File to add file from {}", absolute.display()))?;
1421 }
1422 }
1423 }
1424
1425 // Include additional files
1426 if let Some(pyproject) = pyproject_toml {
1427 // FIXME: in src-layout pyproject.toml isn't located directly in python dir
1428 let pyproject_dir = python_dir;
1429 if let Some(glob_patterns) = pyproject.include() {
1430 for pattern in glob_patterns
1431 .iter()
1432 .filter_map(|glob_pattern| glob_pattern.targets(Format::Wheel))
1433 {
1434 eprintln!("📦 Including files matching \"{pattern}\"");
1435 for source in glob::glob(&pyproject_dir.join(pattern).to_string_lossy())
1436 .with_context(|| format!("Invalid glob pattern: {pattern}"))?
1437 .filter_map(Result::ok)
1438 {
1439 let target = source.strip_prefix(pyproject_dir)?.to_path_buf();
1440 if source.is_dir() {
1441 writer.add_directory(target)?;
1442 } else {
1443 #[cfg(unix)]
1444 let mode = source.metadata()?.permissions().mode();
1445 #[cfg(not(unix))]
1446 let mode = 0o644;
1447 writer.add_file_with_permissions(target, source, mode)?;
1448 }
1449 }
1450 }
1451 }
1452 }
1453
1454 Ok(())
1455 }
1456
1457 /// Creates the .dist-info directory and fills it with all metadata files except RECORD
1458 pub fn write_dist_info(
1459 writer: &mut impl ModuleWriter,
1460 pyproject_dir: &Path,
1461 metadata24: &Metadata24,
1462 tags: &[String],
1463 ) -> Result<()> {
1464 let dist_info_dir = metadata24.get_dist_info_dir();
1465
1466 writer.add_directory(&dist_info_dir)?;
1467
1468 writer.add_bytes(
1469 dist_info_dir.join("METADATA"),
1470 None,
1471 metadata24.to_file_contents()?.as_bytes(),
1472 )?;
1473
1474 writer.add_bytes(
1475 dist_info_dir.join("WHEEL"),
1476 None,
1477 wheel_file(tags)?.as_bytes(),
1478 )?;
1479
1480 let mut entry_points = String::new();
1481 if !metadata24.scripts.is_empty() {
1482 entry_points.push_str(&entry_points_txt("console_scripts", &metadata24.scripts));
1483 }
1484 if !metadata24.gui_scripts.is_empty() {
1485 entry_points.push_str(&entry_points_txt("gui_scripts", &metadata24.gui_scripts));
1486 }
1487 for (entry_type, scripts) in &metadata24.entry_points {
1488 entry_points.push_str(&entry_points_txt(entry_type, scripts));
1489 }
1490 if !entry_points.is_empty() {
1491 writer.add_bytes(
1492 dist_info_dir.join("entry_points.txt"),
1493 None,
1494 entry_points.as_bytes(),
1495 )?;
1496 }
1497
1498 if !metadata24.license_files.is_empty() {
1499 let license_files_dir = dist_info_dir.join("licenses");
1500 writer.add_directory(&license_files_dir)?;
1501 for path in &metadata24.license_files {
1502 writer.add_file(license_files_dir.join(path), pyproject_dir.join(path))?;
1503 }
1504 }
1505
1506 Ok(())
1507 }
1508
1509 /// If any, copies the data files from the data directory, resolving symlinks to their source.
1510 /// We resolve symlinks since we require this rather rigid structure while people might need
1511 /// to save or generate the data in other places
1512 ///
1513 /// See https://peps.python.org/pep-0427/#file-contents
1514 pub fn add_data(
1515 writer: &mut impl ModuleWriter,
1516 metadata24: &Metadata24,
1517 data: Option<&Path>,
1518 ) -> Result<()> {
1519 let possible_data_dir_names = ["data", "scripts", "headers", "purelib", "platlib"];
1520 if let Some(data) = data {
1521 for subdir in fs::read_dir(data).context("Failed to read data dir")? {
1522 let subdir = subdir?;
1523 let dir_name = subdir
1524 .file_name()
1525 .to_str()
1526 .context("Invalid data dir name")?
1527 .to_string();
1528 if !subdir.path().is_dir() || !possible_data_dir_names.contains(&dir_name.as_str()) {
1529 bail!(
1530 "Invalid data dir entry {}. Possible are directories named {}",
1531 subdir.path().display(),
1532 possible_data_dir_names.join(", ")
1533 );
1534 }
1535 debug!("Adding data from {}", subdir.path().display());
1536 (|| {
1537 for file in WalkBuilder::new(subdir.path())
1538 .standard_filters(false)
1539 .build()
1540 {
1541 let file = file?;
1542 #[cfg(unix)]
1543 let mode = file.metadata()?.permissions().mode();
1544 #[cfg(not(unix))]
1545 let mode = 0o644;
1546 let relative = metadata24
1547 .get_data_dir()
1548 .join(file.path().strip_prefix(data).unwrap());
1549
1550 if file.path_is_symlink() {
1551 // Copy the actual file contents, not the link, so that you can create a
1552 // data directory by joining different data sources
1553 let source = fs::read_link(file.path())?;
1554 writer.add_file_with_permissions(
1555 relative,
1556 source.parent().unwrap(),
1557 mode,
1558 )?;
1559 } else if file.path().is_file() {
1560 writer.add_file_with_permissions(relative, file.path(), mode)?;
1561 } else if file.path().is_dir() {
1562 writer.add_directory(relative)?;
1563 } else {
1564 bail!("Can't handle data dir entry {}", file.path().display());
1565 }
1566 }
1567 Ok(())
1568 })()
1569 .with_context(|| format!("Failed to include data from {}", data.display()))?
1570 }
1571 }
1572 Ok(())
1573 }
1574
1575 #[cfg(test)]
1576 mod tests {
1577 use ignore::overrides::OverrideBuilder;
1578 use pep440_rs::Version;
1579
1580 use super::*;
1581
1582 #[test]
1583 // The mechanism is the same for wheel_writer
1584 fn sdist_writer_excludes() -> Result<(), Box<dyn std::error::Error>> {
1585 let metadata = Metadata24::new("dummy".to_string(), Version::new([1, 0]));
1586 let perm = 0o777;
1587
1588 // No excludes
1589 let tmp_dir = TempDir::new()?;
1590 let mut writer = SDistWriter::new(&tmp_dir, &metadata, Override::empty())?;
1591 assert!(writer.file_tracker.0.is_empty());
1592 writer.add_bytes_with_permissions("test", Some(Path::new("test")), &[], perm)?;
1593 assert_eq!(writer.file_tracker.0.len(), 1);
1594 writer.finish()?;
1595 tmp_dir.close()?;
1596
1597 // A test filter
1598 let tmp_dir = TempDir::new()?;
1599 let mut excludes = OverrideBuilder::new(&tmp_dir);
1600 excludes.add("test*")?;
1601 excludes.add("!test2")?;
1602 let mut writer = SDistWriter::new(&tmp_dir, &metadata, excludes.build()?)?;
1603 writer.add_bytes_with_permissions("test1", Some(Path::new("test1")), &[], perm)?;
1604 writer.add_bytes_with_permissions("test3", Some(Path::new("test3")), &[], perm)?;
1605 assert!(writer.file_tracker.0.is_empty());
1606 writer.add_bytes_with_permissions("test2", Some(Path::new("test2")), &[], perm)?;
1607 assert!(!writer.file_tracker.0.is_empty());
1608 writer.add_bytes_with_permissions("yes", Some(Path::new("yes")), &[], perm)?;
1609 assert_eq!(writer.file_tracker.0.len(), 2);
1610 writer.finish()?;
1611 tmp_dir.close()?;
1612
1613 Ok(())
1614 }
1615
1616 #[test]
1617 fn wheel_writer_no_compression() -> Result<(), Box<dyn std::error::Error>> {
1618 let metadata = Metadata24::new("dummy".to_string(), Version::new([1, 0]));
1619 let tmp_dir = TempDir::new()?;
1620
1621 let writer = WheelWriter::new(
1622 "no compression",
1623 tmp_dir.path(),
1624 tmp_dir.path(),
1625 &metadata,
1626 &[],
1627 Override::empty(),
1628 CompressionOptions {
1629 compression_method: CompressionMethod::Stored,
1630 ..Default::default()
1631 },
1632 )?;
1633
1634 writer.finish()?;
1635 tmp_dir.close()?;
1636
1637 Ok(())
1638 }
1639 }