feat: matcha add appends capability handler to the controller

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-11 13:33:32 -05:00
1 parent 72e984d35c
commit 4fe5b53e7f
4 files changed
+155 -1

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
//! `matcha add <sse|stream|buffer>` — 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<PathBuf> {
let dir = std::path::Path::new("src/controllers");
let mut hits: Vec<PathBuf> = 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<String> {
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(())
}
+7 -1
View File
@@ -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);
}
}
}
}
+53
View File
@@ -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
/// <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 <class>` is found at all (the splice point can't be located).
pub fn insert_method(src: &str, class: &str, method_src: &str) -> Option<String> {
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 <class>`'s body,
/// searching the whole tree in source order (depth-first).
fn find_class_body_close(root: &Node, src: &str, class: &str) -> Option<usize> {
fn visit(node: Node, src: &str, class: &str) -> Option<usize> {
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.