Debian Codegraph @

src/main.rs

raw
1 //! Build and publish crates with pyo3, cffi and uniffi bindings as well as rust binaries
2 //! as python packages. This file contains the CLI and keyring integration.
3 //!
4 //! Run with --help for usage information
5
6 use anyhow::{bail, Context, Result};
7 use cargo_options::heading;
8 #[cfg(feature = "zig")]
9 use cargo_zigbuild::Zig;
10 #[cfg(feature = "cli-completion")]
11 use clap::CommandFactory;
12 use clap::{Parser, Subcommand};
13 #[cfg(feature = "scaffolding")]
14 use maturin::{ci::GenerateCI, init_project, new_project, GenerateProjectOptions};
15 use maturin::{
16 develop, find_path_deps, write_dist_info, BridgeModel, BuildOptions, CargoOptions,
17 DevelopOptions, PathWriter, PythonInterpreter, Target, TargetTriple,
18 };
19 #[cfg(feature = "schemars")]
20 use maturin::{generate_json_schema, GenerateJsonSchemaOptions};
21 #[cfg(feature = "upload")]
22 use maturin::{upload_ui, PublishOpt};
23 use std::env;
24 use std::path::PathBuf;
25 use std::str::FromStr;
26 use tracing::{debug, instrument};
27 use tracing_subscriber::filter::Directive;
28 use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};
29
30 #[derive(Debug, Parser)]
31 #[command(
32 version,
33 name = env!("CARGO_PKG_NAME"),
34 display_order = 1,
35 after_help = "Visit https://maturin.rs to learn more about maturin.",
36 styles = cargo_options::styles(),
37 )]
38 /// Build and publish crates with pyo3, cffi and uniffi bindings as well
39 /// as rust binaries as python packages
40 struct Opt {
41 /// Use verbose output.
42 ///
43 /// * Default: Show build information and `cargo build` output.
44 /// * `-v`: Use `cargo build -v`.
45 /// * `-vv`: Show debug logging and use `cargo build -vv`.
46 /// * `-vvv`: Show trace logging.
47 ///
48 /// You can configure fine-grained logging using the `RUST_LOG` environment variable.
49 /// (<https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives>)
50 #[arg(global = true, action = clap::ArgAction::Count, long, short)]
51 verbose: u8,
52 #[command(subcommand)]
53 command: Command,
54 }
55
56 #[derive(Debug, Parser)]
57 #[allow(clippy::large_enum_variant)]
58 /// Build and publish crates with pyo3, cffi and uniffi bindings as well
59 /// as rust binaries as python packages
60 enum Command {
61 #[command(name = "build", alias = "b")]
62 /// Build the crate into python packages
63 Build {
64 /// Build artifacts in release mode, with optimizations
65 #[arg(short = 'r', long, help_heading = heading::COMPILATION_OPTIONS)]
66 release: bool,
67 /// Strip the library for minimum file size
68 #[arg(long)]
69 strip: bool,
70 /// Build a source distribution
71 #[arg(long)]
72 sdist: bool,
73 #[command(flatten)]
74 build: BuildOptions,
75 },
76 #[cfg(feature = "upload")]
77 #[command(name = "publish")]
78 /// Build and publish the crate as python packages to pypi
79 Publish {
80 /// Do not pass --release to cargo
81 #[arg(long)]
82 debug: bool,
83 /// Do not strip the library for minimum file size
84 #[arg(long = "no-strip")]
85 no_strip: bool,
86 /// Don't build a source distribution
87 #[arg(long = "no-sdist")]
88 no_sdist: bool,
89 #[command(flatten)]
90 publish: PublishOpt,
91 #[command(flatten)]
92 build: BuildOptions,
93 },
94 #[command(name = "list-python")]
95 /// Search and list the available python installations
96 ListPython {
97 #[arg(long)]
98 target: Option<TargetTriple>,
99 },
100 #[command(name = "develop", alias = "dev")]
101 /// Install the crate as module in the current virtualenv
102 Develop(DevelopOptions),
103 /// Build only a source distribution (sdist) without compiling.
104 ///
105 /// Building a source distribution requires a pyproject.toml with a `[build-system]` table.
106 ///
107 /// This command is a workaround for [pypa/pip#6041](https://github.com/pypa/pip/issues/6041)
108 #[command(name = "sdist")]
109 SDist {
110 #[arg(short = 'm', long = "manifest-path")]
111 /// The path to the Cargo.toml
112 manifest_path: Option<PathBuf>,
113 /// The directory to store the built wheels in. Defaults to a new "wheels"
114 /// directory in the project's target directory
115 #[arg(short, long)]
116 out: Option<PathBuf>,
117 },
118 /// Create a new cargo project in an existing directory
119 #[cfg(feature = "scaffolding")]
120 #[command(name = "init")]
121 InitProject {
122 /// Project path
123 path: Option<String>,
124 #[command(flatten)]
125 options: GenerateProjectOptions,
126 },
127 /// Create a new cargo project
128 #[cfg(feature = "scaffolding")]
129 #[command(name = "new")]
130 NewProject {
131 /// Project path
132 path: String,
133 #[command(flatten)]
134 options: GenerateProjectOptions,
135 },
136 #[cfg(feature = "scaffolding")]
137 #[command(name = "generate-ci")]
138 GenerateCI(GenerateCI),
139 /// Upload python packages to pypi
140 ///
141 /// It is mostly similar to `twine upload`, but can only upload python wheels
142 /// and source distributions.
143 #[cfg(feature = "upload")]
144 #[command(name = "upload")]
145 Upload {
146 #[command(flatten)]
147 publish: PublishOpt,
148 /// The python packages to upload
149 #[arg(value_name = "FILE")]
150 files: Vec<PathBuf>,
151 },
152 /// Backend for the PEP 517 integration. Not for human consumption
153 ///
154 /// The commands are meant to be called from the python PEP 517
155 #[command(subcommand)]
156 Pep517(Pep517Command),
157 /// Generate shell completions
158 #[cfg(feature = "cli-completion")]
159 #[command(name = "completions", hide = true)]
160 Completions {
161 #[arg(value_name = "SHELL")]
162 shell: clap_complete_command::Shell,
163 },
164 /// Zig linker wrapper
165 #[cfg(feature = "zig")]
166 #[command(subcommand, hide = true)]
167 Zig(Zig),
168 /// Generate the JSON schema for the `pyproject.toml` file.
169 #[cfg(feature = "schemars")]
170 #[command(name = "generate-json-schema", hide = true)]
171 GenerateJsonSchema(GenerateJsonSchemaOptions),
172 }
173
174 /// Backend for the PEP 517 integration. Not for human consumption
175 ///
176 /// The commands are meant to be called from the python PEP 517
177 #[derive(Debug, Subcommand)]
178 #[command(name = "pep517", hide = true)]
179 enum Pep517Command {
180 /// The implementation of prepare_metadata_for_build_wheel
181 #[command(name = "write-dist-info")]
182 WriteDistInfo {
183 #[command(flatten)]
184 build_options: BuildOptions,
185 /// The metadata_directory argument to prepare_metadata_for_build_wheel
186 #[arg(long = "metadata-directory")]
187 metadata_directory: PathBuf,
188 /// Strip the library for minimum file size
189 #[arg(long)]
190 strip: bool,
191 },
192 #[command(name = "build-wheel")]
193 /// Implementation of build_wheel
194 ///
195 /// --release and --strip are currently unused by the PEP 517 implementation
196 BuildWheel {
197 #[command(flatten)]
198 build_options: BuildOptions,
199 /// Strip the library for minimum file size
200 #[arg(long)]
201 strip: bool,
202 /// Build editable wheels
203 #[arg(long)]
204 editable: bool,
205 },
206 /// The implementation of build_sdist
207 #[command(name = "write-sdist")]
208 WriteSDist {
209 /// The sdist_directory argument to build_sdist
210 #[arg(long = "sdist-directory")]
211 sdist_directory: PathBuf,
212 #[arg(short = 'm', long = "manifest-path", value_name = "PATH")]
213 /// The path to the Cargo.toml
214 manifest_path: Option<PathBuf>,
215 },
216 }
217
218 fn detect_venv(target: &Target) -> Result<PathBuf> {
219 match (env::var_os("VIRTUAL_ENV"), env::var_os("CONDA_PREFIX")) {
220 (Some(dir), None) => return Ok(PathBuf::from(dir)),
221 (None, Some(dir)) => return Ok(PathBuf::from(dir)),
222 (Some(venv), Some(conda)) if venv == conda => return Ok(PathBuf::from(venv)),
223 (Some(_), Some(_)) => {
224 bail!("Both VIRTUAL_ENV and CONDA_PREFIX are set. Please unset one of them")
225 }
226 (None, None) => {
227 // No env var, try finding .venv
228 }
229 };
230
231 let current_dir = env::current_dir().context("Failed to detect current directory ಠ_ಠ")?;
232 // .venv in the current or any parent directory
233 for dir in current_dir.ancestors() {
234 let dot_venv = dir.join(".venv");
235 if dot_venv.is_dir() {
236 if !dot_venv.join("pyvenv.cfg").is_file() {
237 bail!(
238 "Expected {} to be a virtual environment, but pyvenv.cfg is missing",
239 dot_venv.display()
240 );
241 }
242 let python = target.get_venv_python(&dot_venv);
243 if !python.is_file() {
244 bail!(
245 "Your virtualenv at {} is broken. It contains a pyvenv.cfg but no python at {}",
246 dot_venv.display(),
247 python.display()
248 );
249 }
250 debug!("Found a virtualenv named .venv at {}", dot_venv.display());
251 return Ok(dot_venv);
252 }
253 }
254
255 bail!(
256 "Couldn't find a virtualenv or conda environment, but you need one to use this command. \
257 For maturin to find your virtualenv you need to either set VIRTUAL_ENV (through activate), \
258 set CONDA_PREFIX (through conda activate) or have a virtualenv called .venv in the current \
259 or any parent folder. \
260 See https://virtualenv.pypa.io/en/latest/index.html on how to use virtualenv or \
261 use `maturin build` and `pip install <path/to/wheel>` instead."
262 )
263 }
264
265 /// Dispatches into the native implementations of the PEP 517 functions
266 ///
267 /// The last line of stdout is used as return value from the python part of the implementation
268 fn pep517(subcommand: Pep517Command) -> Result<()> {
269 match subcommand {
270 Pep517Command::WriteDistInfo {
271 build_options,
272 metadata_directory,
273 strip,
274 } => {
275 assert_eq!(build_options.interpreter.len(), 1);
276 let context = build_options
277 .into_build_context()
278 .release(true)
279 .strip(strip)
280 .editable(false)
281 .build()?;
282
283 let mut writer = PathWriter::from_path(metadata_directory);
284 write_dist_info(
285 &mut writer,
286 &context.project_layout.project_root,
287 &context.metadata24,
288 &context.tags_from_bridge()?,
289 )?;
290 println!("{}", context.metadata24.get_dist_info_dir().display());
291 }
292 Pep517Command::BuildWheel {
293 build_options,
294 strip,
295 editable,
296 } => {
297 let build_context = build_options
298 .into_build_context()
299 .release(true)
300 .strip(strip)
301 .editable(editable)
302 .build()?;
303 let wheels = build_context.build_wheels()?;
304 assert_eq!(wheels.len(), 1);
305 println!("{}", wheels[0].0.to_str().unwrap());
306 }
307 Pep517Command::WriteSDist {
308 sdist_directory,
309 manifest_path,
310 } => {
311 let build_options = BuildOptions {
312 out: Some(sdist_directory),
313 cargo: CargoOptions {
314 manifest_path,
315 // Enable all features to ensure all optional path dependencies are packaged
316 // into source distribution
317 all_features: true,
318 ..Default::default()
319 },
320 ..Default::default()
321 };
322 let build_context = build_options
323 .into_build_context()
324 .release(false)
325 .strip(false)
326 .editable(false)
327 .sdist_only(true)
328 .build()?;
329 let (path, _) = build_context
330 .build_source_distribution()?
331 .context("Failed to build source distribution, pyproject.toml not found")?;
332 println!("{}", path.file_name().unwrap().to_str().unwrap());
333 }
334 };
335
336 Ok(())
337 }
338
339 #[instrument]
340 fn run() -> Result<()> {
341 #[cfg(feature = "zig")]
342 {
343 // Allow symlink `maturin` to `ar` to invoke `zig ar`
344 // See https://github.com/messense/cargo-zigbuild/issues/52
345 let mut args = env::args();
346 let program_path = PathBuf::from(args.next().expect("no program path"));
347 let program_name = program_path.file_stem().expect("no program name");
348 if program_name.eq_ignore_ascii_case("ar") {
349 let zig = Zig::Ar {
350 args: args.collect(),
351 };
352 zig.execute()?;
353 return Ok(());
354 }
355 }
356
357 #[cfg(not(feature = "wild"))]
358 let opt = Opt::parse();
359 #[cfg(feature = "wild")]
360 let opt = Opt::parse_from(wild::args_os());
361
362 setup_logging(opt.verbose)?;
363
364 match opt.command {
365 Command::Build {
366 build,
367 release,
368 strip,
369 sdist,
370 } => {
371 let build_context = build
372 .into_build_context()
373 .release(release)
374 .strip(strip)
375 .editable(false)
376 .build()?;
377 if sdist {
378 build_context
379 .build_source_distribution()?
380 .context("Failed to build source distribution, pyproject.toml not found")?;
381 }
382 let wheels = build_context.build_wheels()?;
383 assert!(!wheels.is_empty());
384 }
385 #[cfg(feature = "upload")]
386 Command::Publish {
387 build,
388 mut publish,
389 debug,
390 no_strip,
391 no_sdist,
392 } => {
393 let build_context = build
394 .into_build_context()
395 .release(!debug)
396 .strip(!no_strip)
397 .editable(false)
398 .build()?;
399
400 if !build_context.release {
401 eprintln!("⚠️ Warning: You're publishing debug wheels");
402 }
403
404 let mut wheels = build_context.build_wheels()?;
405 if !no_sdist {
406 if let Some(sd) = build_context.build_source_distribution()? {
407 wheels.push(sd);
408 }
409 }
410
411 let items = wheels.into_iter().map(|wheel| wheel.0).collect::<Vec<_>>();
412 publish.non_interactive_on_ci();
413
414 upload_ui(&items, &publish)?
415 }
416 Command::ListPython { target } => {
417 let found = if target.is_some() {
418 let target = Target::from_target_triple(target.as_ref())?;
419 PythonInterpreter::find_by_target(&target, None, None)
420 } else {
421 let target = Target::from_target_triple(None)?;
422 // We don't know the targeted bindings yet, so we use the most lenient
423 PythonInterpreter::find_all(&target, &BridgeModel::Cffi, None)?
424 };
425 eprintln!("🐍 {} python interpreter found:", found.len());
426 for interpreter in found {
427 eprintln!(" - {interpreter}");
428 }
429 }
430 Command::Develop(develop_options) => {
431 let target = Target::from_target_triple(develop_options.cargo_options.target.as_ref())?;
432 let venv_dir = detect_venv(&target)?;
433 develop(develop_options, &venv_dir)?;
434 }
435 Command::SDist { manifest_path, out } => {
436 // Get cargo metadata to check for path dependencies
437 let cargo_metadata_result = cargo_metadata::MetadataCommand::new()
438 .cargo_path("cargo")
439 .manifest_path(
440 manifest_path
441 .as_deref()
442 .unwrap_or_else(|| std::path::Path::new("Cargo.toml")),
443 )
444 .verbose(true)
445 .exec();
446
447 let has_path_deps = cargo_metadata_result
448 .ok()
449 .and_then(|metadata| find_path_deps(&metadata).ok())
450 .map(|path_deps| !path_deps.is_empty())
451 .unwrap_or(false); // If we can't get metadata, don't force all features
452 let build_options = BuildOptions {
453 out,
454 cargo: CargoOptions {
455 manifest_path,
456 // Only enable all features when we have local path dependencies
457 // to ensure they are packaged into source distribution
458 all_features: has_path_deps,
459 ..Default::default()
460 },
461 ..Default::default()
462 };
463 let build_context = build_options
464 .into_build_context()
465 .release(false)
466 .strip(false)
467 .editable(false)
468 .sdist_only(true)
469 .build()?;
470 build_context
471 .build_source_distribution()?
472 .context("Failed to build source distribution, pyproject.toml not found")?;
473 }
474 Command::Pep517(subcommand) => pep517(subcommand)?,
475 #[cfg(feature = "scaffolding")]
476 Command::InitProject { path, options } => init_project(path, options)?,
477 #[cfg(feature = "scaffolding")]
478 Command::NewProject { path, options } => new_project(path, options)?,
479 #[cfg(feature = "scaffolding")]
480 Command::GenerateCI(generate_ci) => generate_ci.execute()?,
481 #[cfg(feature = "upload")]
482 Command::Upload { mut publish, files } => {
483 if files.is_empty() {
484 eprintln!("⚠️ Warning: No files given, exiting.");
485 return Ok(());
486 }
487 publish.non_interactive_on_ci();
488
489 upload_ui(&files, &publish)?
490 }
491 #[cfg(feature = "cli-completion")]
492 Command::Completions { shell } => {
493 shell.generate(&mut Opt::command(), &mut std::io::stdout());
494 }
495 #[cfg(feature = "zig")]
496 Command::Zig(subcommand) => {
497 subcommand
498 .execute()
499 .context("Failed to run zig linker wrapper")?;
500 }
501 #[cfg(feature = "schemars")]
502 Command::GenerateJsonSchema(args) => generate_json_schema(args)?,
503 }
504
505 Ok(())
506 }
507
508 #[cfg(not(debug_assertions))]
509 fn setup_panic_hook() {
510 let default_hook = std::panic::take_hook();
511 std::panic::set_hook(Box::new(move |panic_info| {
512 eprintln!("\n===================================================================");
513 eprintln!("maturin has panicked. This is a bug in maturin. Please report this");
514 eprintln!("at https://github.com/PyO3/maturin/issues/new/choose.");
515 eprintln!("If you can reliably reproduce this panic, include the");
516 eprintln!("reproduction steps and re-run with the RUST_BACKTRACE=1 environment");
517 eprintln!("variable set and include the backtrace in your report.");
518 eprintln!();
519 eprintln!("Platform: {} {}", env::consts::OS, env::consts::ARCH);
520 eprintln!("Version: {}", env!("CARGO_PKG_VERSION"));
521 eprintln!("Args: {}", env::args().collect::<Vec<_>>().join(" "));
522 eprintln!();
523 default_hook(panic_info);
524 // Rust set exit code to 101 when the process panicked,
525 // so here we use the same exit code
526 std::process::exit(101);
527 }));
528 }
529
530 fn setup_logging(verbose: u8) -> Result<()> {
531 // `RUST_LOG` takes precedence over these
532 let default_directive = match verbose {
533 // `-v` runs `cargo build -v`, but doesn't show maturin debug logging yet.
534 0..=1 => tracing::level_filters::LevelFilter::OFF.into(),
535 2 => Directive::from_str("debug").unwrap(),
536 3.. => Directive::from_str("trace").unwrap(),
537 };
538
539 let filter = EnvFilter::builder()
540 .with_default_directive(default_directive)
541 .from_env()
542 .context("Invalid RUST_LOG directives")?;
543
544 let logger = tracing_subscriber::fmt::layer()
545 // Avoid showing all the details from the spans
546 .compact()
547 // Log the timing of each span
548 .with_span_events(tracing_subscriber::fmt::format::FmtSpan::CLOSE);
549
550 tracing_subscriber::registry()
551 .with(logger.with_filter(filter))
552 .init();
553
554 Ok(())
555 }
556
557 fn main() {
558 #[cfg(not(debug_assertions))]
559 setup_panic_hook();
560
561 if let Err(e) = run() {
562 eprintln!("💥 maturin failed");
563 for cause in e.chain() {
564 eprintln!(" Caused by: {cause}");
565 }
566 std::process::exit(1);
567 }
568 }