Skip to main content

rypip/
lib.rs

1//! rypip: a pip-like tool for the rython toolchain.
2//!
3//! rypip builds Python packages as native Rust binaries and installs them
4//! where cargo installs binaries (`cargo install`'s root, normally
5//! `~/.cargo/bin`), and converts Python packages into Rust crates —
6//! optionally with PyO3 bindings so the converted crate can still be
7//! imported from Python.
8
9pub mod convert;
10pub mod package;
11
12use std::path::Path;
13use std::process::Command;
14
15use anyhow::{bail, Context, Result};
16
17pub use convert::{convert, ConvertOptions, ConvertedCrate};
18pub use package::{discover, PyPackage};
19
20/// Run `cargo build --release` on a converted crate.
21pub fn cargo_build(krate: &ConvertedCrate) -> Result<()> {
22    run_cargo(
23        Command::new("cargo")
24            .arg("build")
25            .arg("--release")
26            .current_dir(&krate.root),
27        "cargo build",
28    )
29}
30
31/// Install a converted crate's binary the same way `cargo install` would
32/// (into `$CARGO_INSTALL_ROOT`/`~/.cargo/bin` unless `root` overrides it).
33pub fn cargo_install(krate: &ConvertedCrate, root: Option<&Path>) -> Result<()> {
34    if !krate.has_binary {
35        bail!(
36            "package `{}` has no entry point; add an `if __name__ == \"__main__\":` block \
37             or a __main__.py to install it as a binary (use `convert` for library crates)",
38            krate.name
39        );
40    }
41    let mut cmd = Command::new("cargo");
42    cmd.arg("install")
43        .arg("--path")
44        .arg(&krate.root)
45        .arg("--force");
46    if let Some(root) = root {
47        cmd.arg("--root").arg(root);
48    }
49    run_cargo(&mut cmd, "cargo install")
50}
51
52fn run_cargo(cmd: &mut Command, what: &str) -> Result<()> {
53    let status = cmd
54        .status()
55        .with_context(|| format!("running {}", what))?;
56    if !status.success() {
57        bail!("{} failed with {}", what, status);
58    }
59    Ok(())
60}