Skip to content

Commit c78176a

Browse files
committed
Refactor StubInfoBuilder to reduce dependence on PyProject
To support generating stubs without a pyproject.toml file, it needs to be possible to build a StubInfo without one. The StubInfo only uses it to find the python root, so that value can be determined earlier in the process and passed along instead of the PyProject. StubInfoBuilder is not exported, so its ::new() can be renamed without causing backwards incompatibility.
1 parent 4721c02 commit c78176a

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

pyo3-stub-gen/src/generate/stub_info.rs

+10-13
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,22 @@ use std::{collections::BTreeMap, fs, io::Write, path::*};
55
#[derive(Debug, Clone, PartialEq)]
66
pub struct StubInfo {
77
pub modules: BTreeMap<String, Module>,
8-
pub pyproject: PyProject,
8+
pub python_root: PathBuf,
99
}
1010

1111
impl StubInfo {
1212
pub fn from_pyproject_toml(path: impl AsRef<Path>) -> Result<Self> {
1313
let pyproject = PyProject::parse_toml(path)?;
14-
Ok(StubInfoBuilder::new(pyproject).build())
14+
Ok(StubInfoBuilder::from_pyproject_toml(pyproject).build())
1515
}
1616

1717
pub fn generate(&self) -> Result<()> {
18-
let python_root = self
19-
.pyproject
20-
.python_source()
21-
.unwrap_or(PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()));
22-
2318
for (name, module) in self.modules.iter() {
2419
let path = name.replace(".", "/");
2520
let dest = if module.submodules.is_empty() {
26-
python_root.join(format!("{path}.pyi"))
21+
self.python_root.join(format!("{path}.pyi"))
2722
} else {
28-
python_root.join(path).join("__init__.pyi")
23+
self.python_root.join(path).join("__init__.pyi")
2924
};
3025

3126
let dir = dest.parent().context("Cannot get parent directory")?;
@@ -47,15 +42,17 @@ impl StubInfo {
4742
struct StubInfoBuilder {
4843
modules: BTreeMap<String, Module>,
4944
default_module_name: String,
50-
pyproject: PyProject,
45+
python_root: PathBuf,
5146
}
5247

5348
impl StubInfoBuilder {
54-
fn new(pyproject: PyProject) -> Self {
49+
fn from_pyproject_toml(pyproject: PyProject) -> Self {
5550
Self {
5651
modules: BTreeMap::new(),
5752
default_module_name: pyproject.module_name().to_string(),
58-
pyproject,
53+
python_root: pyproject
54+
.python_source()
55+
.unwrap_or(PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())),
5956
}
6057
}
6158

@@ -158,7 +155,7 @@ impl StubInfoBuilder {
158155
self.register_submodules();
159156
StubInfo {
160157
modules: self.modules,
161-
pyproject: self.pyproject,
158+
python_root: self.python_root,
162159
}
163160
}
164161
}

0 commit comments

Comments
 (0)