| 1 |
use crate::module_writer::ModuleWriter; |
| 2 |
use crate::pyproject_toml::SdistGenerator; |
| 3 |
use crate::{pyproject_toml::Format, BuildContext, PyProjectToml, SDistWriter}; |
| 4 |
use anyhow::{bail, Context, Result}; |
| 5 |
use cargo_metadata::camino::Utf8Path; |
| 6 |
use cargo_metadata::{Metadata, MetadataCommand, PackageId}; |
| 7 |
use fs_err as fs; |
| 8 |
use ignore::overrides::Override; |
| 9 |
use normpath::PathExt as _; |
| 10 |
use path_slash::PathExt as _; |
| 11 |
use pyproject_toml::check_pep639_glob; |
| 12 |
use std::collections::{HashMap, HashSet}; |
| 13 |
use std::ffi::OsStr; |
| 14 |
use std::io::Write; |
| 15 |
use std::path::{Path, PathBuf}; |
| 16 |
use std::process::Command; |
| 17 |
use std::str; |
| 18 |
use toml_edit::DocumentMut; |
| 19 |
use tracing::{debug, trace}; |
| 20 |
|
| 21 |
/// Path dependency information. |
| 22 |
/// It may be in a different workspace than the root crate. |
| 23 |
/// |
| 24 |
/// ```toml |
| 25 |
/// [dependencies] |
| 26 |
/// foo = { path = "path/to/foo" } |
| 27 |
/// ``` |
| 28 |
#[derive(Debug, Clone)] |
| 29 |
pub struct PathDependency { |
| 30 |
/// `Cargo.toml` path of the path dependency |
| 31 |
manifest_path: PathBuf, |
| 32 |
/// workspace root of the path dependency |
| 33 |
workspace_root: PathBuf, |
| 34 |
/// readme path of the path dependency |
| 35 |
readme: Option<PathBuf>, |
| 36 |
} |
| 37 |
|
| 38 |
fn parse_toml_file(path: &Path, kind: &str) -> Result<toml_edit::DocumentMut> { |
| 39 |
let text = fs::read_to_string(path)?; |
| 40 |
let document = text.parse::<toml_edit::DocumentMut>().context(format!( |
| 41 |
"Failed to parse {} at {}", |
| 42 |
kind, |
| 43 |
path.display() |
| 44 |
))?; |
| 45 |
Ok(document) |
| 46 |
} |
| 47 |
|
| 48 |
/// Rewrite Cargo.toml to only retain path dependencies that are actually used |
| 49 |
/// |
| 50 |
/// We only want to add path dependencies that are actually used |
| 51 |
/// to reduce the size of the source distribution. |
| 52 |
fn rewrite_cargo_toml( |
| 53 |
document: &mut DocumentMut, |
| 54 |
manifest_path: &Path, |
| 55 |
known_path_deps: &HashMap<String, PathDependency>, |
| 56 |
) -> Result<()> { |
| 57 |
debug!( |
| 58 |
"Rewriting Cargo.toml `workspace.members` at {}", |
| 59 |
manifest_path.display() |
| 60 |
); |
| 61 |
// Update workspace members |
| 62 |
if let Some(workspace) = document.get_mut("workspace").and_then(|x| x.as_table_mut()) { |
| 63 |
if let Some(members) = workspace.get_mut("members").and_then(|x| x.as_array()) { |
| 64 |
if known_path_deps.is_empty() { |
| 65 |
// Remove workspace members when there isn't any path dep |
| 66 |
workspace.remove("members"); |
| 67 |
if workspace.is_empty() { |
| 68 |
// Remove workspace all together if it's empty |
| 69 |
document.remove("workspace"); |
| 70 |
} |
| 71 |
} else { |
| 72 |
let mut new_members = toml_edit::Array::new(); |
| 73 |
for member in members { |
| 74 |
if let toml_edit::Value::String(ref s) = member { |
| 75 |
let member_path = s.value(); |
| 76 |
// See https://github.com/rust-lang/cargo/blob/0de91c89e6479016d0ed8719fdc2947044335b36/src/cargo/util/restricted_names.rs#L119-L122 |
| 77 |
let is_glob_pattern = member_path.contains(['*', '?', '[', ']']); |
| 78 |
if is_glob_pattern { |
| 79 |
let pattern = glob::Pattern::new(member_path).with_context(|| { |
| 80 |
format!( |
| 81 |
"Invalid `workspace.members` glob pattern: {} in {}", |
| 82 |
member_path, |
| 83 |
manifest_path.display() |
| 84 |
) |
| 85 |
})?; |
| 86 |
if known_path_deps.values().any(|path_dep| { |
| 87 |
let relative_path = path_dep |
| 88 |
.manifest_path |
| 89 |
.strip_prefix(&path_dep.workspace_root) |
| 90 |
.unwrap(); |
| 91 |
let relative_path_str = relative_path.to_str().unwrap(); |
| 92 |
pattern.matches(relative_path_str) |
| 93 |
}) { |
| 94 |
new_members.push(member_path); |
| 95 |
} |
| 96 |
} else if known_path_deps.contains_key(member_path) { |
| 97 |
new_members.push(member_path); |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
if !new_members.is_empty() { |
| 102 |
workspace["members"] = toml_edit::value(new_members); |
| 103 |
} else { |
| 104 |
workspace.remove("members"); |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
} |
| 109 |
Ok(()) |
| 110 |
} |
| 111 |
|
| 112 |
/// Rewrite `Cargo.toml` to find the readme in the same directory. |
| 113 |
/// |
| 114 |
/// `package.readme` may point to any point above the package, so when we move the directory, but |
| 115 |
/// keep the readme position, we could get different readme files at the same archive location. |
| 116 |
/// Putting the readme in the same directory as the `Cargo.toml` prevents this. |
| 117 |
fn rewrite_cargo_toml_readme( |
| 118 |
document: &mut DocumentMut, |
| 119 |
manifest_path: &Path, |
| 120 |
readme_name: Option<&str>, |
| 121 |
) -> Result<()> { |
| 122 |
debug!( |
| 123 |
"Rewriting Cargo.toml `package.readme` at {}", |
| 124 |
manifest_path.display() |
| 125 |
); |
| 126 |
|
| 127 |
if let Some(readme_name) = readme_name { |
| 128 |
let project = document.get_mut("package").with_context(|| { |
| 129 |
format!( |
| 130 |
"Missing `[package]` table in Cargo.toml with readme at {}", |
| 131 |
manifest_path.display() |
| 132 |
) |
| 133 |
})?; |
| 134 |
project["readme"] = toml_edit::value(readme_name); |
| 135 |
} |
| 136 |
Ok(()) |
| 137 |
} |
| 138 |
|
| 139 |
/// When `pyproject.toml` is inside the Cargo workspace root, |
| 140 |
/// we need to update `tool.maturin.manifest-path` in `pyproject.toml`. |
| 141 |
fn rewrite_pyproject_toml( |
| 142 |
pyproject_toml_path: &Path, |
| 143 |
relative_manifest_path: &Path, |
| 144 |
) -> Result<String> { |
| 145 |
let mut data = parse_toml_file(pyproject_toml_path, "pyproject.toml")?; |
| 146 |
let tool = data |
| 147 |
.entry("tool") |
| 148 |
.or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new())) |
| 149 |
.as_table_like_mut() |
| 150 |
.with_context(|| { |
| 151 |
format!( |
| 152 |
"`[tool]` must be a table in {}", |
| 153 |
pyproject_toml_path.display() |
| 154 |
) |
| 155 |
})?; |
| 156 |
let maturin = tool |
| 157 |
.entry("maturin") |
| 158 |
.or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new())) |
| 159 |
.as_table_like_mut() |
| 160 |
.with_context(|| { |
| 161 |
format!( |
| 162 |
"`[tool.maturin]` must be a table in {}", |
| 163 |
pyproject_toml_path.display() |
| 164 |
) |
| 165 |
})?; |
| 166 |
|
| 167 |
maturin.remove("manifest-path"); |
| 168 |
maturin.insert( |
| 169 |
"manifest-path", |
| 170 |
toml_edit::value(relative_manifest_path.to_str().unwrap()), |
| 171 |
); |
| 172 |
|
| 173 |
Ok(data.to_string()) |
| 174 |
} |
| 175 |
|
| 176 |
/// Copies the files of a crate to a source distribution, recursively adding path dependencies |
| 177 |
/// and rewriting path entries in Cargo.toml |
| 178 |
/// |
| 179 |
/// Runs `cargo package --list --allow-dirty` to obtain a list of files to package. |
| 180 |
fn add_crate_to_source_distribution( |
| 181 |
writer: &mut SDistWriter, |
| 182 |
manifest_path: impl AsRef<Path>, |
| 183 |
prefix: impl AsRef<Path>, |
| 184 |
readme: Option<&Path>, |
| 185 |
known_path_deps: &HashMap<String, PathDependency>, |
| 186 |
root_crate: bool, |
| 187 |
skip_cargo_toml: bool, |
| 188 |
) -> Result<()> { |
| 189 |
debug!( |
| 190 |
"Getting cargo package file list for {}", |
| 191 |
manifest_path.as_ref().display() |
| 192 |
); |
| 193 |
let prefix = prefix.as_ref(); |
| 194 |
let manifest_path = manifest_path.as_ref(); |
| 195 |
let args = ["package", "--list", "--allow-dirty", "--manifest-path"]; |
| 196 |
let output = Command::new("cargo") |
| 197 |
.args(args) |
| 198 |
.arg(manifest_path) |
| 199 |
.output() |
| 200 |
.with_context(|| { |
| 201 |
format!( |
| 202 |
"Failed to run `cargo package --list --allow-dirty --manifest-path {}`", |
| 203 |
manifest_path.display() |
| 204 |
) |
| 205 |
})?; |
| 206 |
if !output.status.success() { |
| 207 |
bail!( |
| 208 |
"Failed to query file list from cargo: {}\n--- Manifest path: {}\n--- Stdout:\n{}\n--- Stderr:\n{}", |
| 209 |
output.status, |
| 210 |
manifest_path.display(), |
| 211 |
String::from_utf8_lossy(&output.stdout), |
| 212 |
String::from_utf8_lossy(&output.stderr), |
| 213 |
); |
| 214 |
} |
| 215 |
if !output.stderr.is_empty() { |
| 216 |
eprintln!( |
| 217 |
"From `cargo {} {}`:", |
| 218 |
args.join(" "), |
| 219 |
manifest_path.display() |
| 220 |
); |
| 221 |
std::io::stderr().write_all(&output.stderr)?; |
| 222 |
} |
| 223 |
|
| 224 |
let file_list: Vec<&str> = str::from_utf8(&output.stdout) |
| 225 |
.context("Cargo printed invalid utf-8 ಠ_ಠ")? |
| 226 |
.lines() |
| 227 |
.collect(); |
| 228 |
|
| 229 |
trace!("File list: {}", file_list.join(", ")); |
| 230 |
|
| 231 |
// manifest_dir should be a relative path |
| 232 |
let manifest_dir = manifest_path.parent().unwrap(); |
| 233 |
let target_source: Vec<_> = file_list |
| 234 |
.into_iter() |
| 235 |
.map(|relative_to_manifests| { |
| 236 |
let relative_to_cwd = manifest_dir.join(relative_to_manifests); |
| 237 |
(relative_to_manifests, relative_to_cwd) |
| 238 |
}) |
| 239 |
.filter(|(target, source)| { |
| 240 |
#[allow(clippy::if_same_then_else)] |
| 241 |
if *target == "Cargo.toml.orig" { |
| 242 |
// Skip generated files. See https://github.com/rust-lang/cargo/issues/7938#issuecomment-593280660 |
| 243 |
// and https://github.com/PyO3/maturin/issues/449 |
| 244 |
false |
| 245 |
} else if *target == "Cargo.toml" { |
| 246 |
// We rewrite Cargo.toml and add it separately |
| 247 |
false |
| 248 |
} else if root_crate && *target == "pyproject.toml" { |
| 249 |
// pyproject.toml is handled separately because it has to be put in the root dir |
| 250 |
// of source distribution |
| 251 |
false |
| 252 |
} else if prefix.components().count() == 1 && *target == "pyproject.toml" { |
| 253 |
// Skip pyproject.toml for cases when the root is in a workspace member and both the |
| 254 |
// member and the root have a pyproject.toml. |
| 255 |
debug!("Skipping potentially non-main {}", prefix.join(target).display()); |
| 256 |
false |
| 257 |
} else if matches!(Path::new(target).extension(), Some(ext) if ext == "pyc" || ext == "pyd" || ext == "so") { |
| 258 |
// Technically, `cargo package --list` should handle this, |
| 259 |
// but somehow it doesn't on Alpine Linux running in GitHub Actions, |
| 260 |
// so we do it manually here. |
| 261 |
// See https://github.com/PyO3/maturin/pull/1255#issuecomment-1308838786 |
| 262 |
debug!("Ignoring {}", target); |
| 263 |
false |
| 264 |
} else { |
| 265 |
source.exists() |
| 266 |
} |
| 267 |
}) |
| 268 |
.collect(); |
| 269 |
|
| 270 |
writer.add_directory(prefix)?; |
| 271 |
|
| 272 |
let cargo_toml_path = prefix.join(manifest_path.file_name().unwrap()); |
| 273 |
|
| 274 |
let readme_name = readme |
| 275 |
.as_ref() |
| 276 |
.map(|readme| { |
| 277 |
readme |
| 278 |
.file_name() |
| 279 |
.and_then(OsStr::to_str) |
| 280 |
.with_context(|| format!("Missing readme filename for {}", manifest_path.display())) |
| 281 |
}) |
| 282 |
.transpose()?; |
| 283 |
|
| 284 |
if root_crate { |
| 285 |
let mut document = parse_toml_file(manifest_path, "Cargo.toml")?; |
| 286 |
rewrite_cargo_toml_readme(&mut document, manifest_path, readme_name)?; |
| 287 |
rewrite_cargo_toml(&mut document, manifest_path, known_path_deps)?; |
| 288 |
writer.add_bytes( |
| 289 |
cargo_toml_path, |
| 290 |
Some(manifest_path), |
| 291 |
document.to_string().as_bytes(), |
| 292 |
)?; |
| 293 |
} else if !skip_cargo_toml { |
| 294 |
let mut document = parse_toml_file(manifest_path, "Cargo.toml")?; |
| 295 |
rewrite_cargo_toml_readme(&mut document, manifest_path, readme_name)?; |
| 296 |
writer.add_bytes( |
| 297 |
cargo_toml_path, |
| 298 |
Some(manifest_path), |
| 299 |
document.to_string().as_bytes(), |
| 300 |
)?; |
| 301 |
} |
| 302 |
|
| 303 |
for (target, source) in target_source { |
| 304 |
writer.add_file(prefix.join(target), source)?; |
| 305 |
} |
| 306 |
|
| 307 |
Ok(()) |
| 308 |
} |
| 309 |
|
| 310 |
/// Finds all path dependencies of the crate |
| 311 |
pub fn find_path_deps(cargo_metadata: &Metadata) -> Result<HashMap<String, PathDependency>> { |
| 312 |
let root = cargo_metadata |
| 313 |
.root_package() |
| 314 |
.context("Expected the dependency graph to have a root package")?; |
| 315 |
let pkg_readmes = cargo_metadata |
| 316 |
.packages |
| 317 |
.iter() |
| 318 |
.filter_map(|package| { |
| 319 |
package |
| 320 |
.readme |
| 321 |
.as_ref() |
| 322 |
.map(|readme| (package.id.clone(), readme.clone().into_std_path_buf())) |
| 323 |
}) |
| 324 |
.collect::<HashMap<PackageId, PathBuf>>(); |
| 325 |
// scan the dependency graph for path dependencies |
| 326 |
let mut path_deps = HashMap::new(); |
| 327 |
let mut stack: Vec<&cargo_metadata::Package> = vec![root]; |
| 328 |
while let Some(top) = stack.pop() { |
| 329 |
// There seems to be no API to get the package id of a dependency, so collect the package ids from resolve |
| 330 |
// and match them up with the `Dependency`s from `Package.dependencies`. |
| 331 |
let dep_ids = &cargo_metadata |
| 332 |
.resolve |
| 333 |
.as_ref() |
| 334 |
.unwrap() |
| 335 |
.nodes |
| 336 |
.iter() |
| 337 |
.find(|node| node.id == top.id) |
| 338 |
.unwrap() |
| 339 |
.dependencies; |
| 340 |
for dep_id in dep_ids { |
| 341 |
// Assumption: Each package name can only occur once in a `[dependencies]` table. |
| 342 |
let dependency = top |
| 343 |
.dependencies |
| 344 |
.iter() |
| 345 |
.find(|package| { |
| 346 |
// Package ids are opaque and there seems to be no way to query their name. |
| 347 |
let dep_name = &cargo_metadata |
| 348 |
.packages |
| 349 |
.iter() |
| 350 |
.find(|package| &package.id == dep_id) |
| 351 |
.unwrap() |
| 352 |
.name; |
| 353 |
&package.name == dep_name |
| 354 |
}) |
| 355 |
.unwrap(); |
| 356 |
if let Some(path) = &dependency.path { |
| 357 |
let dep_name = dependency.rename.as_ref().unwrap_or(&dependency.name); |
| 358 |
if path_deps.contains_key(dep_name) { |
| 359 |
continue; |
| 360 |
} |
| 361 |
// we search for the respective package by `manifest_path`, there seems |
| 362 |
// to be no way to query the dependency graph given `dependency` |
| 363 |
let dep_manifest_path = path.join("Cargo.toml"); |
| 364 |
// Path dependencies may not be in the same workspace as the root crate, |
| 365 |
// thus we need to find out its workspace root from `cargo metadata` |
| 366 |
let path_dep_metadata = MetadataCommand::new() |
| 367 |
.manifest_path(&dep_manifest_path) |
| 368 |
.verbose(true) |
| 369 |
// We don't need to resolve the dependency graph |
| 370 |
.no_deps() |
| 371 |
.exec() |
| 372 |
.with_context(|| { |
| 373 |
format!( |
| 374 |
"Failed to resolve workspace root for {dep_id} at '{dep_manifest_path}'" |
| 375 |
) |
| 376 |
})?; |
| 377 |
|
| 378 |
path_deps.insert( |
| 379 |
dep_name.clone(), |
| 380 |
PathDependency { |
| 381 |
manifest_path: PathBuf::from(dep_manifest_path.clone()), |
| 382 |
workspace_root: path_dep_metadata |
| 383 |
.workspace_root |
| 384 |
.clone() |
| 385 |
.into_std_path_buf(), |
| 386 |
readme: pkg_readmes.get(dep_id).cloned(), |
| 387 |
}, |
| 388 |
); |
| 389 |
if let Some(dep_package) = cargo_metadata |
| 390 |
.packages |
| 391 |
.iter() |
| 392 |
.find(|package| package.manifest_path == dep_manifest_path) |
| 393 |
{ |
| 394 |
// scan the dependencies of the path dependency |
| 395 |
stack.push(dep_package) |
| 396 |
} |
| 397 |
} |
| 398 |
} |
| 399 |
} |
| 400 |
Ok(path_deps) |
| 401 |
} |
| 402 |
|
| 403 |
/// Copies the files of git to a source distribution |
| 404 |
/// |
| 405 |
/// Runs `git ls-files -z` to obtain a list of files to package. |
| 406 |
fn add_git_tracked_files_to_sdist( |
| 407 |
pyproject_toml_path: &Path, |
| 408 |
writer: &mut SDistWriter, |
| 409 |
prefix: impl AsRef<Path>, |
| 410 |
) -> Result<()> { |
| 411 |
let pyproject_dir = pyproject_toml_path.parent().unwrap(); |
| 412 |
let output = Command::new("git") |
| 413 |
.args(["ls-files", "-z"]) |
| 414 |
.current_dir(pyproject_dir) |
| 415 |
.output() |
| 416 |
.context("Failed to run `git ls-files -z`")?; |
| 417 |
if !output.status.success() { |
| 418 |
bail!( |
| 419 |
"Failed to query file list from git: {}\n--- Project Path: {}\n--- Stdout:\n{}\n--- Stderr:\n{}", |
| 420 |
output.status, |
| 421 |
pyproject_dir.display(), |
| 422 |
String::from_utf8_lossy(&output.stdout), |
| 423 |
String::from_utf8_lossy(&output.stderr), |
| 424 |
); |
| 425 |
} |
| 426 |
|
| 427 |
let prefix = prefix.as_ref(); |
| 428 |
writer.add_directory(prefix)?; |
| 429 |
|
| 430 |
let file_paths = str::from_utf8(&output.stdout) |
| 431 |
.context("git printed invalid utf-8 ಠ_ಠ")? |
| 432 |
.split('\0') |
| 433 |
.filter(|s| !s.is_empty()) |
| 434 |
.map(Path::new); |
| 435 |
for source in file_paths { |
| 436 |
writer.add_file(prefix.join(source), pyproject_dir.join(source))?; |
| 437 |
} |
| 438 |
Ok(()) |
| 439 |
} |
| 440 |
|
| 441 |
/// Copies the files of a crate to a source distribution, recursively adding path dependencies |
| 442 |
/// and rewriting path entries in Cargo.toml |
| 443 |
fn add_cargo_package_files_to_sdist( |
| 444 |
build_context: &BuildContext, |
| 445 |
pyproject_toml_path: &Path, |
| 446 |
writer: &mut SDistWriter, |
| 447 |
root_dir: &Path, |
| 448 |
) -> Result<()> { |
| 449 |
let manifest_path = &build_context.manifest_path; |
| 450 |
let workspace_root = &build_context.cargo_metadata.workspace_root; |
| 451 |
let workspace_manifest_path = workspace_root.join("Cargo.toml"); |
| 452 |
|
| 453 |
let known_path_deps = find_path_deps(&build_context.cargo_metadata)?; |
| 454 |
debug!( |
| 455 |
"Found path dependencies: {:?}", |
| 456 |
known_path_deps.keys().collect::<Vec<_>>() |
| 457 |
); |
| 458 |
let mut sdist_root = |
| 459 |
common_path_prefix(workspace_root.as_std_path(), pyproject_toml_path).unwrap(); |
| 460 |
for path_dep in known_path_deps.values() { |
| 461 |
if let Some(prefix) = |
| 462 |
common_path_prefix(&sdist_root, path_dep.manifest_path.parent().unwrap()) |
| 463 |
{ |
| 464 |
sdist_root = prefix; |
| 465 |
} else { |
| 466 |
bail!("Failed to determine common path prefix of path dependencies"); |
| 467 |
} |
| 468 |
} |
| 469 |
|
| 470 |
debug!("Found sdist root: {}", sdist_root.display()); |
| 471 |
|
| 472 |
// Add local path dependencies |
| 473 |
for (name, path_dep) in known_path_deps.iter() { |
| 474 |
add_path_dep( |
| 475 |
writer, |
| 476 |
root_dir, |
| 477 |
workspace_root, |
| 478 |
&workspace_manifest_path, |
| 479 |
&known_path_deps, |
| 480 |
&sdist_root, |
| 481 |
name, |
| 482 |
path_dep, |
| 483 |
) |
| 484 |
.with_context(|| format!("Failed to add path dependency {name}"))?; |
| 485 |
} |
| 486 |
|
| 487 |
debug!("Adding the main crate {}", manifest_path.display()); |
| 488 |
// Add the main crate |
| 489 |
let abs_manifest_path = manifest_path |
| 490 |
.normalize() |
| 491 |
.with_context(|| { |
| 492 |
format!( |
| 493 |
"manifest path `{}` does not exist or is invalid", |
| 494 |
manifest_path.display() |
| 495 |
) |
| 496 |
})? |
| 497 |
.into_path_buf(); |
| 498 |
let abs_manifest_dir = abs_manifest_path.parent().unwrap(); |
| 499 |
let main_crate = build_context.cargo_metadata.root_package().unwrap(); |
| 500 |
let relative_main_crate_manifest_dir = manifest_path |
| 501 |
.parent() |
| 502 |
.unwrap() |
| 503 |
.strip_prefix(&sdist_root) |
| 504 |
.unwrap(); |
| 505 |
// Handle possible relative readme field in Cargo.toml |
| 506 |
let readme_path = if let Some(readme) = main_crate.readme.as_ref() { |
| 507 |
let readme = abs_manifest_dir.join(readme); |
| 508 |
let abs_readme = readme |
| 509 |
.normalize() |
| 510 |
.with_context(|| { |
| 511 |
format!( |
| 512 |
"readme path `{}` does not exist or is invalid", |
| 513 |
readme.display() |
| 514 |
) |
| 515 |
})? |
| 516 |
.into_path_buf(); |
| 517 |
// Add readme next to Cargo.toml so we don't get collisions between crates using readmes |
| 518 |
// higher up the file tree. |
| 519 |
writer.add_file( |
| 520 |
root_dir |
| 521 |
.join(relative_main_crate_manifest_dir) |
| 522 |
.join(readme.file_name().unwrap()), |
| 523 |
&abs_readme, |
| 524 |
)?; |
| 525 |
Some(abs_readme) |
| 526 |
} else { |
| 527 |
None |
| 528 |
}; |
| 529 |
add_crate_to_source_distribution( |
| 530 |
writer, |
| 531 |
manifest_path, |
| 532 |
root_dir.join(relative_main_crate_manifest_dir), |
| 533 |
readme_path.as_deref(), |
| 534 |
&known_path_deps, |
| 535 |
true, |
| 536 |
false, |
| 537 |
)?; |
| 538 |
|
| 539 |
// Add Cargo.lock file and workspace Cargo.toml |
| 540 |
let manifest_cargo_lock_path = abs_manifest_dir.join("Cargo.lock"); |
| 541 |
let workspace_cargo_lock = workspace_root.join("Cargo.lock").into_std_path_buf(); |
| 542 |
let (cargo_lock_path, use_workspace_cargo_lock) = if manifest_cargo_lock_path.exists() { |
| 543 |
(Some(manifest_cargo_lock_path.clone()), false) |
| 544 |
} else if workspace_cargo_lock.exists() { |
| 545 |
(Some(workspace_cargo_lock), true) |
| 546 |
} else { |
| 547 |
(None, false) |
| 548 |
}; |
| 549 |
let cargo_lock_required = |
| 550 |
build_context.cargo_options.locked || build_context.cargo_options.frozen; |
| 551 |
if let Some(cargo_lock_path) = cargo_lock_path { |
| 552 |
let pyproject_root = pyproject_toml_path.parent().unwrap(); |
| 553 |
let project_root = |
| 554 |
if pyproject_root == sdist_root || pyproject_root.starts_with(&sdist_root) { |
| 555 |
&sdist_root |
| 556 |
} else { |
| 557 |
assert!(sdist_root.starts_with(pyproject_root)); |
| 558 |
pyproject_root |
| 559 |
}; |
| 560 |
let relative_cargo_lock = cargo_lock_path.strip_prefix(project_root).unwrap(); |
| 561 |
writer.add_file(root_dir.join(relative_cargo_lock), &cargo_lock_path)?; |
| 562 |
if use_workspace_cargo_lock { |
| 563 |
let relative_workspace_cargo_toml = relative_cargo_lock.with_file_name("Cargo.toml"); |
| 564 |
let mut deps_to_keep = known_path_deps.clone(); |
| 565 |
// Also need to the main Python binding crate |
| 566 |
let main_member_name = abs_manifest_dir |
| 567 |
.strip_prefix(workspace_root) |
| 568 |
.unwrap() |
| 569 |
.to_slash() |
| 570 |
.unwrap() |
| 571 |
.to_string(); |
| 572 |
deps_to_keep.insert( |
| 573 |
main_member_name, |
| 574 |
PathDependency { |
| 575 |
manifest_path: manifest_path.clone(), |
| 576 |
workspace_root: workspace_root.clone().into_std_path_buf(), |
| 577 |
readme: None, |
| 578 |
}, |
| 579 |
); |
| 580 |
let mut document = |
| 581 |
parse_toml_file(workspace_manifest_path.as_std_path(), "Cargo.toml")?; |
| 582 |
rewrite_cargo_toml( |
| 583 |
&mut document, |
| 584 |
workspace_manifest_path.as_std_path(), |
| 585 |
&deps_to_keep, |
| 586 |
)?; |
| 587 |
writer.add_bytes( |
| 588 |
root_dir.join(relative_workspace_cargo_toml), |
| 589 |
Some(workspace_manifest_path.as_std_path()), |
| 590 |
document.to_string().as_bytes(), |
| 591 |
)?; |
| 592 |
} |
| 593 |
} else if cargo_lock_required { |
| 594 |
bail!("Cargo.lock is required by `--locked`/`--frozen` but it's not found."); |
| 595 |
} else { |
| 596 |
eprintln!( |
| 597 |
"⚠️ Warning: Cargo.lock is not found, it is recommended \ |
| 598 |
to include it in the source distribution" |
| 599 |
); |
| 600 |
} |
| 601 |
|
| 602 |
// Add pyproject.toml |
| 603 |
let pyproject_dir = pyproject_toml_path.parent().unwrap(); |
| 604 |
if pyproject_dir != sdist_root { |
| 605 |
// rewrite `tool.maturin.manifest-path` in pyproject.toml |
| 606 |
let rewritten_pyproject_toml = rewrite_pyproject_toml( |
| 607 |
pyproject_toml_path, |
| 608 |
&relative_main_crate_manifest_dir.join("Cargo.toml"), |
| 609 |
)?; |
| 610 |
writer.add_bytes( |
| 611 |
root_dir.join("pyproject.toml"), |
| 612 |
Some(pyproject_toml_path), |
| 613 |
rewritten_pyproject_toml.as_bytes(), |
| 614 |
)?; |
| 615 |
} else { |
| 616 |
writer.add_file(root_dir.join("pyproject.toml"), pyproject_toml_path)?; |
| 617 |
} |
| 618 |
|
| 619 |
// Add python source files |
| 620 |
let mut python_packages = Vec::new(); |
| 621 |
if let Some(python_module) = build_context.project_layout.python_module.as_ref() { |
| 622 |
trace!("Resolved python module: {}", python_module.display()); |
| 623 |
python_packages.push(python_module.to_path_buf()); |
| 624 |
} |
| 625 |
for package in &build_context.project_layout.python_packages { |
| 626 |
let package_path = build_context.project_layout.python_dir.join(package); |
| 627 |
if python_packages.contains(&package_path) { |
| 628 |
continue; |
| 629 |
} |
| 630 |
trace!("Resolved python package: {}", package_path.display()); |
| 631 |
python_packages.push(package_path); |
| 632 |
} |
| 633 |
|
| 634 |
for package in python_packages { |
| 635 |
for entry in ignore::Walk::new(package) { |
| 636 |
let source = entry?.into_path(); |
| 637 |
// Technically, `ignore` crate should handle this, |
| 638 |
// but somehow it doesn't on Alpine Linux running in GitHub Actions, |
| 639 |
// so we do it manually here. |
| 640 |
// See https://github.com/PyO3/maturin/pull/1187#issuecomment-1273987013 |
| 641 |
if source |
| 642 |
.extension() |
| 643 |
.map(|ext| ext == "pyc" || ext == "pyd" || ext == "so") |
| 644 |
.unwrap_or_default() |
| 645 |
{ |
| 646 |
debug!("Ignoring {}", source.display()); |
| 647 |
continue; |
| 648 |
} |
| 649 |
let target = root_dir.join(source.strip_prefix(pyproject_dir).unwrap()); |
| 650 |
if source.is_dir() { |
| 651 |
writer.add_directory(target)?; |
| 652 |
} else { |
| 653 |
writer.add_file(target, &source)?; |
| 654 |
} |
| 655 |
} |
| 656 |
} |
| 657 |
|
| 658 |
Ok(()) |
| 659 |
} |
| 660 |
|
| 661 |
#[allow(clippy::too_many_arguments)] // TODO(konsti) |
| 662 |
fn add_path_dep( |
| 663 |
writer: &mut SDistWriter, |
| 664 |
root_dir: &Path, |
| 665 |
workspace_root: &Utf8Path, |
| 666 |
workspace_manifest_path: &Utf8Path, |
| 667 |
known_path_deps: &HashMap<String, PathDependency>, |
| 668 |
sdist_root: &Path, |
| 669 |
name: &str, |
| 670 |
path_dep: &PathDependency, |
| 671 |
) -> Result<()> { |
| 672 |
debug!( |
| 673 |
"Adding path dependency: {} at {}", |
| 674 |
name, |
| 675 |
path_dep.manifest_path.display() |
| 676 |
); |
| 677 |
let path_dep_manifest_dir = path_dep.manifest_path.parent().unwrap(); |
| 678 |
let relative_path_dep_manifest_dir = path_dep_manifest_dir.strip_prefix(sdist_root).unwrap(); |
| 679 |
// we may need to rewrite workspace Cargo.toml later so don't add it to sdist yet |
| 680 |
let skip_cargo_toml = workspace_manifest_path == path_dep.manifest_path; |
| 681 |
add_crate_to_source_distribution( |
| 682 |
writer, |
| 683 |
&path_dep.manifest_path, |
| 684 |
root_dir.join(relative_path_dep_manifest_dir), |
| 685 |
path_dep.readme.as_deref(), |
| 686 |
known_path_deps, |
| 687 |
false, |
| 688 |
skip_cargo_toml, |
| 689 |
) |
| 690 |
.with_context(|| { |
| 691 |
format!( |
| 692 |
"Failed to add local dependency {} at {} to the source distribution", |
| 693 |
name, |
| 694 |
path_dep.manifest_path.display() |
| 695 |
) |
| 696 |
})?; |
| 697 |
// Include readme |
| 698 |
if let Some(readme) = path_dep.readme.as_ref() { |
| 699 |
let readme = path_dep_manifest_dir.join(readme); |
| 700 |
let abs_readme = readme |
| 701 |
.normalize() |
| 702 |
.with_context(|| { |
| 703 |
format!( |
| 704 |
"readme path `{}` does not exist or is invalid", |
| 705 |
readme.display() |
| 706 |
) |
| 707 |
})? |
| 708 |
.into_path_buf(); |
| 709 |
// Add readme next to Cargo.toml so we don't get collisions between crates using readmes |
| 710 |
// higher up the file tree. See also [`rewrite_cargo_toml_readme`]. |
| 711 |
writer.add_file( |
| 712 |
root_dir |
| 713 |
.join(relative_path_dep_manifest_dir) |
| 714 |
.join(readme.file_name().unwrap()), |
| 715 |
&abs_readme, |
| 716 |
)?; |
| 717 |
} |
| 718 |
// Handle different workspace manifest |
| 719 |
if path_dep.workspace_root != workspace_root { |
| 720 |
let path_dep_workspace_manifest = path_dep.workspace_root.join("Cargo.toml"); |
| 721 |
let relative_path_dep_workspace_manifest = path_dep_workspace_manifest |
| 722 |
.strip_prefix(sdist_root) |
| 723 |
.unwrap(); |
| 724 |
writer.add_file( |
| 725 |
root_dir.join(relative_path_dep_workspace_manifest), |
| 726 |
&path_dep_workspace_manifest, |
| 727 |
)?; |
| 728 |
} |
| 729 |
Ok(()) |
| 730 |
} |
| 731 |
|
| 732 |
/// Creates a source distribution, packing the root crate and all local dependencies |
| 733 |
/// |
| 734 |
/// The source distribution format is specified in |
| 735 |
/// [PEP 517 under "build_sdist"](https://www.python.org/dev/peps/pep-0517/#build-sdist) |
| 736 |
/// and in |
| 737 |
/// https://packaging.python.org/specifications/source-distribution-format/#source-distribution-file-format |
| 738 |
pub fn source_distribution( |
| 739 |
build_context: &BuildContext, |
| 740 |
pyproject: &PyProjectToml, |
| 741 |
excludes: Override, |
| 742 |
) -> Result<PathBuf> { |
| 743 |
let pyproject_toml_path = build_context |
| 744 |
.pyproject_toml_path |
| 745 |
.normalize() |
| 746 |
.with_context(|| { |
| 747 |
format!( |
| 748 |
"pyproject.toml path `{}` does not exist or is invalid", |
| 749 |
build_context.pyproject_toml_path.display() |
| 750 |
) |
| 751 |
})? |
| 752 |
.into_path_buf(); |
| 753 |
let metadata24 = &build_context.metadata24; |
| 754 |
let mut writer = SDistWriter::new(&build_context.out, metadata24, excludes)?; |
| 755 |
let root_dir = PathBuf::from(format!( |
| 756 |
"{}-{}", |
| 757 |
&metadata24.get_distribution_escaped(), |
| 758 |
&metadata24.get_version_escaped() |
| 759 |
)); |
| 760 |
|
| 761 |
match pyproject.sdist_generator() { |
| 762 |
SdistGenerator::Cargo => add_cargo_package_files_to_sdist( |
| 763 |
build_context, |
| 764 |
&pyproject_toml_path, |
| 765 |
&mut writer, |
| 766 |
&root_dir, |
| 767 |
)?, |
| 768 |
SdistGenerator::Git => { |
| 769 |
add_git_tracked_files_to_sdist(&pyproject_toml_path, &mut writer, &root_dir)? |
| 770 |
} |
| 771 |
} |
| 772 |
|
| 773 |
let pyproject_toml_path = build_context |
| 774 |
.pyproject_toml_path |
| 775 |
.normalize() |
| 776 |
.with_context(|| { |
| 777 |
format!( |
| 778 |
"pyproject.toml path `{}` does not exist or is invalid", |
| 779 |
build_context.pyproject_toml_path.display() |
| 780 |
) |
| 781 |
})? |
| 782 |
.into_path_buf(); |
| 783 |
let pyproject_dir = pyproject_toml_path.parent().unwrap(); |
| 784 |
// Add readme, license |
| 785 |
if let Some(project) = pyproject.project.as_ref() { |
| 786 |
if let Some(pyproject_toml::ReadMe::RelativePath(readme)) = project.readme.as_ref() { |
| 787 |
writer.add_file(root_dir.join(readme), pyproject_dir.join(readme))?; |
| 788 |
} |
| 789 |
if let Some(pyproject_toml::License::File { file }) = project.license.as_ref() { |
| 790 |
writer.add_file(root_dir.join(file), pyproject_dir.join(file))?; |
| 791 |
} |
| 792 |
if let Some(license_files) = &project.license_files { |
| 793 |
// Safe on Windows and Unix as neither forward nor backwards slashes are escaped. |
| 794 |
let escaped_pyproject_dir = |
| 795 |
PathBuf::from(glob::Pattern::escape(pyproject_dir.to_str().unwrap())); |
| 796 |
let mut seen = HashSet::new(); |
| 797 |
for license_glob in license_files { |
| 798 |
check_pep639_glob(license_glob)?; |
| 799 |
for license_path in |
| 800 |
glob::glob(&escaped_pyproject_dir.join(license_glob).to_string_lossy())? |
| 801 |
{ |
| 802 |
let license_path = license_path?; |
| 803 |
if !license_path.is_file() { |
| 804 |
continue; |
| 805 |
} |
| 806 |
let license_path = license_path |
| 807 |
.strip_prefix(pyproject_dir) |
| 808 |
.expect("matched path starts with glob root") |
| 809 |
.to_path_buf(); |
| 810 |
if seen.insert(license_path.clone()) { |
| 811 |
debug!("Including license file `{}`", license_path.display()); |
| 812 |
writer.add_file( |
| 813 |
root_dir.join(&license_path), |
| 814 |
pyproject_dir.join(&license_path), |
| 815 |
)?; |
| 816 |
} |
| 817 |
} |
| 818 |
} |
| 819 |
} |
| 820 |
} |
| 821 |
|
| 822 |
let mut include = |pattern| -> Result<()> { |
| 823 |
eprintln!("📦 Including files matching \"{pattern}\""); |
| 824 |
for source in glob::glob(&pyproject_dir.join(pattern).to_string_lossy()) |
| 825 |
.with_context(|| format!("Invalid glob pattern: {pattern}"))? |
| 826 |
.filter_map(Result::ok) |
| 827 |
{ |
| 828 |
let target = root_dir.join(source.strip_prefix(pyproject_dir).unwrap()); |
| 829 |
if source.is_dir() { |
| 830 |
writer.add_directory(target)?; |
| 831 |
} else { |
| 832 |
writer.add_file(target, source)?; |
| 833 |
} |
| 834 |
} |
| 835 |
Ok(()) |
| 836 |
}; |
| 837 |
|
| 838 |
if let Some(glob_patterns) = pyproject.include() { |
| 839 |
for pattern in glob_patterns |
| 840 |
.iter() |
| 841 |
.filter_map(|glob_pattern| glob_pattern.targets(Format::Sdist)) |
| 842 |
{ |
| 843 |
include(pattern)?; |
| 844 |
} |
| 845 |
} |
| 846 |
|
| 847 |
writer.add_bytes( |
| 848 |
root_dir.join("PKG-INFO"), |
| 849 |
None, |
| 850 |
metadata24.to_file_contents()?.as_bytes(), |
| 851 |
)?; |
| 852 |
|
| 853 |
let source_distribution_path = writer.finish()?; |
| 854 |
|
| 855 |
eprintln!( |
| 856 |
"📦 Built source distribution to {}", |
| 857 |
source_distribution_path.display() |
| 858 |
); |
| 859 |
|
| 860 |
Ok(source_distribution_path) |
| 861 |
} |
| 862 |
|
| 863 |
/// Find the common prefix, if any, between two paths |
| 864 |
/// |
| 865 |
/// Taken from https://docs.rs/common-path/1.0.0/src/common_path/lib.rs.html#84-109 |
| 866 |
/// License: MIT/Apache 2.0 |
| 867 |
fn common_path_prefix<P, Q>(one: P, two: Q) -> Option<PathBuf> |
| 868 |
where |
| 869 |
P: AsRef<Path>, |
| 870 |
Q: AsRef<Path>, |
| 871 |
{ |
| 872 |
let one = one.as_ref(); |
| 873 |
let two = two.as_ref(); |
| 874 |
let one = one.components(); |
| 875 |
let two = two.components(); |
| 876 |
let mut final_path = PathBuf::new(); |
| 877 |
let mut found = false; |
| 878 |
let paths = one.zip(two); |
| 879 |
for (l, r) in paths { |
| 880 |
if l == r { |
| 881 |
final_path.push(l.as_os_str()); |
| 882 |
found = true; |
| 883 |
} else { |
| 884 |
break; |
| 885 |
} |
| 886 |
} |
| 887 |
if found { |
| 888 |
Some(final_path) |
| 889 |
} else { |
| 890 |
None |
| 891 |
} |
| 892 |
} |