Debian Codegraph @

src/develop.rs

raw
1 use crate::auditwheel::AuditWheelMode;
2 use crate::build_options::CargoOptions;
3 use crate::compression::CompressionOptions;
4 use crate::target::detect_arch_from_python;
5 use crate::BuildContext;
6 use crate::BuildOptions;
7 use crate::PlatformTag;
8 use crate::PythonInterpreter;
9 use crate::Target;
10 use anyhow::ensure;
11 use anyhow::{anyhow, bail, Context, Result};
12 use cargo_options::heading;
13 use fs_err as fs;
14 use regex::Regex;
15 use std::path::Path;
16 use std::path::PathBuf;
17 use std::process::Command;
18 use std::str;
19 use tempfile::TempDir;
20 use tracing::{debug, instrument};
21 use url::Url;
22
23 enum InstallBackend {
24 Pip {
25 path: Option<PathBuf>,
26 },
27 Uv {
28 path: PathBuf,
29 args: Vec<&'static str>,
30 },
31 }
32
33 impl InstallBackend {
34 fn name(&self) -> &'static str {
35 match self {
36 InstallBackend::Pip { .. } => "pip",
37 InstallBackend::Uv { .. } => "uv pip",
38 }
39 }
40
41 fn version(&self, python_path: &Path) -> Result<semver::Version> {
42 let mut cmd = self.make_command(python_path);
43
44 // Newer versions of uv no longer support `uv pip --version`, and instead
45 // require that we use `uv --version`. This is a workaround to get the
46 // version of the install backend for both old and new versions of uv.
47 cmd = match self {
48 InstallBackend::Pip { .. } => cmd,
49 InstallBackend::Uv { path, args } => {
50 let mut cmd = Command::new(path);
51 cmd.args(args);
52 cmd
53 }
54 };
55 let output = cmd
56 .arg("--version")
57 .output()
58 .context("failed to get version of install backend")?;
59 ensure!(
60 output.status.success(),
61 "failed to get version of install backend"
62 );
63 let stdout = str::from_utf8(&output.stdout)?;
64 let re = match self {
65 InstallBackend::Pip { .. } => Regex::new(r"pip ([\w\.]+).*"),
66 InstallBackend::Uv { .. } => Regex::new(r"uv ([\w\.]+).*"),
67 };
68 if let Some(captures) = re.expect("regex should be valid").captures(stdout) {
69 Ok(semver::Version::parse(&captures[1])
70 .with_context(|| format!("failed to parse semver from {stdout:?}"))?)
71 } else {
72 bail!("failed to parse version from {:?}", stdout);
73 }
74 }
75
76 /// check whether this install backend supports `show --files`. Returns Ok(()) if it does.
77 fn check_supports_show_files(&self, python_path: &Path) -> Result<()> {
78 match self {
79 InstallBackend::Pip { .. } => Ok(()),
80 InstallBackend::Uv { .. } => {
81 // https://github.com/astral-sh/uv/releases/tag/0.4.25
82 let version = self.version(python_path)?;
83 if version < semver::Version::new(0, 4, 25) {
84 bail!(
85 "uv >= 0.4.25 is required for `show --files`. Version {} was found.",
86 version
87 );
88 }
89 Ok(())
90 }
91 }
92 }
93
94 fn stderr_indicates_problem(&self) -> bool {
95 match self {
96 InstallBackend::Pip { .. } => true,
97 // `uv pip install` sends regular logs to stderr, not just errors
98 InstallBackend::Uv { .. } => false,
99 }
100 }
101
102 fn make_command(&self, python_path: &Path) -> Command {
103 match self {
104 InstallBackend::Pip { path } => match &path {
105 Some(path) => {
106 let mut cmd = Command::new(path);
107 cmd.arg("--python")
108 .arg(python_path)
109 .arg("--disable-pip-version-check");
110 cmd
111 }
112 None => {
113 let mut cmd = Command::new(python_path);
114 cmd.arg("-m").arg("pip").arg("--disable-pip-version-check");
115 cmd
116 }
117 },
118 InstallBackend::Uv { path, args } => {
119 let mut cmd = Command::new(path);
120 cmd.args(args).arg("pip");
121 cmd
122 }
123 }
124 }
125 }
126
127 /// Detect the plain uv binary
128 fn find_uv_bin() -> Result<(PathBuf, Vec<&'static str>)> {
129 let output = Command::new("uv").arg("--version").output()?;
130 if output.status.success() {
131 let version_str =
132 str::from_utf8(&output.stdout).context("`uv --version` didn't return utf8 output")?;
133 debug!(version = %version_str, "Found uv binary in PATH");
134 Ok((PathBuf::from("uv"), Vec::new()))
135 } else {
136 bail!("`uv --version` failed with status: {}", output.status);
137 }
138 }
139
140 /// Detect the Python uv package
141 fn find_uv_python(python_path: &Path) -> Result<(PathBuf, Vec<&'static str>)> {
142 let output = Command::new(python_path)
143 .args(["-m", "uv", "--version"])
144 .output()?;
145 if output.status.success() {
146 let version_str =
147 str::from_utf8(&output.stdout).context("`uv --version` didn't return utf8 output")?;
148 debug!(version = %version_str, "Found Python uv module");
149 Ok((python_path.to_path_buf(), vec!["-m", "uv"]))
150 } else {
151 bail!(
152 "`{} -m uv --version` failed with status: {}",
153 python_path.display(),
154 output.status
155 );
156 }
157 }
158
159 fn check_pip_exists(python_path: &Path, pip_path: Option<&PathBuf>) -> Result<()> {
160 let output = if let Some(pip_path) = pip_path {
161 Command::new(pip_path).args(["--version"]).output()?
162 } else {
163 Command::new(python_path)
164 .args(["-m", "pip", "--version"])
165 .output()?
166 };
167 if output.status.success() {
168 let version_str =
169 str::from_utf8(&output.stdout).context("`pip --version` didn't return utf8 output")?;
170 debug!(version = %version_str, "Found pip");
171 Ok(())
172 } else {
173 bail!("`pip --version` failed with status: {}", output.status);
174 }
175 }
176
177 /// Check if a virtualenv is created by uv by reading pyvenv.cfg
178 fn is_uv_venv(venv_dir: &Path) -> bool {
179 let pyvenv_cfg = venv_dir.join("pyvenv.cfg");
180 if !pyvenv_cfg.exists() {
181 return false;
182 }
183 match fs::read_to_string(&pyvenv_cfg) {
184 Ok(content) => content.contains("\nuv = "),
185 Err(_) => false,
186 }
187 }
188
189 /// Install the crate as module in the current virtualenv
190 #[derive(Debug, clap::Parser)]
191 pub struct DevelopOptions {
192 /// Which kind of bindings to use
193 #[arg(
194 short = 'b',
195 long = "bindings",
196 alias = "binding-crate",
197 value_parser = ["pyo3", "pyo3-ffi", "cffi", "uniffi", "bin"]
198 )]
199 pub bindings: Option<String>,
200 /// Pass --release to cargo
201 #[arg(short = 'r', long, help_heading = heading::COMPILATION_OPTIONS,)]
202 pub release: bool,
203 /// Strip the library for minimum file size
204 #[arg(long)]
205 pub strip: bool,
206 /// Install extra requires aka. optional dependencies
207 ///
208 /// Use as `--extras=extra1,extra2`
209 #[arg(
210 short = 'E',
211 long,
212 value_delimiter = ',',
213 action = clap::ArgAction::Append
214 )]
215 pub extras: Vec<String>,
216 /// Skip installation, only build the extension module inplace
217 ///
218 /// Only works with mixed Rust/Python project layout
219 #[arg(long)]
220 pub skip_install: bool,
221 /// Use a specific pip installation instead of the default one.
222 ///
223 /// This can be used to supply the path to a pip executable when the
224 /// current virtualenv does not provide one.
225 #[arg(long)]
226 pub pip_path: Option<PathBuf>,
227 /// `cargo rustc` options
228 #[command(flatten)]
229 pub cargo_options: CargoOptions,
230 /// Use `uv` to install packages instead of `pip`
231 #[arg(long)]
232 pub uv: bool,
233
234 /// Wheel compression options
235 #[command(flatten)]
236 pub compression: CompressionOptions,
237 }
238
239 #[instrument(skip_all)]
240 fn install_dependencies(
241 build_context: &BuildContext,
242 extras: &[String],
243 python: &Path,
244 venv_dir: &Path,
245 install_backend: &InstallBackend,
246 ) -> Result<()> {
247 if !build_context.metadata24.requires_dist.is_empty() {
248 let mut extra_names = Vec::with_capacity(extras.len());
249 for extra in extras {
250 extra_names.push(
251 pep508_rs::ExtraName::new(extra.clone())
252 .with_context(|| format!("invalid extra name: {extra}"))?,
253 );
254 }
255 let mut args = vec!["install".to_string()];
256 args.extend(build_context.metadata24.requires_dist.iter().map(|x| {
257 let mut pkg = x.clone();
258 // Remove extra marker to make it installable with pip:
259 //
260 // * ` and extra == 'EXTRA_NAME'`
261 // * `; extra == 'EXTRA_NAME'`
262 //
263 // Keep in sync with `Metadata23::merge_pyproject_toml()`
264 pkg.marker = pkg.marker.simplify_extras(&extra_names);
265 pkg.to_string()
266 }));
267 let status = install_backend
268 .make_command(python)
269 .args(&args)
270 .env("VIRTUAL_ENV", venv_dir)
271 .status()
272 .with_context(|| format!("Failed to run {} install", install_backend.name()))?;
273 if !status.success() {
274 bail!(
275 r#"{} install finished with "{}""#,
276 install_backend.name(),
277 status
278 )
279 }
280 }
281 Ok(())
282 }
283
284 #[instrument(skip_all, fields(wheel_filename = %wheel_filename.display()))]
285 fn install_wheel(
286 build_context: &BuildContext,
287 python: &Path,
288 venv_dir: &Path,
289 wheel_filename: &Path,
290 install_backend: &InstallBackend,
291 ) -> Result<()> {
292 let mut cmd = install_backend.make_command(python);
293 let output = cmd
294 .args(["install", "--no-deps", "--force-reinstall"])
295 .arg(dunce::simplified(wheel_filename))
296 .env("VIRTUAL_ENV", venv_dir)
297 .output()
298 .context(format!(
299 "{} install failed (ran {:?} with {:?})",
300 install_backend.name(),
301 cmd.get_program(),
302 &cmd.get_args().collect::<Vec<_>>(),
303 ))?;
304 if !output.status.success() {
305 bail!(
306 "{} install in {} failed running {:?}: {}\n--- Stdout:\n{}\n--- Stderr:\n{}\n---\n",
307 install_backend.name(),
308 venv_dir.display(),
309 &cmd.get_args().collect::<Vec<_>>(),
310 output.status,
311 String::from_utf8_lossy(&output.stdout).trim(),
312 String::from_utf8_lossy(&output.stderr).trim(),
313 );
314 }
315 if !output.stderr.is_empty() && install_backend.stderr_indicates_problem() {
316 eprintln!(
317 "⚠️ Warning: {} raised a warning running {:?}:\n{}",
318 install_backend.name(),
319 &cmd.get_args().collect::<Vec<_>>(),
320 String::from_utf8_lossy(&output.stderr).trim(),
321 );
322 }
323 if let Err(err) = configure_as_editable(build_context, python, install_backend) {
324 eprintln!("⚠️ Warning: failed to set package as editable: {err}");
325 }
326 Ok(())
327 }
328
329 /// Each editable-installed python package has a `direct_url.json` file that includes a `file://` URL
330 /// indicating the location of the source code of that project. The maturin import hook uses this
331 /// URL to locate and rebuild editable-installed projects.
332 ///
333 /// When a maturin package is installed using `pip install -e`, pip takes care of writing the
334 /// correct URL, however when a maturin package is installed with `maturin develop`, the URL is
335 /// set to the path to the temporary wheel file created during installation.
336 #[instrument(skip_all)]
337 fn configure_as_editable(
338 build_context: &BuildContext,
339 python: &Path,
340 install_backend: &InstallBackend,
341 ) -> Result<()> {
342 println!("✏️ Setting installed package as editable");
343 install_backend.check_supports_show_files(python)?;
344 let mut cmd = install_backend.make_command(python);
345 let cmd = cmd.args(["show", "--files", &build_context.metadata24.name]);
346 debug!("running {:?}", cmd);
347 let output = cmd.output()?;
348 ensure!(output.status.success(), "failed to list package files");
349 if let Some(direct_url_path) = parse_direct_url_path(&String::from_utf8_lossy(&output.stdout))?
350 {
351 let project_dir = build_context
352 .pyproject_toml_path
353 .parent()
354 .ok_or_else(|| anyhow!("failed to get project directory"))?;
355 let uri = Url::from_file_path(project_dir)
356 .map_err(|_| anyhow!("failed to convert project directory to file URL"))?;
357 let content = format!("{{\"dir_info\": {{\"editable\": true}}, \"url\": \"{uri}\"}}");
358 fs::write(direct_url_path, content)?;
359 }
360 Ok(())
361 }
362
363 fn parse_direct_url_path(pip_show_output: &str) -> Result<Option<PathBuf>> {
364 if let Some(Some(location)) = Regex::new(r"Location: ([^\r\n]*)")?
365 .captures(pip_show_output)
366 .map(|c| c.get(1))
367 {
368 if let Some(Some(direct_url_path)) = Regex::new(r" (.*direct_url.json)")?
369 .captures(pip_show_output)
370 .map(|c| c.get(1))
371 {
372 return Ok(Some(
373 PathBuf::from(location.as_str()).join(direct_url_path.as_str()),
374 ));
375 }
376 }
377 Ok(None)
378 }
379
380 /// Installs a crate by compiling it and copying the shared library to site-packages.
381 /// Also adds the dist-info directory to make sure pip and other tools detect the library
382 ///
383 /// Works only in a virtualenv.
384 #[allow(clippy::too_many_arguments)]
385 pub fn develop(develop_options: DevelopOptions, venv_dir: &Path) -> Result<()> {
386 let DevelopOptions {
387 bindings,
388 release,
389 strip,
390 extras,
391 skip_install,
392 pip_path,
393 cargo_options,
394 uv,
395 compression,
396 } = develop_options;
397 compression.validate();
398
399 let mut target_triple = cargo_options.target.clone();
400 let target = Target::from_target_triple(cargo_options.target.as_ref())?;
401 let python = target.get_venv_python(venv_dir);
402
403 // check python platform and architecture
404 if !target.user_specified {
405 if let Some(detected_target) = detect_arch_from_python(&python, &target) {
406 target_triple = Some(detected_target);
407 }
408 }
409
410 // Store wheel in a unique location so we don't get name clashes with parallel runs
411 let wheel_dir = TempDir::new().context("Failed to create temporary directory")?;
412
413 let build_options = BuildOptions {
414 platform_tag: vec![PlatformTag::Linux],
415 interpreter: vec![python.clone()],
416 find_interpreter: false,
417 bindings,
418 out: Some(wheel_dir.path().to_path_buf()),
419 auditwheel: Some(AuditWheelMode::Skip),
420 skip_auditwheel: false,
421 #[cfg(feature = "zig")]
422 zig: false,
423 cargo: CargoOptions {
424 target: target_triple,
425 ..cargo_options
426 },
427 compression,
428 };
429
430 let build_context = build_options
431 .into_build_context()
432 .release(release)
433 .strip(strip)
434 .editable(true)
435 .build()?;
436
437 // Ensure that version information is present, https://github.com/PyO3/maturin/issues/2416
438 if build_context
439 .pyproject_toml
440 .as_ref()
441 .is_some_and(|p| !p.warn_invalid_version_info())
442 {
443 bail!("Cannot build without valid version information. \
444 You need to specify either `project.version` or `project.dynamic = [\"version\"]` in pyproject.toml.");
445 }
446
447 let interpreter =
448 PythonInterpreter::check_executable(&python, &target, build_context.bridge())?.ok_or_else(
449 || anyhow!("Expected `python` to be a python interpreter inside a virtualenv ಠ_ಠ"),
450 )?;
451
452 let uv_venv = is_uv_venv(venv_dir);
453 let uv_info = if uv || uv_venv {
454 match find_uv_python(&interpreter.executable).or_else(|_| find_uv_bin()) {
455 Ok(uv_info) => Some(Ok(uv_info)),
456 Err(e) => {
457 if uv {
458 Some(Err(e))
459 } else {
460 // Ignore error and try pip instead if it's a uv venv but `--uv` is not specified
461 None
462 }
463 }
464 }
465 } else {
466 None
467 };
468 let install_backend = if let Some(uv_info) = uv_info {
469 let (uv_path, uv_args) = uv_info?;
470 InstallBackend::Uv {
471 path: uv_path,
472 args: uv_args,
473 }
474 } else {
475 check_pip_exists(&interpreter.executable, pip_path.as_ref())
476 .context("Failed to find pip (if working with a uv venv try `maturin develop --uv`)")?;
477 InstallBackend::Pip {
478 path: pip_path.clone(),
479 }
480 };
481
482 if !skip_install {
483 install_dependencies(&build_context, &extras, &python, venv_dir, &install_backend)?;
484 }
485
486 let wheels = build_context.build_wheels()?;
487 if !skip_install {
488 for (filename, _supported_version) in wheels.iter() {
489 install_wheel(
490 &build_context,
491 &python,
492 venv_dir,
493 filename,
494 &install_backend,
495 )?;
496 eprintln!(
497 "🛠 Installed {}-{}",
498 build_context.metadata24.name, build_context.metadata24.version
499 );
500 }
501 }
502
503 Ok(())
504 }
505
506 #[cfg(test)]
507 mod test {
508 use std::path::PathBuf;
509
510 use super::parse_direct_url_path;
511
512 #[test]
513 #[cfg(not(target_os = "windows"))]
514 fn test_parse_direct_url() {
515 let example_with_direct_url = "\
516 Name: my-project
517 Version: 0.1.0
518 Location: /foo bar/venv/lib/pythonABC/site-packages
519 Editable project location: /tmp/temporary.whl
520 Files:
521 my_project-0.1.0+abc123de.dist-info/INSTALLER
522 my_project-0.1.0+abc123de.dist-info/METADATA
523 my_project-0.1.0+abc123de.dist-info/RECORD
524 my_project-0.1.0+abc123de.dist-info/REQUESTED
525 my_project-0.1.0+abc123de.dist-info/WHEEL
526 my_project-0.1.0+abc123de.dist-info/direct_url.json
527 my_project-0.1.0+abc123de.dist-info/entry_points.txt
528 my_project.pth
529 ";
530 let expected_path = PathBuf::from("/foo bar/venv/lib/pythonABC/site-packages/my_project-0.1.0+abc123de.dist-info/direct_url.json");
531 assert_eq!(
532 parse_direct_url_path(example_with_direct_url).unwrap(),
533 Some(expected_path)
534 );
535
536 let example_without_direct_url = "\
537 Name: my-project
538 Version: 0.1.0
539 Location: /foo bar/venv/lib/pythonABC/site-packages
540 Files:
541 my_project-0.1.0+abc123de.dist-info/INSTALLER
542 my_project-0.1.0+abc123de.dist-info/METADATA
543 my_project-0.1.0+abc123de.dist-info/RECORD
544 my_project-0.1.0+abc123de.dist-info/REQUESTED
545 my_project-0.1.0+abc123de.dist-info/WHEEL
546 my_project-0.1.0+abc123de.dist-info/entry_points.txt
547 my_project.pth
548 ";
549
550 assert_eq!(
551 parse_direct_url_path(example_without_direct_url).unwrap(),
552 None
553 );
554 }
555
556 #[test]
557 #[cfg(target_os = "windows")]
558 fn test_parse_direct_url_windows() {
559 let example_with_direct_url_windows = "\
560 Name: my-project\r
561 Version: 0.1.0\r
562 Location: C:\\foo bar\\venv\\Lib\\site-packages\r
563 Files:\r
564 my_project-0.1.0+abc123de.dist-info\\INSTALLER\r
565 my_project-0.1.0+abc123de.dist-info\\METADATA\r
566 my_project-0.1.0+abc123de.dist-info\\RECORD\r
567 my_project-0.1.0+abc123de.dist-info\\REQUESTED\r
568 my_project-0.1.0+abc123de.dist-info\\WHEEL\r
569 my_project-0.1.0+abc123de.dist-info\\direct_url.json\r
570 my_project-0.1.0+abc123de.dist-info\\entry_points.txt\r
571 my_project.pth\r
572 ";
573
574 let expected_path = PathBuf::from("C:\\foo bar\\venv\\Lib\\site-packages\\my_project-0.1.0+abc123de.dist-info\\direct_url.json");
575 assert_eq!(
576 parse_direct_url_path(example_with_direct_url_windows).unwrap(),
577 Some(expected_path)
578 );
579 }
580 }