Debian Codegraph @

src/project_layout.rs

raw
1 use crate::build_options::{extract_cargo_metadata_args, CargoOptions};
2 use crate::{CargoToml, Metadata24, PyProjectToml};
3 use anyhow::{bail, format_err, Context, Result};
4 use cargo_metadata::{Metadata, MetadataCommand};
5 use normpath::PathExt as _;
6 use std::collections::HashSet;
7 use std::env;
8 use std::io;
9 use std::path::{Path, PathBuf};
10 use tracing::{debug, instrument, warn};
11
12 const PYPROJECT_TOML: &str = "pyproject.toml";
13
14 /// Whether this project is pure rust or rust mixed with python and whether it has wheel data
15 #[derive(Clone, Debug, PartialEq, Eq)]
16 pub struct ProjectLayout {
17 /// Contains the absolute path to the project root directory
18 pub project_root: PathBuf,
19 /// Contains the absolute path to the python source directory
20 pub python_dir: PathBuf,
21 /// Contains the canonicalized (i.e. absolute) path to the python part of the project
22 /// If none, we have a rust crate compiled into a shared library with only some glue python for cffi
23 /// If some, we have a python package that is extended by a native rust module.
24 pub python_module: Option<PathBuf>,
25 /// Python packages to include
26 pub python_packages: Vec<String>,
27 /// Contains the canonicalized (i.e. absolute) path to the rust part of the project
28 pub rust_module: PathBuf,
29 /// Rust extension name
30 pub extension_name: String,
31 /// The location of the wheel data, if any
32 pub data: Option<PathBuf>,
33 }
34
35 /// Project resolver
36 #[derive(Clone, Debug)]
37 pub struct ProjectResolver {
38 /// Project layout
39 pub project_layout: ProjectLayout,
40 /// Cargo.toml path
41 pub cargo_toml_path: PathBuf,
42 /// Parsed Cargo.toml
43 pub cargo_toml: CargoToml,
44 /// pyproject.toml path
45 pub pyproject_toml_path: PathBuf,
46 /// Parsed pyproject.toml
47 pub pyproject_toml: Option<PyProjectToml>,
48 /// Rust module name
49 pub module_name: String,
50 /// Python Package Metadata 2.3
51 pub metadata24: Metadata24,
52 /// Cargo options
53 pub cargo_options: CargoOptions,
54 /// Cargo.toml as resolved by [cargo_metadata]
55 pub cargo_metadata: Metadata,
56 /// maturin options specified in pyproject.toml
57 pub pyproject_toml_maturin_options: Vec<&'static str>,
58 }
59
60 impl ProjectResolver {
61 /// Resolve project layout
62 pub fn resolve(
63 cargo_manifest_path: Option<PathBuf>,
64 mut cargo_options: CargoOptions,
65 ) -> Result<Self> {
66 let (manifest_file, pyproject_file) =
67 Self::resolve_manifest_paths(cargo_manifest_path, &cargo_options)?;
68 if !manifest_file.is_file() {
69 bail!(
70 "{} is not the path to a Cargo.toml",
71 manifest_file.display()
72 );
73 }
74 // Sanity checks in debug build
75 debug_assert!(
76 manifest_file.is_absolute(),
77 "manifest_file {} is not absolute",
78 manifest_file.display()
79 );
80 debug_assert!(
81 pyproject_file.is_absolute(),
82 "pyproject_file {} is not absolute",
83 pyproject_file.display()
84 );
85
86 // Set Cargo manifest path
87 cargo_options.manifest_path = Some(manifest_file.clone());
88
89 let cargo_toml = CargoToml::from_path(&manifest_file)?;
90 cargo_toml.check_removed_python_metadata()?;
91
92 let manifest_dir = manifest_file.parent().unwrap();
93 let pyproject_toml: Option<PyProjectToml> = if pyproject_file.is_file() {
94 let pyproject = PyProjectToml::new(&pyproject_file)?;
95 pyproject.warn_bad_maturin_version();
96 pyproject.warn_missing_build_backend();
97 Some(pyproject)
98 } else {
99 None
100 };
101 let pyproject = pyproject_toml.as_ref();
102 let tool_maturin = pyproject.and_then(|p| p.maturin());
103
104 let pyproject_toml_maturin_options = if let Some(tool_maturin) = tool_maturin {
105 cargo_options.merge_with_pyproject_toml(tool_maturin.clone())
106 } else {
107 Vec::new()
108 };
109
110 let cargo_metadata = Self::resolve_cargo_metadata(&manifest_file, &cargo_options)?;
111
112 let mut metadata24 = Metadata24::from_cargo_toml(manifest_dir, &cargo_metadata)
113 .context("Failed to parse Cargo.toml into python metadata")?;
114 if let Some(pyproject) = pyproject {
115 let pyproject_dir = pyproject_file.parent().unwrap();
116 metadata24.merge_pyproject_toml(pyproject_dir, pyproject)?;
117 }
118
119 let crate_name = &cargo_toml.package.name;
120
121 // If the package name contains minuses, you must declare a module with
122 // underscores as lib name
123 // Precedence:
124 // * Explicitly declared pyproject.toml `tool.maturin.module-name`
125 // * Cargo.toml `lib.name`
126 // * pyproject.toml `project.name`
127 // * Cargo.toml `package.name`
128 let module_name = pyproject
129 .and_then(|x| x.module_name())
130 .or(cargo_toml.lib.as_ref().and_then(|lib| lib.name.as_deref()))
131 .or(pyproject
132 .and_then(|pyproject| pyproject.project.as_ref())
133 .map(|project| project.name.as_str()))
134 .unwrap_or(crate_name)
135 .to_owned();
136
137 let project_root = if pyproject_file.is_file() {
138 pyproject_file.parent().unwrap_or(manifest_dir)
139 } else {
140 manifest_dir
141 };
142 let python_packages = pyproject
143 .and_then(|x| x.python_packages())
144 .unwrap_or_default()
145 .to_vec();
146 let py_root = match pyproject.and_then(|x| x.python_source()) {
147 Some(py_src) => project_root
148 .join(py_src)
149 .normalize()
150 .with_context(|| {
151 format!(
152 "python source path `{}` does not exist or is invalid",
153 py_src.display()
154 )
155 })?
156 .into_path_buf(),
157 None => match pyproject.and_then(|x| x.project_name()) {
158 Some(project_name) => {
159 // Detect src layout
160 let rust_cargo_toml_found =
161 project_root.join("rust").join("Cargo.toml").is_file();
162 let import_name = project_name.replace('-', "_");
163 let mut package_init = HashSet::new();
164 package_init.insert(
165 project_root
166 .join("src")
167 .join(import_name)
168 .join("__init__.py"),
169 );
170 for package in &python_packages {
171 package_init
172 .insert(project_root.join("src").join(package).join("__init__.py"));
173 }
174 let python_src_found = package_init.iter().any(|x| x.is_file());
175 if rust_cargo_toml_found && python_src_found {
176 project_root.join("src")
177 } else {
178 project_root.to_path_buf()
179 }
180 }
181 None => project_root.to_path_buf(),
182 },
183 };
184 let data = pyproject.and_then(|x| x.data()).map(|data| {
185 if data.is_absolute() {
186 data.to_path_buf()
187 } else {
188 project_root.join(data)
189 }
190 });
191 let custom_python_source = pyproject.and_then(|x| x.python_source()).is_some();
192 let project_layout = ProjectLayout::determine(
193 project_root,
194 &module_name,
195 py_root,
196 python_packages,
197 data,
198 custom_python_source,
199 )?;
200 Ok(Self {
201 project_layout,
202 cargo_toml_path: manifest_file,
203 cargo_toml,
204 pyproject_toml_path: pyproject_file,
205 pyproject_toml,
206 module_name,
207 metadata24,
208 cargo_options,
209 cargo_metadata,
210 pyproject_toml_maturin_options,
211 })
212 }
213
214 /// Get cargo manifest file path and pyproject.toml path
215 fn resolve_manifest_paths(
216 cargo_manifest_path: Option<PathBuf>,
217 cargo_options: &CargoOptions,
218 ) -> Result<(PathBuf, PathBuf)> {
219 // use command line argument if specified
220 if let Some(path) = cargo_manifest_path {
221 let path = path
222 .normalize()
223 .with_context(|| {
224 format!(
225 "manifest path `{}` does not exist or is invalid",
226 path.display()
227 )
228 })?
229 .into_path_buf();
230 debug!(
231 "Using cargo manifest path from command line argument: {:?}",
232 path
233 );
234 let workspace_root = Self::resolve_cargo_metadata(&path, cargo_options)?.workspace_root;
235 let workspace_parent = workspace_root.parent().unwrap_or(&workspace_root);
236 for parent in path.ancestors().skip(1) {
237 // Allow looking outside to the parent directory of Cargo workspace root
238 if !dunce::simplified(parent).starts_with(workspace_parent) {
239 break;
240 }
241 let pyproject_file = parent.join(PYPROJECT_TOML);
242 if pyproject_file.is_file() {
243 debug!("Found pyproject.toml at {:?}", pyproject_file);
244 return Ok((path, pyproject_file));
245 }
246 }
247 let pyproject_file = path.parent().unwrap().join(PYPROJECT_TOML);
248 debug!("Trying pyproject.toml at {:?}", pyproject_file);
249 return Ok((path, pyproject_file));
250 }
251 // check `manifest-path` option in pyproject.toml
252 let current_dir = env::current_dir()
253 .context("Failed to detect current directory ಠ_ಠ")?
254 .normalize()?
255 .into_path_buf();
256 let pyproject_file = current_dir.join(PYPROJECT_TOML);
257 if pyproject_file.is_file() {
258 debug!(
259 "Found pyproject.toml in working directory at {:?}",
260 pyproject_file
261 );
262 let pyproject = PyProjectToml::new(&pyproject_file)?;
263 if let Some(path) = pyproject.manifest_path() {
264 debug!("Using cargo manifest path from pyproject.toml {:?}", path);
265 return Ok((
266 path.normalize()
267 .with_context(|| {
268 format!(
269 "manifest path `{}` does not exist or is invalid",
270 path.display()
271 )
272 })?
273 .into_path_buf(),
274 pyproject_file,
275 ));
276 } else {
277 // Detect src layout:
278 //
279 // my-project
280 // ├── README.md
281 // ├── pyproject.toml
282 // ├── src
283 // │ └── my_project
284 // │ ├── __init__.py
285 // │ └── bar.py
286 // └── rust
287 // ├── Cargo.toml
288 // └── src
289 // └── lib.rs
290 let path = current_dir.join("rust").join("Cargo.toml");
291 if path.is_file() {
292 debug!("Python first src-layout detected");
293 if pyproject.python_source().is_some() {
294 // python source directory is specified in pyproject.toml
295 return Ok((path, pyproject_file));
296 } else if let Some(project_name) = pyproject.project_name() {
297 // Check if python source directory in `src/<project_name>`
298 let import_name = project_name.replace('-', "_");
299 let mut package_init = HashSet::new();
300 package_init.insert(
301 current_dir
302 .join("src")
303 .join(import_name)
304 .join("__init__.py"),
305 );
306 for package in pyproject.python_packages().unwrap_or_default() {
307 package_init
308 .insert(current_dir.join("src").join(package).join("__init__.py"));
309 }
310 if package_init.iter().any(|x| x.is_file()) {
311 return Ok((path, pyproject_file));
312 }
313 }
314 }
315 }
316 }
317 // check Cargo.toml in current directory
318 let path = current_dir.join("Cargo.toml");
319 if path.exists() {
320 debug!(
321 "Using cargo manifest path from working directory: {:?}",
322 path
323 );
324 Ok((path, current_dir.join(PYPROJECT_TOML)))
325 } else {
326 Err(format_err!(
327 "Can't find {} (in {})",
328 path.display(),
329 current_dir.display()
330 ))
331 }
332 }
333
334 #[instrument(skip_all)]
335 fn resolve_cargo_metadata(
336 manifest_path: &Path,
337 cargo_options: &CargoOptions,
338 ) -> Result<Metadata> {
339 debug!("Resolving cargo metadata from {:?}", manifest_path);
340 let cargo_metadata_extra_args = extract_cargo_metadata_args(cargo_options)?;
341 let result = MetadataCommand::new()
342 // Force resolving metadata using cargo instead of instead of $CARGO env var
343 // to avoid getting wrong file path like target directory, for example `cross` would
344 // output paths in docker while we want paths on host.
345 .cargo_path("cargo")
346 .manifest_path(manifest_path)
347 .verbose(true)
348 .other_options(cargo_metadata_extra_args)
349 .exec();
350
351 let cargo_metadata = match result {
352 Ok(cargo_metadata) => cargo_metadata,
353 Err(cargo_metadata::Error::Io(inner)) if inner.kind() == io::ErrorKind::NotFound => {
354 // NotFound is the specific error when cargo is not in PATH
355 return Err(inner)
356 .context("Cargo metadata failed. Do you have cargo in your PATH?");
357 }
358 Err(err) => {
359 return Err(err)
360 .context("Cargo metadata failed. Does your crate compile with `cargo build`?");
361 }
362 };
363 Ok(cargo_metadata)
364 }
365 }
366
367 impl ProjectLayout {
368 /// Checks whether a python module exists besides Cargo.toml with the right name
369 fn determine(
370 project_root: &Path,
371 module_name: &str,
372 python_root: PathBuf,
373 python_packages: Vec<String>,
374 data: Option<PathBuf>,
375 custom_python_source: bool,
376 ) -> Result<ProjectLayout> {
377 // A dot in the module name means the extension module goes into the module folder specified by the path
378 let parts: Vec<&str> = module_name.split('.').collect();
379 let (python_module, rust_module, extension_name) = if parts.len() > 1 {
380 let mut rust_module = python_root.clone();
381 rust_module.extend(&parts[0..parts.len() - 1]);
382 (
383 python_root.join(parts[0]),
384 rust_module,
385 parts[parts.len() - 1].to_string(),
386 )
387 } else {
388 (
389 python_root.join(module_name),
390 python_root.join(module_name),
391 module_name.to_string(),
392 )
393 };
394 // If no __init__.py exists, we can't treat it as python source module,
395 // it could be a Rust crate with the same name as the module.
396 let python_module = if !python_module.join("__init__.py").is_file()
397 && python_module.join("Cargo.toml").is_file()
398 {
399 debug!("No __init__.py file found in {}", python_module.display());
400 None
401 } else {
402 Some(python_module)
403 };
404 debug!(
405 project_root = %project_root.display(),
406 python_dir = %python_root.display(),
407 rust_module = %rust_module.display(),
408 python_module = ?python_module,
409 extension_name = %extension_name,
410 module_name = %module_name,
411 "Project layout resolved"
412 );
413
414 let data = if let Some(data) = data {
415 if !data.is_dir() {
416 bail!("No such data directory {}", data.display());
417 }
418 Some(data)
419 } else if project_root.join(format!("{module_name}.data")).is_dir() {
420 Some(project_root.join(format!("{module_name}.data")))
421 } else {
422 None
423 };
424
425 if let Some(python_module) = python_module {
426 if python_module.is_dir() {
427 eprintln!("🍹 Building a mixed python/rust project");
428
429 Ok(ProjectLayout {
430 project_root: project_root.to_path_buf(),
431 python_dir: python_root,
432 python_packages,
433 python_module: Some(python_module),
434 rust_module,
435 extension_name,
436 data,
437 })
438 } else {
439 if custom_python_source {
440 eprintln!(
441 "⚠️ Warning: You specified the python source as {}, but the python module at \
442 {} is missing. No python module will be included.",
443 python_root.display(),
444 python_module.display()
445 );
446 }
447
448 Ok(ProjectLayout {
449 project_root: project_root.to_path_buf(),
450 python_dir: python_root,
451 python_packages,
452 python_module: None,
453 rust_module: project_root.to_path_buf(),
454 extension_name,
455 data,
456 })
457 }
458 } else {
459 Ok(ProjectLayout {
460 project_root: project_root.to_path_buf(),
461 python_dir: python_root,
462 python_packages,
463 python_module: None,
464 rust_module: project_root.to_path_buf(),
465 extension_name,
466 data,
467 })
468 }
469 }
470 }