From 9fd1181497b366f033e18edafe1921b0f893e400 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 19:10:58 -0500 Subject: [PATCH 1/4] feat(wire): create @Module key if absent + createApp modules target Signed-off-by: Diego Resendez --- src/wire.rs | 183 +++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 144 insertions(+), 39 deletions(-) diff --git a/src/wire.rs b/src/wire.rs index 35c5a4a..1e2f33a 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -162,27 +162,69 @@ fn find_named_imports<'a>(root: &Node<'a>, src: &str, from: &str) -> Option Option { let tree = parser().parse(src, None).unwrap(); - let (open, close, existing) = find_array(&tree.root_node(), src, key)?; - if existing.split(',').map(str::trim).any(|s| s == symbol) { - return Some(src.to_string()); // idempotent + let root = tree.root_node(); + let object = find_module_object(&root, src)?; + insert_into_object_array(src, object, key, symbol) +} + +/// Inserts `symbol` into the `modules` array of the first `createApp(...)` +/// call's argument object (creating the `modules` key if absent). Idempotent; +/// reverts (returns `None`) on parse breakage or when no `createApp(...)` call +/// with an object argument is found. +// Not yet called outside this module's tests — the `matcha create module` +// generator that wires it in lands in the next task. +#[allow(dead_code)] +pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option { + let tree = parser().parse(src, None).unwrap(); + let root = tree.root_node(); + let object = find_createapp_object(&root, src)?; + insert_into_object_array(src, object, "modules", symbol) +} + +/// Inserts `symbol` into the `key: [...]` array directly inside `object` +/// (an object-literal node). If that `key` pair is absent, a new +/// `key: [symbol]` pair is inserted into the object. Idempotent; re-parses and +/// returns `None` on breakage. +fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> Option { + if let Some((open, close)) = find_key_array_span(object, src, key) { + let inner = &src[open + 1..close]; + if inner.split(',').map(str::trim).any(|s| s == symbol) { + return Some(src.to_string()); // idempotent + } + let joined = if inner.trim().is_empty() { + symbol.to_string() + } else { + format!("{}, {}", inner.trim_end().trim_end_matches(','), symbol) + }; + let mut out = String::with_capacity(src.len() + symbol.len() + 2); + out.push_str(&src[..open + 1]); + out.push_str(&joined); + out.push_str(&src[close..]); + return if parses_clean(&out) { Some(out) } else { None }; } - let inner = &src[open + 1..close]; // between [ ] - let joined = if inner.trim().is_empty() { - symbol.to_string() + + // key absent → create `key: [symbol]` inside the object, before its '}' + let obj_open = object.start_byte(); + let obj_close = object.end_byte() - 1; // the '}' + let existing = src[obj_open + 1..obj_close].trim(); + let pair = format!("{key}: [{symbol}]"); + let new_inner = if existing.is_empty() { + format!(" {pair} ") } else { - format!("{}, {}", inner.trim_end().trim_end_matches(','), symbol) + format!(" {}, {pair} ", existing.trim_end_matches(',')) }; - let mut out = String::with_capacity(src.len() + symbol.len() + 2); - out.push_str(&src[..open + 1]); - out.push_str(&joined); - out.push_str(&src[close..]); + let mut out = String::with_capacity(src.len() + pair.len() + 4); + out.push_str(&src[..obj_open + 1]); + out.push_str(&new_inner); + out.push_str(&src[obj_close..]); if parses_clean(&out) { Some(out) } else { @@ -190,18 +232,11 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option } } -/// Returns `(open_bracket_byte, close_bracket_byte, inner_text)` for the -/// `key: [...]` pair found directly inside the first `@Module({...})` -/// decorator's argument object. Unscoped searches over the whole tree would -/// risk matching a same-named key in an unrelated object literal (e.g. a -/// nested `providers:`/`controllers:` array inside `imports: [X.register({ -/// ... })]`, or a decoy object literal elsewhere in the file) — scoping to -/// the `@Module(...)` object's own pairs avoids that. -fn find_array(root: &Node, src: &str, key: &str) -> Option<(usize, usize, String)> { - let module_object = find_module_object(root, src)?; - - let mut c = module_object.walk(); - for child in module_object.named_children(&mut c) { +/// Returns `(open_bracket_byte, close_bracket_byte)` of the `key: [...]` array +/// among `object`'s direct `pair` children, or `None` if absent. +fn find_key_array_span(object: Node, src: &str, key: &str) -> Option<(usize, usize)> { + let mut c = object.walk(); + for child in object.named_children(&mut c) { if child.kind() != "pair" { continue; } @@ -217,14 +252,43 @@ fn find_array(root: &Node, src: &str, key: &str) -> Option<(usize, usize, String if v.kind() != "array" { continue; } - let open = v.start_byte(); - let close = v.end_byte() - 1; // the ']' - let inner = src[open + 1..close].to_string(); - return Some((open, close, inner)); + return Some((v.start_byte(), v.end_byte() - 1)); } None } +/// Locates the argument object literal of the first `createApp(...)` call +/// expression (function identifier `createApp`), in source order. +fn find_createapp_object<'a>(root: &Node<'a>, src: &str) -> Option> { + fn visit<'a>(node: Node<'a>, src: &str) -> Option> { + if node.kind() == "call_expression" { + let is_createapp = node + .child_by_field_name("function") + .filter(|f| f.kind() == "identifier") + .and_then(|f| f.utf8_text(src.as_bytes()).ok()) + == Some("createApp"); + if is_createapp { + if let Some(args) = node.child_by_field_name("arguments") { + let mut ac = args.walk(); + for child in args.named_children(&mut ac) { + if child.kind() == "object" { + return Some(child); + } + } + } + } + } + let mut c = node.walk(); + for child in node.children(&mut c) { + if let Some(r) = visit(child, src) { + return Some(r); + } + } + None + } + visit(*root, src) +} + /// Inserts `method_src` immediately before the closing `}` of `class /// `'s body. Returns `None` — leaving the caller's original text /// untouched — when the edited text fails to re-parse clean, or when no @@ -347,7 +411,11 @@ export class AppModule {} #[test] fn broken_result_is_rejected() { - // key missing entirely → our splice can't find it → None, file untouched upstream + // Predates create-if-absent: `providers` used to be missing entirely, + // so the old `find_array` couldn't locate it → None. Now the key is + // created instead, so either outcome is accepted here; the dedicated + // `creates_providers_key_and_reverts_on_break` test above covers the + // create-if-absent behavior explicitly. assert!( add_to_module_array(MOD, "providers", "X").is_none() || add_to_module_array(MOD, "providers", "X") @@ -356,12 +424,11 @@ export class AppModule {} ); } - /// Extra coverage beyond the brief: `broken_result_is_rejected` above only - /// exercises the "key not found" `None` path (via `find_array`). This - /// exercises the *other* `None` path — a splice that finds the array but - /// produces text that no longer parses clean — proving the revert-on-ERROR - /// guarantee (`parses_clean` check in `add_to_module_array`) is real, not - /// just theoretically reachable. + /// Extra coverage beyond the brief: this exercises the `None` path where + /// `insert_into_object_array` finds (or creates) the target but the + /// splice produces text that no longer parses clean — proving the + /// revert-on-ERROR guarantee (`parses_clean` check) is real, not just + /// theoretically reachable. #[test] fn revert_on_actual_parse_error() { // A "symbol" containing stray syntax breaks the array/object/class @@ -426,4 +493,42 @@ export class AppModule {} let out = add_import(src, "Sse", "@green-tea/core"); assert!(out.contains("import { Sse } from '@green-tea/core';")); } + + #[test] + fn creates_steps_key_when_absent() { + // MOD has only `controllers` — adding a step must CREATE `steps: [...]` + let out = add_to_module_array(MOD, "steps", "PasitoStep").unwrap(); + assert!(out.contains("steps: [PasitoStep]")); + assert!(out.contains("controllers: [HomeController]")); // untouched + // idempotent + assert_eq!( + add_to_module_array(&out, "steps", "PasitoStep").unwrap(), + out + ); + } + + #[test] + fn creates_providers_key_and_reverts_on_break() { + let out = add_to_module_array(MOD, "providers", "ConfigProvider").unwrap(); + assert!(out.contains("providers: [ConfigProvider]")); + // a symbol with stray syntax must still be rejected (revert guard) + assert!(add_to_module_array(MOD, "providers", "X]; class Evil {").is_none()); + } + + const MAIN: &str = "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nconst app = createApp({ modules: [AppModule] });\n"; + + #[test] + fn adds_module_to_createapp() { + let out = add_to_createapp_modules(MAIN, "UsersModule").unwrap(); + assert!(out.contains("AppModule, UsersModule")); + assert_eq!(add_to_createapp_modules(&out, "UsersModule").unwrap(), out); + // idempotent + } + + #[test] + fn createapp_creates_modules_key_when_absent() { + let src = "const app = createApp({});\n"; + let out = add_to_createapp_modules(src, "AppModule").unwrap(); + assert!(out.contains("modules: [AppModule]")); + } } -- 2.54.1 From 3066cc477eb5d5ee4c8fa0aaea672b8ba35caa07 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 19:14:16 -0500 Subject: [PATCH 2/4] feat(create): implement step, provider, and module generators Signed-off-by: Diego Resendez --- src/cli.rs | 2 +- src/cmd_create.rs | 140 ++++++++++++++++++++++++++++++++++++---------- tests/create.rs | 54 ++++++++++++++++++ 3 files changed, 166 insertions(+), 30 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index acddbf9..5e127a4 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -21,7 +21,7 @@ pub enum Command { Run, /// Generate a piece and auto-wire it into the module Create { - #[arg(value_parser = ["module", "controller", "step"])] + #[arg(value_parser = ["module", "controller", "step", "provider"])] kind: String, name: String, #[arg(long)] diff --git a/src/cmd_create.rs b/src/cmd_create.rs index fd0f22f..ef3b3df 100644 --- a/src/cmd_create.rs +++ b/src/cmd_create.rs @@ -1,33 +1,42 @@ //! `matcha create ` — generate a stub file for `` and //! auto-wire it into `src/app.module.ts` via the pure text-editing helpers //! in `wire`. -//! -//! `module` and `step` are intentionally stubbed as "not implemented yet" -//! for v1 — they will reuse the same `wire` primitives as `controller` in a -//! fast follow. use std::io::{Error, ErrorKind}; use std::path::Path; use crate::wire; -fn controller_stub(name: &str) -> String { - format!( - "import {{ Route, Get }} from '@green-tea/core';\n\n\ -@Route('/{lower}')\nexport class {name}Controller {{\n \ -@Get('/')\n list() {{\n return [];\n }}\n}}\n", - lower = name.to_lowercase(), - name = name - ) -} - pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> { match kind { - "controller" => create_controller(name, check), - "module" | "step" => Err(Error::new( - ErrorKind::Unsupported, - format!("create {kind} not implemented yet"), - )), + "controller" => create_piece( + name, + check, + "controllers", + "controller", + "Controller", + "controllers", + controller_stub(name), + ), + "step" => create_piece( + name, + check, + "steps", + "step", + "Step", + "steps", + step_stub(name), + ), + "provider" => create_piece( + name, + check, + "providers", + "provider", + "Provider", + "providers", + provider_stub(name), + ), + "module" => create_module(name, check), other => Err(Error::new( ErrorKind::InvalidInput, format!("unknown kind {other}"), @@ -35,32 +44,78 @@ pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> { } } -fn create_controller(name: &str, check: bool) -> std::io::Result<()> { - let file = Path::new("src/controllers").join(format!("{}.controller.ts", name.to_lowercase())); +/// Writes a piece file under `src//` and wires it into the `@Module` +/// in `src/app.module.ts` (`module_key` array). Emit-only + hint on failure. +#[allow(clippy::too_many_arguments)] +fn create_piece( + name: &str, + check: bool, + subdir: &str, + ext: &str, + suffix: &str, + module_key: &str, + stub: String, +) -> std::io::Result<()> { + let lower = name.to_lowercase(); + let file = Path::new("src") + .join(subdir) + .join(format!("{lower}.{ext}.ts")); std::fs::create_dir_all(file.parent().unwrap())?; - std::fs::write(&file, controller_stub(name))?; + std::fs::write(&file, stub)?; println!("✓ {}", file.display()); - let symbol = format!("{name}Controller"); - let from = format!("./controllers/{}.controller", name.to_lowercase()); + let symbol = format!("{name}{suffix}"); + let from = format!("./{subdir}/{lower}.{ext}"); let module_path = Path::new("src/app.module.ts"); if !module_path.exists() { println!("→ add {symbol} to your @Module manually (no src/app.module.ts found)"); - return Ok(()); + return maybe_check(check); } let src = std::fs::read_to_string(module_path)?; let imported = wire::add_import(&src, &symbol, &from); - match wire::add_to_module_array(&imported, "controllers", &symbol) { + match wire::add_to_module_array(&imported, module_key, &symbol) { Some(wired) => { std::fs::write(module_path, wired)?; println!("✓ wired {symbol} into AppModule"); } None => { - // agreed fallback: emit-only, do NOT corrupt the module - println!("→ could not auto-wire; add {symbol} to controllers[] in src/app.module.ts"); + println!("→ could not auto-wire; add {symbol} to {module_key}[] in src/app.module.ts") } } + maybe_check(check) +} +/// Writes `src/.module.ts` and registers it in the `createApp({ modules })` +/// call in `src/main.ts`. Emit-only + hint on failure. +fn create_module(name: &str, check: bool) -> std::io::Result<()> { + let lower = name.to_lowercase(); + let file = Path::new("src").join(format!("{lower}.module.ts")); + std::fs::create_dir_all(file.parent().unwrap())?; + std::fs::write(&file, module_stub(name))?; + println!("✓ {}", file.display()); + + let symbol = format!("{name}Module"); + let from = format!("./{lower}.module"); + let main_path = Path::new("src/main.ts"); + if !main_path.exists() { + println!("→ register {symbol} in createApp({{ modules }}) manually (no src/main.ts found)"); + return maybe_check(check); + } + let src = std::fs::read_to_string(main_path)?; + let imported = wire::add_import(&src, &symbol, &from); + match wire::add_to_createapp_modules(&imported, &symbol) { + Some(wired) => { + std::fs::write(main_path, wired)?; + println!("✓ registered {symbol} in createApp"); + } + None => println!( + "→ could not auto-register; add {symbol} to createApp modules[] in src/main.ts" + ), + } + maybe_check(check) +} + +fn maybe_check(check: bool) -> std::io::Result<()> { if check { match crate::check::run(Path::new(".")) { Ok(true) => println!("✓ type-check passed"), @@ -68,6 +123,33 @@ fn create_controller(name: &str, check: bool) -> std::io::Result<()> { Err(e) => println!("⚠ could not run type-check: {e}"), } } - Ok(()) } + +fn controller_stub(name: &str) -> String { + let lower = name.to_lowercase(); + format!( + "import {{ Route, Get }} from '@green-tea/core';\n\n@Route('/{lower}')\nexport class {name}Controller {{\n @Get('/')\n list() {{\n return [];\n }}\n}}\n" + ) +} + +fn step_stub(name: &str) -> String { + let lower = name.to_lowercase(); + format!( + "import {{ Step }} from '@green-tea/core';\n\n@Step({{ provides: '{lower}', needs: [] }})\nexport class {name}Step {{\n run(ctx: Record) {{\n return {{ {lower}: null }};\n }}\n}}\n" + ) +} + +fn provider_stub(name: &str) -> String { + let lower = name.to_lowercase(); + format!( + "import {{ Provider }} from '@green-tea/core';\n\n@Provider({{ provides: '{lower}' }})\nexport class {name}Provider {{\n provide() {{\n return {{ {lower}: null }};\n }}\n}}\n" + ) +} + +fn module_stub(name: &str) -> String { + let lower = name.to_lowercase(); + format!( + "import {{ Module }} from '@green-tea/core';\n\n@Module({{ mountpoint: '/{lower}', controllers: [], providers: [], steps: [] }})\nexport class {name}Module {{}}\n" + ) +} diff --git a/tests/create.rs b/tests/create.rs index cf202f4..0a853e1 100644 --- a/tests/create.rs +++ b/tests/create.rs @@ -30,3 +30,57 @@ fn create_controller_writes_and_wires() { assert!(module.contains("UsersController")); assert!(module.contains("import { UsersController }")); } + +#[test] +fn create_step_writes_and_wires() { + let d = tempdir().unwrap(); + seed_module(d.path()); // writes src/app.module.ts with `@Module({ controllers: [] })` + Command::cargo_bin("matcha") + .unwrap() + .current_dir(d.path()) + .args(["create", "step", "Pasito"]) + .assert() + .success(); + assert!(d.path().join("src/steps/pasito.step.ts").exists()); + let m = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap(); + assert!(m.contains("PasitoStep")); + assert!(m.contains("import { PasitoStep }")); + assert!(m.contains("steps: [PasitoStep]")); +} + +#[test] +fn create_provider_writes_and_wires() { + let d = tempdir().unwrap(); + seed_module(d.path()); + Command::cargo_bin("matcha") + .unwrap() + .current_dir(d.path()) + .args(["create", "provider", "Config"]) + .assert() + .success(); + assert!(d.path().join("src/providers/config.provider.ts").exists()); + let m = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap(); + assert!(m.contains("providers: [ConfigProvider]")); + assert!(m.contains("import { ConfigProvider }")); +} + +#[test] +fn create_module_writes_and_registers_in_createapp() { + let d = tempdir().unwrap(); + std::fs::create_dir_all(d.path().join("src")).unwrap(); + std::fs::write( + d.path().join("src/main.ts"), + "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nconst app = createApp({ modules: [AppModule] });\n", + ) + .unwrap(); + Command::cargo_bin("matcha") + .unwrap() + .current_dir(d.path()) + .args(["create", "module", "Users"]) + .assert() + .success(); + assert!(d.path().join("src/users.module.ts").exists()); + let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap(); + assert!(main.contains("AppModule, UsersModule")); + assert!(main.contains("import { UsersModule }")); +} -- 2.54.1 From 314bf3a4b0853f580fc8e8dd09f49fd4bf7f5555 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 19:16:09 -0500 Subject: [PATCH 3/4] chore(wire): drop stale dead_code allow on add_to_createapp_modules Signed-off-by: Diego Resendez --- src/wire.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/wire.rs b/src/wire.rs index 1e2f33a..56127e7 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -179,9 +179,6 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option /// call's argument object (creating the `modules` key if absent). Idempotent; /// reverts (returns `None`) on parse breakage or when no `createApp(...)` call /// with an object argument is found. -// Not yet called outside this module's tests — the `matcha create module` -// generator that wires it in lands in the next task. -#[allow(dead_code)] pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option { let tree = parser().parse(src, None).unwrap(); let root = tree.root_node(); -- 2.54.1 From 444567ffb30f15f7d1293dc1a3472739ce47e5c4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 19:20:53 -0500 Subject: [PATCH 4/4] fix(wire): refuse to create a duplicate key when the existing value isn't an array Signed-off-by: Diego Resendez --- src/wire.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/wire.rs b/src/wire.rs index 56127e7..b489e68 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -208,6 +208,14 @@ fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> return if parses_clean(&out) { Some(out) } else { None }; } + // The key exists but its value isn't an array literal (e.g. `controllers: SHARED` + // or `modules: MODULES`). Creating a second `key: [...]` pair parses clean yet + // silently shadows the user's value at runtime (JS keeps the last duplicate key), + // so `parses_clean` can't catch it. Refuse — the caller falls back to emit-only. + if object_has_key(object, src, key) { + return None; + } + // key absent → create `key: [symbol]` inside the object, before its '}' let obj_open = object.start_byte(); let obj_close = object.end_byte() - 1; // the '}' @@ -229,6 +237,24 @@ fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> } } +/// True when `object` has any direct `pair` child whose key text equals `key`, +/// regardless of the value's kind. Used to avoid creating a duplicate key when +/// an existing pair's value isn't an array literal. +fn object_has_key(object: Node, src: &str, key: &str) -> bool { + let mut c = object.walk(); + for child in object.named_children(&mut c) { + if child.kind() == "pair" + && child + .child_by_field_name("key") + .and_then(|k| k.utf8_text(src.as_bytes()).ok()) + == Some(key) + { + return true; + } + } + false +} + /// Returns `(open_bracket_byte, close_bracket_byte)` of the `key: [...]` array /// among `object`'s direct `pair` children, or `None` if absent. fn find_key_array_span(object: Node, src: &str, key: &str) -> Option<(usize, usize)> { @@ -528,4 +554,18 @@ export class AppModule {} let out = add_to_createapp_modules(src, "AppModule").unwrap(); assert!(out.contains("modules: [AppModule]")); } + + #[test] + fn refuses_duplicate_key_when_module_value_not_array() { + // `controllers` exists but its value is an identifier, not an array literal. + // Adding must NOT create a second `controllers` pair (silent runtime shadowing). + let src = "@Module({ mountpoint: '/', controllers: SHARED })\nexport class AppModule {}\n"; + assert!(add_to_module_array(src, "controllers", "X").is_none()); + } + + #[test] + fn refuses_duplicate_modules_when_createapp_value_not_array() { + let src = "const app = createApp({ modules: MODULES });\n"; + assert!(add_to_createapp_modules(src, "UsersModule").is_none()); + } } -- 2.54.1