diff --git a/src/cmd_add.rs b/src/cmd_add.rs new file mode 100644 index 0000000..8fc0076 --- /dev/null +++ b/src/cmd_add.rs @@ -0,0 +1,76 @@ +//! `matcha add ` — appends a capability handler method to +//! the single controller found under `src/controllers`, wiring in the +//! decorator import via `wire::add_import` and splicing the method body via +//! `wire::insert_method`. + +use std::io::{Error, ErrorKind}; +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)> { + match cap { + "sse" => Some(( + "Sse", + "\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(), + )), + "stream" => Some(( + "Stream", + "\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(), + )), + "buffer" => Some(( + "Get", + "\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(), + )), + _ => None, + } +} + +/// Finds the single `*.controller.ts` file in `src/controllers`. Errors if +/// there are zero or more than one — this v1 has no way to disambiguate. +fn only_controller() -> std::io::Result { + let dir = std::path::Path::new("src/controllers"); + let mut hits: Vec = std::fs::read_dir(dir)? + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.to_string_lossy().ends_with(".controller.ts")) + .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)")), + } +} + +/// Extracts the class name following `export class `. This is a plain text +/// scan rather than a tree-sitter query — `insert_method` does the real +/// grammar-aware work once the name is known. +fn class_name(src: &str) -> Option { + let idx = src.find("export class ")? + "export class ".len(); + let rest = &src[idx..]; + let end = rest.find(|c: char| !c.is_alphanumeric() && c != '_')?; + Some(rest[..end].to_string()) +} + +pub fn run(cap: &str) -> std::io::Result<()> { + let (decorator, method) = 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"))?; + 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()), + } + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index 8a665f4..ea02138 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ mod check; mod cli; +mod cmd_add; mod cmd_create; mod cmd_new; mod cmd_run; @@ -31,6 +32,11 @@ fn main() { std::process::exit(1); } } - Command::Add { .. } => eprintln!("add: not yet implemented"), + Command::Add { capability } => { + if let Err(e) = cmd_add::run(&capability) { + eprintln!("error: {e}"); + std::process::exit(1); + } + } } } diff --git a/src/wire.rs b/src/wire.rs index 068b47a..e8b88ee 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -141,6 +141,51 @@ fn find_array(root: &Node, src: &str, key: &str) -> Option<(usize, usize, String None } +/// 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 +/// `class ` is found at all (the splice point can't be located). +pub fn insert_method(src: &str, class: &str, method_src: &str) -> Option { + let tree = parser().parse(src, None).unwrap(); + let close = find_class_body_close(&tree.root_node(), src, class)?; + let mut out = String::with_capacity(src.len() + method_src.len() + 1); + out.push_str(&src[..close]); + if !src[..close].ends_with('\n') { + out.push('\n'); + } + out.push_str(method_src); + out.push_str(&src[close..]); + if parses_clean(&out) { + Some(out) + } else { + None + } +} + +/// Finds the byte offset of the closing `}` of `class `'s body, +/// searching the whole tree in source order (depth-first). +fn find_class_body_close(root: &Node, src: &str, class: &str) -> Option { + fn visit(node: Node, src: &str, class: &str) -> Option { + if node.kind() == "class_declaration" { + if let Some(n) = node.child_by_field_name("name") { + if n.utf8_text(src.as_bytes()).ok() == Some(class) { + if let Some(body) = node.child_by_field_name("body") { + return Some(body.end_byte() - 1); // the closing '}' + } + } + } + } + let mut c = node.walk(); + for child in node.children(&mut c) { + if let Some(r) = visit(child, src, class) { + return Some(r); + } + } + None + } + visit(*root, src, class) +} + /// Locates the argument object literal of the first `@Module(...)` /// decorator in `src`, in source order. A decorator node is recognized as /// `@Module(...)` when its `call_expression` child has a `function` field @@ -237,6 +282,14 @@ export class AppModule {} assert!(out.is_none()); } + #[test] + fn method_inserted_before_class_close() { + let src = "export class HomeController {\n home() {}\n}\n"; + let out = insert_method(src, "HomeController", " @Sse('/zen')\n zen() {}\n").unwrap(); + assert!(out.contains("zen()")); + assert!(out.trim_end().ends_with('}')); + } + #[test] fn targets_module_array_not_a_decoy_before_it() { // A decoy object literal with a `controllers:` array appears BEFORE the real @Module. diff --git a/tests/add.rs b/tests/add.rs new file mode 100644 index 0000000..988836a --- /dev/null +++ b/tests/add.rs @@ -0,0 +1,19 @@ +use assert_cmd::Command; +use tempfile::tempdir; + +#[test] +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(); + + Command::cargo_bin("matcha").unwrap() + .current_dir(d.path()) + .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(")); + assert!(out.contains("import { Route, Get, Sse }") || out.contains("Sse }")); +}