1use anyhow::{Context, Result};
13use std::path::Path;
14
15pub fn generate_item(
19 name: &str,
20 dir: &Path,
21 kind: &str,
22 template: &str,
23 extra_replacements: &[(&str, &str)],
24) -> Result<()> {
25 validate_identifier(name)?;
26 let mod_name = to_snake_case(name);
27 let mut content = template.replace("__NAME__", name);
28 for (placeholder, value) in extra_replacements {
29 content = content.replace(placeholder, value);
30 }
31 generate_file(dir, &mod_name, kind, &content, Some(name))
32}
33
34pub fn generate_file(
41 dir: &Path,
42 mod_name: &str,
43 kind: &str,
44 content: &str,
45 export: Option<&str>,
46) -> Result<()> {
47 anyhow::ensure!(
48 dir.is_dir(),
49 "no {} directory found here (run this from a Larust app's root)",
50 dir.display()
51 );
52
53 let path = dir.join(format!("{mod_name}.rs"));
54 anyhow::ensure!(
55 !path.exists(),
56 "a {kind} already exists at {}",
57 path.display()
58 );
59
60 std::fs::write(&path, content).with_context(|| format!("writing {}", path.display()))?;
61
62 if let Err(err) = append_to_mod_rs(&dir.join("mod.rs"), mod_name, export) {
63 let _ = std::fs::remove_file(&path);
67 return Err(err);
68 }
69
70 println!("Created {kind}: {}", path.display());
71 Ok(())
72}
73
74pub fn generate_nested_file(
84 root: &Path,
85 path_segments: &[String],
86 mod_name: &str,
87 kind: &str,
88 content: &str,
89 export: Option<&str>,
90) -> Result<()> {
91 let mut dir = root.to_path_buf();
92 for segment in path_segments {
93 let parent_mod_rs = dir.join("mod.rs");
94 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
95 append_to_mod_rs(&parent_mod_rs, segment, None)?;
96 dir = dir.join(segment);
97 }
98 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
99 generate_file(&dir, mod_name, kind, content, export)
100}
101
102pub fn append_to_mod_rs(mod_path: &Path, mod_name: &str, export: Option<&str>) -> Result<()> {
108 let mut existing = std::fs::read_to_string(mod_path).unwrap_or_default();
109 let mod_line = format!("pub mod {mod_name};");
110 if existing.contains(&mod_line) {
111 return Ok(());
112 }
113
114 if !existing.is_empty() && !existing.ends_with('\n') {
115 existing.push('\n');
116 }
117 existing.push_str(&mod_line);
118 existing.push('\n');
119 if let Some(export) = export {
120 existing.push_str(&format!("\npub use {mod_name}::{export};\n"));
121 }
122
123 std::fs::write(mod_path, existing).with_context(|| format!("writing {}", mod_path.display()))
124}
125
126const RUST_KEYWORDS: &[&str] = &[
133 "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
134 "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
135 "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where",
136 "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "macro",
137 "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
138];
139
140pub(crate) fn is_rust_keyword(name: &str) -> bool {
150 let snake = to_snake_case(name);
151 RUST_KEYWORDS.iter().any(|kw| *kw == name || *kw == snake)
152}
153
154pub fn validate_identifier(name: &str) -> Result<()> {
160 let mut chars = name.chars();
161 let starts_ok = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_');
162 let rest_ok = chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
163 anyhow::ensure!(
164 starts_ok && rest_ok,
165 "invalid name `{name}`: must be a valid Rust identifier (letters, digits, underscore; can't start with a digit)"
166 );
167 anyhow::ensure!(
168 !(name.starts_with("__") && name.ends_with("__")),
169 "invalid name `{name}`: names shaped like `__WORD__` collide with this generator's own template placeholders"
170 );
171
172 let snake = to_snake_case(name);
173 if let Some(keyword) = RUST_KEYWORDS
174 .iter()
175 .find(|kw| **kw == name || **kw == snake)
176 {
177 anyhow::bail!(
178 "invalid name `{name}`: `{keyword}` is a Rust keyword and can't be used as a generated identifier"
179 );
180 }
181
182 Ok(())
183}
184
185pub fn to_snake_case(name: &str) -> String {
187 let mut result = String::with_capacity(name.len() + 4);
188 for (i, c) in name.chars().enumerate() {
189 if c.is_uppercase() {
190 if i != 0 {
191 result.push('_');
192 }
193 result.extend(c.to_lowercase());
194 } else {
195 result.push(c);
196 }
197 }
198 result
199}
200
201pub fn pluralize(word: &str) -> String {
207 let preceded_by_vowel = word
210 .len()
211 .checked_sub(2)
212 .and_then(|i| word.as_bytes().get(i))
213 .is_some_and(|b| matches!(b, b'a' | b'e' | b'i' | b'o' | b'u'));
214 if word.ends_with('y') && !preceded_by_vowel {
215 format!("{}ies", &word[..word.len() - 1])
216 } else if word.ends_with("ss")
217 || word.ends_with('x')
218 || word.ends_with('z')
219 || word.ends_with("ch")
220 || word.ends_with("sh")
221 {
222 format!("{word}es")
223 } else if word.ends_with('s') {
224 word.to_string()
243 } else {
244 format!("{word}s")
245 }
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251
252 #[test]
253 fn validate_identifier_accepts_pascal_case() {
254 assert!(validate_identifier("PostController").is_ok());
255 assert!(validate_identifier("_Leading").is_ok());
256 }
257
258 #[test]
259 fn validate_identifier_rejects_invalid_names() {
260 assert!(validate_identifier("").is_err());
261 assert!(validate_identifier("Foo Bar").is_err());
262 assert!(validate_identifier("123Foo").is_err());
263 assert!(validate_identifier("Foo-Bar").is_err());
264 }
265
266 #[test]
267 fn validate_identifier_rejects_keywords_used_directly() {
268 assert!(validate_identifier("type").is_err());
269 assert!(validate_identifier("self").is_err());
270 assert!(validate_identifier("Self").is_err());
271 }
272
273 #[test]
274 fn validate_identifier_rejects_names_that_snake_case_into_a_keyword() {
275 assert!(validate_identifier("Type").is_err());
276 assert!(validate_identifier("Move").is_err());
277 assert!(validate_identifier("Use").is_err());
278 }
279
280 #[test]
281 fn validate_identifier_rejects_names_shaped_like_a_template_placeholder() {
282 assert!(validate_identifier("__NAME__").is_err());
283 assert!(validate_identifier("__USER__").is_err());
284 }
285
286 #[test]
287 fn to_snake_case_converts_pascal_case() {
288 assert_eq!(to_snake_case("PostController"), "post_controller");
289 assert_eq!(to_snake_case("Post"), "post");
290 }
291
292 #[test]
293 fn pluralize_handles_common_cases() {
294 assert_eq!(pluralize("post"), "posts");
295 assert_eq!(pluralize("category"), "categories");
296 assert_eq!(pluralize("box"), "boxes");
297 assert_eq!(pluralize("class"), "classes");
298 assert_eq!(pluralize("day"), "days");
299 }
300
301 #[test]
302 fn pluralize_treats_a_word_already_ending_in_a_bare_s_as_already_plural() {
303 assert_eq!(pluralize("blogs"), "blogs");
312 assert_eq!(pluralize("terms"), "terms");
313 assert_eq!(pluralize("bus"), "bus");
314 }
315
316 #[test]
317 fn generate_file_cleans_up_orphaned_rs_file_if_mod_rs_write_fails() {
318 let tmp = tempfile::tempdir().unwrap();
319 let dir = tmp.path();
320 let mod_path = dir.join("mod.rs");
321 std::fs::write(&mod_path, "").unwrap();
322
323 let original_perms = std::fs::metadata(&mod_path).unwrap().permissions();
324 let mut readonly_perms = original_perms.clone();
325 readonly_perms.set_readonly(true);
326 std::fs::set_permissions(&mod_path, readonly_perms).unwrap();
327
328 let result = generate_file(dir, "thing", "widget", "pub struct Thing;\n", Some("Thing"));
329
330 std::fs::set_permissions(&mod_path, original_perms).unwrap();
331
332 assert!(result.is_err());
333 assert!(
334 !dir.join("thing.rs").exists(),
335 "orphaned .rs file should be cleaned up when registering it in mod.rs fails"
336 );
337 }
338
339 #[test]
340 fn generate_nested_file_creates_every_intermediate_directory_and_mod_rs() {
341 let tmp = tempfile::tempdir().unwrap();
342 let root = tmp.path();
343 std::fs::write(root.join("mod.rs"), "").unwrap();
344
345 generate_nested_file(
346 root,
347 &["pages".to_string(), "webservices".to_string()],
348 "compare",
349 "widget",
350 "pub struct Compare;\n",
351 Some("Compare"),
352 )
353 .unwrap();
354
355 assert!(root.join("pages/webservices/compare.rs").exists());
356 assert_eq!(
357 std::fs::read_to_string(root.join("mod.rs")).unwrap(),
358 "pub mod pages;\n"
359 );
360 assert_eq!(
361 std::fs::read_to_string(root.join("pages/mod.rs")).unwrap(),
362 "pub mod webservices;\n"
363 );
364 let leaf_mod = std::fs::read_to_string(root.join("pages/webservices/mod.rs")).unwrap();
365 assert!(leaf_mod.contains("pub mod compare;"));
366 assert!(leaf_mod.contains("pub use compare::Compare;"));
367 }
368
369 #[test]
370 fn generate_nested_file_with_no_segments_behaves_like_generate_file() {
371 let tmp = tempfile::tempdir().unwrap();
372 let root = tmp.path();
373 std::fs::write(root.join("mod.rs"), "").unwrap();
374
375 generate_nested_file(
376 root,
377 &[],
378 "home",
379 "widget",
380 "pub struct Home;\n",
381 Some("Home"),
382 )
383 .unwrap();
384
385 assert!(root.join("home.rs").exists());
386 let mod_rs = std::fs::read_to_string(root.join("mod.rs")).unwrap();
387 assert!(mod_rs.contains("pub mod home;"));
388 }
389
390 #[test]
391 fn generate_nested_file_is_idempotent_across_siblings_sharing_a_directory() {
392 let tmp = tempfile::tempdir().unwrap();
393 let root = tmp.path();
394 std::fs::write(root.join("mod.rs"), "").unwrap();
395
396 generate_nested_file(
397 root,
398 &["pages".to_string()],
399 "blog",
400 "widget",
401 "pub struct Blog;\n",
402 Some("Blog"),
403 )
404 .unwrap();
405 generate_nested_file(
406 root,
407 &["pages".to_string()],
408 "about",
409 "widget",
410 "pub struct About;\n",
411 Some("About"),
412 )
413 .unwrap();
414
415 let mod_rs = std::fs::read_to_string(root.join("mod.rs")).unwrap();
419 assert_eq!(mod_rs.matches("pub mod pages;").count(), 1);
420 let pages_mod = std::fs::read_to_string(root.join("pages/mod.rs")).unwrap();
421 assert!(pages_mod.contains("pub mod blog;"));
422 assert!(pages_mod.contains("pub mod about;"));
423 }
424}