Debian Codegraph @

src/new_project.rs

raw
1 use self::package_name_validations::{cargo_check_name, pypi_check_name};
2 use crate::ci::GenerateCI;
3 use crate::{BridgeModel, PyO3};
4 use anyhow::{bail, Context, Result};
5 use console::style;
6 use dialoguer::{theme::ColorfulTheme, Select};
7 use fs_err as fs;
8 use minijinja::{context, Environment};
9 use semver::Version;
10 use std::path::Path;
11
12 /// Mixed Rust/Python project layout
13 #[derive(Debug, Clone, Copy)]
14 enum ProjectLayout {
15 Mixed { src: bool },
16 PureRust,
17 }
18
19 struct ProjectGenerator<'a> {
20 env: Environment<'a>,
21 project_name: String,
22 crate_name: String,
23 bindings: String,
24 layout: ProjectLayout,
25 ci_config: String,
26 overwrite: bool,
27 }
28
29 impl ProjectGenerator<'_> {
30 fn new(
31 project_name: String,
32 layout: ProjectLayout,
33 bindings: String,
34 overwrite: bool,
35 ) -> Result<Self> {
36 let crate_name = project_name.replace('-', "_");
37 let mut env = Environment::new();
38 env.set_keep_trailing_newline(true);
39 env.add_template(".gitignore", include_str!("templates/.gitignore.j2"))?;
40 env.add_template("Cargo.toml", include_str!("templates/Cargo.toml.j2"))?;
41 env.add_template(
42 "pyproject.toml",
43 include_str!("templates/pyproject.toml.j2"),
44 )?;
45 env.add_template("lib.rs", include_str!("templates/lib.rs.j2"))?;
46 env.add_template("main.rs", include_str!("templates/main.rs.j2"))?;
47 env.add_template("build.rs", include_str!("templates/build.rs.j2"))?;
48 env.add_template("__init__.py", include_str!("templates/__init__.py.j2"))?;
49 env.add_template("test_all.py", include_str!("templates/test_all.py.j2"))?;
50 env.add_template("example.udl", include_str!("templates/example.udl.j2"))?;
51
52 let bridge_model = match bindings.as_str() {
53 "bin" => BridgeModel::Bin(None),
54 "cffi" => BridgeModel::Cffi,
55 "uniffi" => BridgeModel::UniFfi,
56 _ => BridgeModel::PyO3(PyO3 {
57 crate_name: bindings.parse()?,
58 version: Version::new(0, 23, 1),
59 abi3: None,
60 metadata: None,
61 }),
62 };
63 let ci_config =
64 GenerateCI::default().generate_github(&project_name, &bridge_model, true)?;
65
66 Ok(Self {
67 env,
68 project_name,
69 crate_name,
70 bindings,
71 layout,
72 ci_config,
73 overwrite,
74 })
75 }
76
77 fn generate(&self, project_path: &Path) -> Result<()> {
78 fs::create_dir_all(project_path)?;
79 self.write_project_file(project_path, ".gitignore")?;
80 self.write_project_file(project_path, "pyproject.toml")?;
81
82 // CI configuration
83 let gh_action_path = project_path.join(".github").join("workflows");
84 fs::create_dir_all(&gh_action_path)?;
85 self.write_content(&gh_action_path, "CI.yml", self.ci_config.as_bytes())?;
86
87 let rust_project = match self.layout {
88 ProjectLayout::Mixed { src } => {
89 let python_dir = if src {
90 project_path.join("src")
91 } else {
92 project_path.join("python")
93 };
94 let python_project = python_dir.join(&self.crate_name);
95 fs::create_dir_all(&python_project)?;
96 self.write_project_file(&python_project, "__init__.py")?;
97
98 let test_dir = python_dir.join("tests");
99 fs::create_dir_all(&test_dir)?;
100 self.write_project_file(&test_dir, "test_all.py")?;
101
102 if src {
103 project_path.join("rust")
104 } else {
105 project_path.to_path_buf()
106 }
107 }
108 ProjectLayout::PureRust => project_path.to_path_buf(),
109 };
110
111 let rust_src = rust_project.join("src");
112 fs::create_dir_all(&rust_src)?;
113 self.write_project_file(&rust_project, "Cargo.toml")?;
114 if self.bindings == "bin" {
115 self.write_project_file(&rust_src, "main.rs")?;
116 } else {
117 self.write_project_file(&rust_src, "lib.rs")?;
118 if self.bindings == "uniffi" {
119 self.write_project_file(&rust_project, "build.rs")?;
120 self.write_project_file(&rust_src, "example.udl")?;
121 }
122 }
123
124 Ok(())
125 }
126
127 fn render_template(&self, tmpl_name: &str) -> Result<String> {
128 let version_major: usize = env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap();
129 let version_minor: usize = env!("CARGO_PKG_VERSION_MINOR").parse().unwrap();
130 let tmpl = self.env.get_template(tmpl_name)?;
131 let out = tmpl.render(context!(
132 name => self.project_name,
133 crate_name => self.crate_name,
134 bindings => self.bindings,
135 mixed_non_src => matches!(self.layout, ProjectLayout::Mixed { src: false }),
136 version_major => version_major,
137 version_minor => version_minor
138 ))?;
139 Ok(out)
140 }
141
142 fn write_project_file(&self, directory: &Path, file: &str) -> Result<()> {
143 let content = self.render_template(file)?;
144 self.write_content(directory, file, content.as_bytes())
145 }
146
147 fn write_content(&self, directory: &Path, file: &str, content: &[u8]) -> Result<()> {
148 let path = directory.join(file);
149 if self.overwrite || !path.exists() {
150 fs::write(path, content)?;
151 }
152 Ok(())
153 }
154 }
155
156 fn validate_name(name: &str) -> anyhow::Result<String> {
157 cargo_check_name(name).context("Invalid Cargo package name")?;
158 pypi_check_name(name).context("Invalid PyPI package name")?;
159 Ok(name.to_string())
160 }
161 /// Options common to `maturin new` and `maturin init`.
162 #[derive(Debug, clap::Parser)]
163 pub struct GenerateProjectOptions {
164 /// Set the resulting package name, defaults to the directory name
165 #[arg(
166 long,
167 value_parser=validate_name,
168 )]
169 name: Option<String>,
170 /// Use mixed Rust/Python project layout
171 #[arg(long)]
172 mixed: bool,
173 /// Use Python first src layout for mixed Rust/Python project
174 #[arg(long)]
175 src: bool,
176 /// Which kind of bindings to use
177 #[arg(
178 short,
179 long,
180 value_parser = ["pyo3", "cffi", "uniffi", "bin"]
181 )]
182 bindings: Option<String>,
183 }
184
185 /// Generate a new cargo project
186 pub fn new_project(path: String, options: GenerateProjectOptions) -> Result<()> {
187 let project_path = Path::new(&path);
188 if project_path.exists() {
189 bail!("destination `{}` already exists", project_path.display());
190 }
191 generate_project(project_path, options, true)?;
192 eprintln!(
193 " ✨ {} {} {}",
194 style("Done!").bold().green(),
195 style("New project created").bold(),
196 style(&project_path.display()).underlined()
197 );
198 Ok(())
199 }
200
201 /// Generate a new cargo project in an existing directory
202 pub fn init_project(path: Option<String>, options: GenerateProjectOptions) -> Result<()> {
203 let project_path = path
204 .map(Into::into)
205 .map_or_else(std::env::current_dir, Ok)?;
206 if project_path.join("pyproject.toml").exists() || project_path.join("Cargo.toml").exists() {
207 bail!("`maturin init` cannot be run on existing projects");
208 }
209 generate_project(&project_path, options, false)?;
210 eprintln!(
211 " ✨ {} {} {}",
212 style("Done!").bold().green(),
213 style("Initialized project").bold(),
214 style(&project_path.display()).underlined()
215 );
216 Ok(())
217 }
218
219 fn generate_project(
220 project_path: &Path,
221 options: GenerateProjectOptions,
222 overwrite: bool,
223 ) -> Result<()> {
224 let name = if let Some(name) = options.name {
225 name
226 } else {
227 let file_name = project_path.file_name().with_context(|| {
228 format!("Failed to get name from path '{}'", project_path.display())
229 })?;
230 let temp = file_name
231 .to_str()
232 .context("Filename isn't valid Unicode")?
233 .to_string();
234
235 validate_name(temp.as_str()).map_err(|e| anyhow::anyhow!(e))?
236 };
237 let bindings_items = if options.mixed {
238 vec!["pyo3", "cffi", "uniffi"]
239 } else {
240 vec!["pyo3", "cffi", "uniffi", "bin"]
241 };
242 let bindings = if let Some(bindings) = options.bindings {
243 bindings
244 } else {
245 let selection = Select::with_theme(&ColorfulTheme::default())
246 .with_prompt(format!(
247 "🤷 {}\n 📖 {}",
248 style("Which kind of bindings to use?").bold(),
249 style("Documentation: https://maturin.rs/bindings.html").dim()
250 ))
251 .items(&bindings_items)
252 .default(0)
253 .interact()?;
254 bindings_items[selection].to_string()
255 };
256
257 let layout = if options.mixed {
258 ProjectLayout::Mixed { src: options.src }
259 } else {
260 ProjectLayout::PureRust
261 };
262 let generator = ProjectGenerator::new(name, layout, bindings, overwrite)?;
263 generator.generate(project_path)
264 }
265
266 mod package_name_validations {
267 // based on: https://github.com/pypi/warehouse/blob/8f79d90a310f0243ab15f52c41de093708a61dfd/warehouse/packaging/models.py#L211C9-L214C10
268 pub fn pypi_check_name(name: &str) -> anyhow::Result<()> {
269 // The `(?i)` flag was added to make the regex case-insensitive
270 let pattern = regex::Regex::new(r"^((?i)[A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$").unwrap();
271
272 if !pattern.is_match(name) {
273 anyhow::bail!("The name `{}` is not a valid package name", name)
274 }
275 Ok(())
276 }
277
278 // Based on: https://github.com/rust-lang/cargo/blob/e975158c1b542aa3833fd8584746538c17a6ae55/src/cargo/ops/cargo_new.rs#L169
279 pub fn cargo_check_name(name: &str) -> anyhow::Result<()> {
280 // Instead of `PackageName::new` which performs these checks in the original cargo code
281 validate_package_name(name)?;
282
283 if is_keyword(name) {
284 anyhow::bail!(
285 "the name `{}` cannot be used as a package name, it is a Rust keyword",
286 name,
287 );
288 }
289 if is_conflicting_artifact_name(name) {
290 anyhow::bail!(
291 "the name `{}` cannot be used as a package name, \
292 it conflicts with cargo's build directory names",
293 name,
294 );
295 }
296 if name == "test" {
297 anyhow::bail!(
298 "the name `test` cannot be used as a package name, \
299 it conflicts with Rust's built-in test library",
300 );
301 }
302 if ["core", "std", "alloc", "proc_macro", "proc-macro"].contains(&name) {
303 eprintln!(
304 "⚠️ Warning: the name `{name}` is part of Rust's standard library\n\
305 It is recommended to use a different name to avoid problems.",
306 );
307 }
308 if is_windows_reserved(name) {
309 eprintln!(
310 "⚠️ Warning: the name `{name}` is a reserved Windows filename\n\
311 This package will not work on Windows platforms.",
312 );
313 }
314 if is_non_ascii_name(name) {
315 eprintln!(
316 "⚠️ Warning: the name `{name}` contains non-ASCII characters\n\
317 Non-ASCII crate names are not supported by Rust.",
318 );
319 }
320 let name_in_lowercase = name.to_lowercase();
321 if name != name_in_lowercase {
322 eprintln!(
323 "⚠️ Warning: the name `{name}` is not snake_case or kebab-case which is recommended for package names, consider `{name_in_lowercase}`"
324 );
325 }
326
327 Ok(())
328 }
329
330 // Based on: https://github.com/rust-lang/cargo/blob/7b7af3077bff8d60b7f124189bc9de227d3063a9/crates/cargo-util-schemas/src/restricted_names.rs#L42
331 fn validate_package_name(name: &str) -> anyhow::Result<()> {
332 if name.is_empty() {
333 anyhow::bail!("Package names cannot be empty");
334 }
335
336 let mut chars = name.chars();
337 if let Some(ch) = chars.next() {
338 if ch.is_ascii_digit() {
339 // A specific error for a potentially common case.
340 anyhow::bail!("Package names cannot start with a digit");
341 }
342 if !(unicode_xid::UnicodeXID::is_xid_start(ch) || ch == '_') {
343 anyhow::bail!(
344 "the first character must be a Unicode XID start character (most letters or `_`)"
345 );
346 }
347 }
348 for ch in chars {
349 if !(unicode_xid::UnicodeXID::is_xid_continue(ch) || ch == '-') {
350 anyhow::bail!(
351 "characters must be Unicode XID characters (numbers, `-`, `_`, or most letters)"
352 );
353 }
354 }
355 Ok(())
356 }
357
358 // The following functions are based on https://github.com/rust-lang/cargo/blob/e975158c1b542aa3833fd8584746538c17a6ae55/src/cargo/util/restricted_names.rs
359
360 /// Returns `true` if the name contains non-ASCII characters.
361 pub fn is_non_ascii_name(name: &str) -> bool {
362 name.chars().any(|ch| ch > '\x7f')
363 }
364
365 /// A Rust keyword.
366 pub fn is_keyword(name: &str) -> bool {
367 // See https://doc.rust-lang.org/reference/keywords.html
368 [
369 "Self", "abstract", "as", "async", "await", "become", "box", "break", "const",
370 "continue", "crate", "do", "dyn", "else", "enum", "extern", "false", "final", "fn",
371 "for", "if", "impl", "in", "let", "loop", "macro", "match", "mod", "move", "mut",
372 "override", "priv", "pub", "ref", "return", "self", "static", "struct", "super",
373 "trait", "true", "try", "type", "typeof", "unsafe", "unsized", "use", "virtual",
374 "where", "while", "yield",
375 ]
376 .contains(&name)
377 }
378
379 /// These names cannot be used on Windows, even with an extension.
380 pub fn is_windows_reserved(name: &str) -> bool {
381 [
382 "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7",
383 "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
384 ]
385 .contains(&name.to_ascii_lowercase().as_str())
386 }
387
388 /// An artifact with this name will conflict with one of Cargo's build directories.
389 pub fn is_conflicting_artifact_name(name: &str) -> bool {
390 ["deps", "examples", "build", "incremental"].contains(&name)
391 }
392 }