diff --git a/src/check.rs b/src/check.rs index 6327efc..1f542b8 100644 --- a/src/check.rs +++ b/src/check.rs @@ -1,18 +1,23 @@ -use std::path::Path; use crate::runtime::{self, Runtime}; +use std::path::Path; fn check_command(rt: Runtime) -> (&'static str, Vec<&'static str>) { match rt { Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]), - Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]), + Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]), Runtime::Node => ("npx", vec!["tsc", "--noEmit"]), } } pub fn run(dir: &Path) -> std::io::Result { - let Some(rt) = runtime::detect(dir) else { return Ok(true) }; // nothing to check against + let Some(rt) = runtime::detect(dir) else { + return Ok(true); + }; // nothing to check against let (prog, args) = check_command(rt); - let status = std::process::Command::new(prog).args(&args).current_dir(dir).status()?; + let status = std::process::Command::new(prog) + .args(&args) + .current_dir(dir) + .status()?; Ok(status.success()) } @@ -23,16 +28,25 @@ mod tests { #[test] fn deno_check_cmd() { - assert_eq!(check_command(Runtime::Deno), ("deno", vec!["check", "src/app.module.ts"])); + assert_eq!( + check_command(Runtime::Deno), + ("deno", vec!["check", "src/app.module.ts"]) + ); } #[test] fn node_uses_tsc_noemit() { - assert_eq!(check_command(Runtime::Node), ("npx", vec!["tsc", "--noEmit"])); + assert_eq!( + check_command(Runtime::Node), + ("npx", vec!["tsc", "--noEmit"]) + ); } #[test] fn bun_uses_bunx_tsc_noemit() { - assert_eq!(check_command(Runtime::Bun), ("bunx", vec!["tsc", "--noEmit"])); + assert_eq!( + check_command(Runtime::Bun), + ("bunx", vec!["tsc", "--noEmit"]) + ); } } diff --git a/src/cmd_add.rs b/src/cmd_add.rs index 8fc0076..12ae594 100644 --- a/src/cmd_add.rs +++ b/src/cmd_add.rs @@ -8,21 +8,31 @@ use std::path::PathBuf; use crate::wire; -/// Returns `(decorator symbol, method source)` for a known capability, or -/// `None` for an unrecognized one. -fn handler(cap: &str) -> Option<(&'static str, String)> { +/// Returns `(decorator symbol, method source, dedup marker)` for a known +/// capability, or `None` for an unrecognized one. +/// +/// The dedup marker is the route-path string literal baked into that +/// capability's `handler()` template (e.g. `'/events'`, `'/stream'`, +/// `'/data'`). It is unique per capability, unlike the decorator name — both +/// `buffer` and any pre-existing handler can legitimately use `@Get` — so +/// it's what `run` checks for before inserting, to keep `matcha add ` +/// idempotent per capability rather than per decorator. +fn handler(cap: &str) -> Option<(&'static str, String, &'static str)> { match cap { "sse" => Some(( "Sse", "\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(), + "'/events'", )), "stream" => Some(( "Stream", "\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(), + "'/stream'", )), "buffer" => Some(( "Get", "\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(), + "'/data'", )), _ => None, } @@ -38,8 +48,13 @@ fn only_controller() -> std::io::Result { .collect(); match hits.len() { 1 => Ok(hits.pop().unwrap()), - 0 => Err(Error::new(ErrorKind::NotFound, "no *.controller.ts in src/controllers")), - _ => Err(Error::other("multiple controllers; specify which (not yet supported)")), + 0 => Err(Error::new( + ErrorKind::NotFound, + "no *.controller.ts in src/controllers", + )), + _ => Err(Error::other( + "multiple controllers; specify which (not yet supported)", + )), } } @@ -54,23 +69,30 @@ fn class_name(src: &str) -> Option { } pub fn run(cap: &str) -> std::io::Result<()> { - let (decorator, method) = handler(cap) + let (decorator, method, marker) = handler(cap) .ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("unknown capability {cap}")))?; let path = only_controller()?; let src = std::fs::read_to_string(&path)?; let class = class_name(&src).ok_or_else(|| Error::other("no exported class found"))?; + if src.contains(marker) { + println!("→ {cap} already present in {class}"); + return Ok(()); + } + // wire::add_import merges `decorator` into an existing + // `import { ... } from '@green-tea/core';` brace when one is already + // present, rather than appending a second import line for the same + // module (which would be a duplicate ESM binding — a hard SyntaxError, + // not a harmless dupe). let with_import = wire::add_import(&src, decorator, "@green-tea/core"); - // add_import above assumes a fresh import line; if '@green-tea/core' is - // already imported under a shared brace, we still append a second import - // line for the new symbol — a duplicate named import is legal TS and tsc - // dedups at type level. Merging into the existing brace is deferred past - // v1; not worth tree-sitter surgery now. match wire::insert_method(&with_import, &class, &method) { Some(out) => { std::fs::write(&path, out)?; println!("✓ added @{decorator} to {class}"); } - None => println!("→ could not edit {}; add @{decorator} handler manually", path.display()), + None => println!( + "→ could not edit {}; add @{decorator} handler manually", + path.display() + ), } Ok(()) } diff --git a/src/cmd_create.rs b/src/cmd_create.rs index ada2ac4..fd0f22f 100644 --- a/src/cmd_create.rs +++ b/src/cmd_create.rs @@ -13,24 +13,30 @@ use crate::wire; fn controller_stub(name: &str) -> String { format!( -"import {{ Route, Get }} from '@green-tea/core';\n\n\ + "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) + 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"))), - other => Err(Error::new(ErrorKind::InvalidInput, format!("unknown kind {other}"))), + "module" | "step" => Err(Error::new( + ErrorKind::Unsupported, + format!("create {kind} not implemented yet"), + )), + other => Err(Error::new( + ErrorKind::InvalidInput, + format!("unknown kind {other}"), + )), } } fn create_controller(name: &str, check: bool) -> std::io::Result<()> { - let file = Path::new("src/controllers") - .join(format!("{}.controller.ts", name.to_lowercase())); + let file = Path::new("src/controllers").join(format!("{}.controller.ts", name.to_lowercase())); std::fs::create_dir_all(file.parent().unwrap())?; std::fs::write(&file, controller_stub(name))?; println!("✓ {}", file.display()); diff --git a/src/cmd_new.rs b/src/cmd_new.rs index e9b5786..4d0072d 100644 --- a/src/cmd_new.rs +++ b/src/cmd_new.rs @@ -6,8 +6,10 @@ use crate::template; pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> { let dest = Path::new(name); if dest.exists() { - return Err(Error::new(ErrorKind::AlreadyExists, - format!("'{name}' already exists"))); + return Err(Error::new( + ErrorKind::AlreadyExists, + format!("'{name}' already exists"), + )); } match template_url { @@ -46,12 +48,16 @@ mod tests { use super::*; #[test] fn gh_shorthand_expands() { - assert_eq!(resolve_url("gh:green-tea/tmpl"), - "https://github.com/green-tea/tmpl"); + assert_eq!( + resolve_url("gh:green-tea/tmpl"), + "https://github.com/green-tea/tmpl" + ); } #[test] fn full_url_passes_through() { - assert_eq!(resolve_url("https://example.com/x.git"), - "https://example.com/x.git"); + assert_eq!( + resolve_url("https://example.com/x.git"), + "https://example.com/x.git" + ); } } diff --git a/src/cmd_run.rs b/src/cmd_run.rs index 35b3686..28cb2df 100644 --- a/src/cmd_run.rs +++ b/src/cmd_run.rs @@ -12,13 +12,18 @@ fn command_for(rt: Runtime) -> (&'static str, Vec<&'static str>) { } pub fn run(dir: &Path) -> std::io::Result<()> { - let rt = runtime::detect(dir).ok_or_else(|| Error::new( - ErrorKind::NotFound, - "no runtime detected (need deno.json, bun.lock, or package.json)", - ))?; + let rt = runtime::detect(dir).ok_or_else(|| { + Error::new( + ErrorKind::NotFound, + "no runtime detected (need deno.json, bun.lock, or package.json)", + ) + })?; let (prog, args) = command_for(rt); println!("→ {prog} {}", args.join(" ")); - let status = std::process::Command::new(prog).args(&args).current_dir(dir).status()?; + let status = std::process::Command::new(prog) + .args(&args) + .current_dir(dir) + .status()?; std::process::exit(status.code().unwrap_or(1)); } @@ -33,7 +38,10 @@ mod tests { } #[test] fn bun_watch() { - assert_eq!(command_for(Runtime::Bun), ("bun", vec!["--watch", "run", "dev"])); + assert_eq!( + command_for(Runtime::Bun), + ("bun", vec!["--watch", "run", "dev"]) + ); } #[test] fn node_watch() { diff --git a/src/wire.rs b/src/wire.rs index 38709c7..35c5a4a 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -30,7 +30,6 @@ fn parser() -> Parser { /// True when tree-sitter parses `src` with no `ERROR`/missing node anywhere /// in the tree. Used as the revert-on-breakage guarantee: if an edit fails /// this check, the caller must discard it. -#[allow(dead_code)] fn parses_clean(src: &str) -> bool { let tree = parser().parse(src, None).unwrap(); !has_error(tree.root_node()) @@ -49,16 +48,60 @@ fn has_error(node: Node) -> bool { false } -/// Inserts `import { } from '';` after the last top-level -/// import statement. No-op (returns `src` unchanged) if the exact import -/// line is already present, making repeated calls idempotent. +/// Wires `symbol` into `src`'s imports from module `from`: +/// +/// 1. If an `import { ... } from '';` statement already exists, merge +/// `symbol` into its named-imports brace (`{ A, B } ` → `{ A, B, symbol }`) +/// instead of appending a second, colliding `import` line for the same +/// module (a duplicate ESM binding is a hard `SyntaxError`/`TS2300`, not a +/// harmless dupe). Idempotent: a repeat call with `symbol` already present +/// in that brace returns `src` unchanged. +/// 2. Otherwise, appends `import { } from '';` after the last +/// top-level import statement (original behavior, for a module that isn't +/// imported yet at all). +/// +/// The brace-merge edit is re-parsed with [`parses_clean`] before being +/// accepted; if merging somehow produces broken text, this falls back to +/// appending a fresh import line rather than returning broken source. pub fn add_import(src: &str, symbol: &str, from: &str) -> String { + let tree = parser().parse(src, None).unwrap(); + let root = tree.root_node(); + + if let Some(named_imports) = find_named_imports(&root, src, from) { + let mut c = named_imports.walk(); + let already_present = named_imports.named_children(&mut c).any(|spec| { + spec.kind() == "import_specifier" + && spec + .child_by_field_name("name") + .and_then(|n| n.utf8_text(src.as_bytes()).ok()) + == Some(symbol) + }); + if already_present { + return src.to_string(); + } + let open = named_imports.start_byte(); + let close = named_imports.end_byte() - 1; // the '}' + let inner = src[open + 1..close].trim().trim_end_matches(',').trim_end(); + let joined = if inner.is_empty() { + format!(" {symbol} ") + } else { + format!(" {inner}, {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..]); + if parses_clean(&out) { + return out; + } + // Merge produced broken text (shouldn't normally happen) — fall + // through to the append-a-new-line path below rather than return it. + } + let line = format!("import {{ {symbol} }} from '{from}';"); if src.contains(&line) { return src.to_string(); } - let tree = parser().parse(src, None).unwrap(); - let root = tree.root_node(); let mut last_end = 0usize; let mut c = root.walk(); for child in root.children(&mut c) { @@ -77,6 +120,47 @@ pub fn add_import(src: &str, symbol: &str, from: &str) -> String { out } +/// Finds the `named_imports` (`{ A, B, C }`) brace of the top-level `import +/// { ... } from '';` statement whose module specifier string literal +/// equals `from` exactly. Returns `None` when no import statement has that +/// source, or when the matching statement has no named-imports clause at all +/// (e.g. a bare default import) — callers treat that as "can't merge, fall +/// back to appending a new line". +fn find_named_imports<'a>(root: &Node<'a>, src: &str, from: &str) -> Option> { + let mut c = root.walk(); + for stmt in root.children(&mut c) { + if stmt.kind() != "import_statement" { + continue; + } + let Some(source) = stmt.child_by_field_name("source") else { + continue; + }; + let Ok(raw) = source.utf8_text(src.as_bytes()) else { + continue; + }; + let unquoted = raw + .strip_prefix(['\'', '"']) + .and_then(|s| s.strip_suffix(['\'', '"'])) + .unwrap_or(raw); + if unquoted != from { + continue; + } + let mut sc = stmt.walk(); + for clause in stmt.children(&mut sc) { + if clause.kind() != "import_clause" { + continue; + } + let mut cc = clause.walk(); + for named in clause.children(&mut cc) { + if named.kind() == "named_imports" { + return Some(named); + } + } + } + } + None +} + /// Finds the `key: [ ... ]` array inside the first `@Module({...})` and /// inserts `symbol` into it. Idempotent: a repeat call that would insert an /// already-present symbol is a no-op. Returns `None` — leaving the caller's @@ -226,7 +310,9 @@ fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option> { let call = find_decorator_call(*root, src)?; let args = call.child_by_field_name("arguments")?; let mut ac = args.walk(); - let object = args.named_children(&mut ac).find(|&child| child.kind() == "object"); + let object = args + .named_children(&mut ac) + .find(|&child| child.kind() == "object"); object } @@ -264,7 +350,9 @@ export class AppModule {} // key missing entirely → our splice can't find it → None, file untouched upstream assert!( add_to_module_array(MOD, "providers", "X").is_none() - || add_to_module_array(MOD, "providers", "X").unwrap().contains("providers") + || add_to_module_array(MOD, "providers", "X") + .unwrap() + .contains("providers") ); } @@ -317,4 +405,25 @@ export class AppModule {} let src = "export class HomeController {\n home() {}\n}\n"; assert!(insert_method(src, "NotHere", " zen() {}\n").is_none()); } + + #[test] + fn add_import_merges_into_existing_brace() { + let src = "import { Route, Get, Html, Sse } from '@green-tea/core';\n\nexport class C {}\n"; + let out = add_import(src, "Stream", "@green-tea/core"); + assert!(out.contains("Stream")); + assert_eq!(out.matches("from '@green-tea/core'").count(), 1); // NO duplicate import line + } + + #[test] + fn add_import_merge_idempotent_when_symbol_present() { + let src = "import { Route, Sse } from '@green-tea/core';\nexport class C {}\n"; + assert_eq!(add_import(src, "Sse", "@green-tea/core"), src); + } + + #[test] + fn add_import_new_line_when_module_absent() { + let src = "export class C {}\n"; + let out = add_import(src, "Sse", "@green-tea/core"); + assert!(out.contains("import { Sse } from '@green-tea/core';")); + } } diff --git a/tests/add.rs b/tests/add.rs index f093b20..2e11c5e 100644 --- a/tests/add.rs +++ b/tests/add.rs @@ -5,13 +5,19 @@ use tempfile::tempdir; fn add_sse_appends_handler() { let d = tempdir().unwrap(); std::fs::create_dir_all(d.path().join("src/controllers")).unwrap(); - std::fs::write(d.path().join("src/controllers/home.controller.ts"), -"import { Route, Get } from '@green-tea/core';\n\n\ -@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n").unwrap(); + std::fs::write( + d.path().join("src/controllers/home.controller.ts"), + "import { Route, Get } from '@green-tea/core';\n\n\ +@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n", + ) + .unwrap(); - Command::cargo_bin("matcha").unwrap() + Command::cargo_bin("matcha") + .unwrap() .current_dir(d.path()) - .args(["add", "sse"]).assert().success(); + .args(["add", "sse"]) + .assert() + .success(); let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap(); assert!(out.contains("@Sse(")); @@ -22,9 +28,34 @@ fn add_sse_appends_handler() { fn add_errors_when_no_controller() { let d = tempdir().unwrap(); std::fs::create_dir_all(d.path().join("src/controllers")).unwrap(); - Command::cargo_bin("matcha").unwrap() + Command::cargo_bin("matcha") + .unwrap() .current_dir(d.path()) - .args(["add", "sse"]).assert().failure(); + .args(["add", "sse"]) + .assert() + .failure(); +} + +#[test] +fn add_sse_twice_is_idempotent() { + let d = tempdir().unwrap(); + std::fs::create_dir_all(d.path().join("src/controllers")).unwrap(); + std::fs::write(d.path().join("src/controllers/home.controller.ts"), +"import { Route, Get } from '@green-tea/core';\n\n@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n").unwrap(); + let run = || { + Command::cargo_bin("matcha") + .unwrap() + .current_dir(d.path()) + .args(["add", "sse"]) + .assert() + .success() + }; + run(); + run(); + let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap(); + // exactly one Sse handler, exactly one @green-tea/core import line + assert_eq!(out.matches("@Sse(").count(), 1); + assert_eq!(out.matches("from '@green-tea/core'").count(), 1); } #[test] @@ -36,10 +67,19 @@ fn add_errors_when_multiple_controllers_and_writes_nothing() { for n in ["a", "b"] { std::fs::write(cdir.join(format!("{n}.controller.ts")), original).unwrap(); } - Command::cargo_bin("matcha").unwrap() + Command::cargo_bin("matcha") + .unwrap() .current_dir(d.path()) - .args(["add", "sse"]).assert().failure(); + .args(["add", "sse"]) + .assert() + .failure(); // no file was modified - assert_eq!(std::fs::read_to_string(cdir.join("a.controller.ts")).unwrap(), original); - assert_eq!(std::fs::read_to_string(cdir.join("b.controller.ts")).unwrap(), original); + assert_eq!( + std::fs::read_to_string(cdir.join("a.controller.ts")).unwrap(), + original + ); + assert_eq!( + std::fs::read_to_string(cdir.join("b.controller.ts")).unwrap(), + original + ); } diff --git a/tests/cli.rs b/tests/cli.rs index 8547984..8147b92 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -3,14 +3,22 @@ use predicates::str::contains; #[test] fn help_lists_all_subcommands() { - Command::cargo_bin("matcha").unwrap() - .arg("--help").assert().success() - .stdout(contains("new")).stdout(contains("run")) - .stdout(contains("create")).stdout(contains("add")); + Command::cargo_bin("matcha") + .unwrap() + .arg("--help") + .assert() + .success() + .stdout(contains("new")) + .stdout(contains("run")) + .stdout(contains("create")) + .stdout(contains("add")); } #[test] fn new_requires_a_name() { - Command::cargo_bin("matcha").unwrap() - .arg("new").assert().failure(); // missing + Command::cargo_bin("matcha") + .unwrap() + .arg("new") + .assert() + .failure(); // missing } diff --git a/tests/create.rs b/tests/create.rs index fb747bf..cf202f4 100644 --- a/tests/create.rs +++ b/tests/create.rs @@ -3,20 +3,29 @@ use tempfile::tempdir; fn seed_module(dir: &std::path::Path) { std::fs::create_dir_all(dir.join("src/controllers")).unwrap(); - std::fs::write(dir.join("src/app.module.ts"), -"import { Module } from '@green-tea/core';\n\n\ -@Module({ controllers: [] })\nexport class AppModule {}\n").unwrap(); + std::fs::write( + dir.join("src/app.module.ts"), + "import { Module } from '@green-tea/core';\n\n\ +@Module({ controllers: [] })\nexport class AppModule {}\n", + ) + .unwrap(); } #[test] fn create_controller_writes_and_wires() { let d = tempdir().unwrap(); seed_module(d.path()); - Command::cargo_bin("matcha").unwrap() + Command::cargo_bin("matcha") + .unwrap() .current_dir(d.path()) - .args(["create", "controller", "Users"]).assert().success(); + .args(["create", "controller", "Users"]) + .assert() + .success(); - assert!(d.path().join("src/controllers/users.controller.ts").exists()); + assert!(d + .path() + .join("src/controllers/users.controller.ts") + .exists()); let module = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap(); assert!(module.contains("UsersController")); assert!(module.contains("import { UsersController }")); diff --git a/tests/new.rs b/tests/new.rs index 66e9f20..4f34b40 100644 --- a/tests/new.rs +++ b/tests/new.rs @@ -5,9 +5,12 @@ use tempfile::tempdir; #[test] fn new_scaffolds_into_named_dir() { let d = tempdir().unwrap(); - Command::cargo_bin("matcha").unwrap() + Command::cargo_bin("matcha") + .unwrap() .current_dir(d.path()) - .args(["new", "my-api"]).assert().success(); + .args(["new", "my-api"]) + .assert() + .success(); let root = d.path().join("my-api"); assert!(root.join("src/app.module.ts").exists()); assert!(root.join("public/index.html").exists()); @@ -17,9 +20,12 @@ fn new_scaffolds_into_named_dir() { fn new_refuses_existing_dir() { let d = tempdir().unwrap(); std::fs::create_dir(d.path().join("taken")).unwrap(); - Command::cargo_bin("matcha").unwrap() + Command::cargo_bin("matcha") + .unwrap() .current_dir(d.path()) - .args(["new", "taken"]).assert().failure(); + .args(["new", "taken"]) + .assert() + .failure(); } #[test] @@ -29,15 +35,37 @@ fn new_clones_local_template() { let src = d.path().join("src-tmpl"); std::fs::create_dir_all(src.join("public")).unwrap(); std::fs::write(src.join("public/marker.txt"), "hi").unwrap(); - Proc::new("git").args(["init", "-q"]).current_dir(&src).status().unwrap(); - Proc::new("git").args(["add", "."]).current_dir(&src).status().unwrap(); - Proc::new("git").args(["-c","user.email=t@t","-c","user.name=t", - "commit","-qm","init"]).current_dir(&src).status().unwrap(); + Proc::new("git") + .args(["init", "-q"]) + .current_dir(&src) + .status() + .unwrap(); + Proc::new("git") + .args(["add", "."]) + .current_dir(&src) + .status() + .unwrap(); + Proc::new("git") + .args([ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "init", + ]) + .current_dir(&src) + .status() + .unwrap(); let url = format!("file://{}", src.display()); - Command::cargo_bin("matcha").unwrap() + Command::cargo_bin("matcha") + .unwrap() .current_dir(d.path()) - .args(["new", "cloned", "--template-url", &url]).assert().success(); + .args(["new", "cloned", "--template-url", &url]) + .assert() + .success(); assert!(d.path().join("cloned/public/marker.txt").exists()); assert!(!d.path().join("cloned/.git").exists()); // .git stripped }