10 Commits
Author SHA1 Message Date
chrnx 757b729986 fix(add): merge imports into existing brace + capability idempotency; fmt
- wire::add_import now merges a new symbol into an already-present
  `import { ... } from '<from>';` brace 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 as previously
  assumed). Falls back to appending a new line when the module isn't
  imported yet, or if the brace-merge edit fails the parses_clean
  guard.
- cmd_add::run gains a capability-level idempotency guard, keyed on
  each capability's unique route-path literal, so `matcha add <cap>`
  run twice no longer appends a duplicate handler + route.
- cargo fmt --all across the crate; drop the stale #[allow(dead_code)]
  on wire::parses_clean now that it's demonstrably live.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:52:21 -05:00
chrnx bc013fde9f docs: matcha README with usage and runtime detection
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:39:37 -05:00
chrnx 87d7e185d7 test(add): cover insert_method revert/not-found paths and only_controller errors
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:38:09 -05:00
chrnx 1b9990f02a feat: matcha add appends capability handler to the controller
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:33:32 -05:00
chrnx e99dd58c66 feat: optional --check delegates type-check to detected runtime
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:28:40 -05:00
chrnx 13b77b3999 feat: matcha create controller with tree-sitter auto-wire + emit-only fallback
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:24:29 -05:00
chrnx 4df1e7ce7b fix(wire): scope @Module array search to the Module decorator, not any object literal
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:20:39 -05:00
chrnx acaee0d7e0 feat: tree-sitter import + @Module array wiring with revert-on-break
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:13:38 -05:00
chrnx 16480db7a2 feat: matcha run detects runtime and spawns watch
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:09:08 -05:00
chrnx 2972326103 feat: matcha new --template-url via shallow git clone
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:06:19 -05:00
13 changed files with 996 additions and 21 deletions

No files matched your search

+1
View File
@@ -1 +1,2 @@
/target /target
.superpowers/
+47
View File
@@ -0,0 +1,47 @@
# matcha
The [green-tea](https://git.svc.zoit.services/Green-Tea/core) CLI — scaffold, run, and generate green-tea apps from a single native binary. No JS runtime required to install or operate.
## Install
```bash
cargo install matcha # or: brew install matcha (once published)
```
## Usage
```bash
matcha new my-api # scaffold from the official starter
matcha new my-api --template-url gh:owner/repo # scaffold from any git template
matcha run # detect node/deno/bun and run in watch
matcha create controller Users # generate + auto-wire into @Module
matcha add sse # add a capability (sse|stream|buffer) to your controller
```
### The starter
`matcha new <name>` (no flags) scaffolds a live app: it serves an `index.html`
with the green-tea logo and streams a rotating zen message over `@Sse('/zen')`.
Open the browser and it's already alive — `matcha run` boots it.
### `create` / `add` auto-wiring
`create` and `add` edit your TypeScript with tree-sitter: they insert imports
and wire pieces into the right `@Module` array or controller. Edits are
idempotent and revert themselves if they would break the file's syntax. Pass
`--check` to `create` to type-check with your project's runtime afterward.
## Runtime detection
`matcha run` picks the runtime by precedence, first match wins:
1. `matcha.toml` — `runtime = "node" | "deno" | "bun"`
2. `deno.json` / `deno.jsonc` → **deno**
3. `bun.lockb` / `bun.lock` → **bun**
4. `package.json` → **node**
Edge is a deploy target, not a `matcha run` target.
## License
MIT — same as the green-tea framework. Contributions require a DCO sign-off (`git commit -s`).
+52
View File
@@ -0,0 +1,52 @@
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::Node => ("npx", vec!["tsc", "--noEmit"]),
}
}
pub fn run(dir: &Path) -> std::io::Result<bool> {
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()?;
Ok(status.success())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime::Runtime;
#[test]
fn deno_check_cmd() {
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"])
);
}
#[test]
fn bun_uses_bunx_tsc_noemit() {
assert_eq!(
check_command(Runtime::Bun),
("bunx", vec!["tsc", "--noEmit"])
);
}
}
+98
View File
@@ -0,0 +1,98 @@
//! `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, 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 <cap>`
/// 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,
}
}
/// 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, 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");
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(())
}
+73
View File
@@ -0,0 +1,73 @@
//! `matcha create <kind> <Name>` — generate a stub file for `<kind>` 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"),
)),
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()));
std::fs::create_dir_all(file.parent().unwrap())?;
std::fs::write(&file, controller_stub(name))?;
println!("✓ {}", file.display());
let symbol = format!("{name}Controller");
let from = format!("./controllers/{}.controller", name.to_lowercase());
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(());
}
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) {
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");
}
}
if check {
match crate::check::run(Path::new(".")) {
Ok(true) => println!("✓ type-check passed"),
Ok(false) => println!("⚠ type-check reported errors"),
Err(e) => println!("⚠ could not run type-check: {e}"),
}
}
Ok(())
}
+44 -4
View File
@@ -6,8 +6,10 @@ use crate::template;
pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> { pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> {
let dest = Path::new(name); let dest = Path::new(name);
if dest.exists() { if dest.exists() {
return Err(Error::new(ErrorKind::AlreadyExists, return Err(Error::new(
format!("'{name}' already exists"))); ErrorKind::AlreadyExists,
format!("'{name}' already exists"),
));
} }
match template_url { match template_url {
@@ -15,9 +17,47 @@ pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> {
std::fs::create_dir_all(dest)?; std::fs::create_dir_all(dest)?;
template::write_starter(dest, name)?; template::write_starter(dest, name)?;
} }
Some(_) => return Err(Error::new(ErrorKind::Unsupported, Some(url) => clone_template(url, dest)?,
"--template-url not implemented yet")),
} }
println!("✓ created {name}\n cd {name} && matcha run"); println!("✓ created {name}\n cd {name} && matcha run");
Ok(()) Ok(())
} }
fn resolve_url(spec: &str) -> String {
if let Some(rest) = spec.strip_prefix("gh:") {
format!("https://github.com/{rest}")
} else {
spec.to_string()
}
}
fn clone_template(url: &str, dest: &Path) -> std::io::Result<()> {
let status = std::process::Command::new("git")
.args(["clone", "--depth", "1", &resolve_url(url)])
.arg(dest)
.status()?;
if !status.success() {
return Err(Error::other("git clone failed"));
}
std::fs::remove_dir_all(dest.join(".git")).ok();
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gh_shorthand_expands() {
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"
);
}
}
+50
View File
@@ -0,0 +1,50 @@
use std::io::{Error, ErrorKind};
use std::path::Path;
use crate::runtime::{self, Runtime};
fn command_for(rt: Runtime) -> (&'static str, Vec<&'static str>) {
match rt {
Runtime::Deno => ("deno", vec!["task", "dev"]),
Runtime::Bun => ("bun", vec!["--watch", "run", "dev"]),
Runtime::Node => ("npm", vec!["run", "dev"]),
}
}
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 (prog, args) = command_for(rt);
println!("→ {prog} {}", args.join(" "));
let status = std::process::Command::new(prog)
.args(&args)
.current_dir(dir)
.status()?;
std::process::exit(status.code().unwrap_or(1));
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime::Runtime;
#[test]
fn deno_uses_task_dev() {
assert_eq!(command_for(Runtime::Deno), ("deno", vec!["task", "dev"]));
}
#[test]
fn bun_watch() {
assert_eq!(
command_for(Runtime::Bun),
("bun", vec!["--watch", "run", "dev"])
);
}
#[test]
fn node_watch() {
assert_eq!(command_for(Runtime::Node), ("npm", vec!["run", "dev"]));
}
}
+23 -3
View File
@@ -1,7 +1,12 @@
mod check;
mod cli; mod cli;
mod cmd_add;
mod cmd_create;
mod cmd_new; mod cmd_new;
mod cmd_run;
mod runtime; mod runtime;
mod template; mod template;
mod wire;
use clap::Parser; use clap::Parser;
use cli::{Cli, Command}; use cli::{Cli, Command};
@@ -15,8 +20,23 @@ fn main() {
std::process::exit(1); std::process::exit(1);
} }
} }
Command::Run => eprintln!("run: not yet implemented"), Command::Run => {
Command::Create { .. } => eprintln!("create: not yet implemented"), if let Err(e) = cmd_run::run(std::path::Path::new(".")) {
Command::Add { .. } => eprintln!("add: not yet implemented"), eprintln!("error: {e}");
std::process::exit(1);
}
}
Command::Create { kind, name, check } => {
if let Err(e) = cmd_create::run(&kind, &name, check) {
eprintln!("error: {e}");
std::process::exit(1);
}
}
Command::Add { capability } => {
if let Err(e) = cmd_add::run(&capability) {
eprintln!("error: {e}");
std::process::exit(1);
}
}
} }
} }
+429
View File
@@ -0,0 +1,429 @@
//! Pure text-editing core for wiring generated TypeScript symbols into an
//! existing `@green-tea/core` project: adding `import` statements and
//! inserting symbols into a `@Module({...})` array (e.g. `controllers`,
//! `providers`).
//!
//! This module is intentionally free of CLI/I-O concerns — it operates on
//! `&str` in, `String`/`Option<String>` out — so it can be exercised with
//! plain string fixtures and reused by the `add` command (Task 8) without
//! any filesystem coupling.
//!
//! Resolved crate API notes (tree-sitter 0.22.6 / tree-sitter-typescript
//! 0.21.2, confirmed against the installed crate source, not just docs):
//! - The language accessor is the function `tree_sitter_typescript::language_typescript()`
//! (this crate version does NOT expose a `LANGUAGE_TYPESCRIPT` const).
//! - `Parser::set_language` takes `&Language`.
//! - Grammar node kinds `import_statement`, `pair`, `array` and field names
//! `key`/`value` on `pair` match the brief's assumptions (verified via
//! `typescript/src/node-types.json` in the resolved crate).
use tree_sitter::{Node, Parser};
/// Builds a fresh parser configured for the TypeScript grammar.
fn parser() -> Parser {
let mut p = Parser::new();
p.set_language(&tree_sitter_typescript::language_typescript())
.expect("load ts grammar");
p
}
/// 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.
fn parses_clean(src: &str) -> bool {
let tree = parser().parse(src, None).unwrap();
!has_error(tree.root_node())
}
fn has_error(node: Node) -> bool {
if node.is_error() || node.is_missing() {
return true;
}
let mut c = node.walk();
for child in node.children(&mut c) {
if has_error(child) {
return true;
}
}
false
}
/// Wires `symbol` into `src`'s imports from module `from`:
///
/// 1. If an `import { ... } from '<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 { <symbol> } from '<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 mut last_end = 0usize;
let mut c = root.walk();
for child in root.children(&mut c) {
if child.kind() == "import_statement" {
last_end = child.end_byte();
}
}
if last_end == 0 {
return format!("{line}\n{src}");
}
let mut out = String::with_capacity(src.len() + line.len() + 1);
out.push_str(&src[..last_end]);
out.push('\n');
out.push_str(&line);
out.push_str(&src[last_end..]);
out
}
/// Finds the `named_imports` (`{ A, B, C }`) brace of the top-level `import
/// { ... } from '<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<Node<'a>> {
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
/// original text untouched — when the edited text fails to re-parse clean
/// (an `ERROR`/missing node appears), which is also what happens when `key`
/// doesn't exist in the module object at all (the splice can't be located).
pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option<String> {
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 inner = &src[open + 1..close]; // between [ ]
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..]);
if parses_clean(&out) {
Some(out)
} else {
None
}
}
/// 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) {
if child.kind() != "pair" {
continue;
}
let Some(k) = child.child_by_field_name("key") else {
continue;
};
if k.utf8_text(src.as_bytes()).ok() != Some(key) {
continue;
}
let Some(v) = child.child_by_field_name("value") else {
continue;
};
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));
}
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
/// that is an `identifier` with text `"Module"`; the object literal is the
/// first `object`-kind named child of that call's `arguments` node.
///
/// Returns `None` when there is no `@Module(...)` decorator at all, or when
/// one exists but its argument isn't an object literal.
fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option<Node<'a>> {
fn find_decorator_call<'a>(node: Node<'a>, src: &str) -> Option<Node<'a>> {
if node.kind() == "decorator" {
let mut c = node.walk();
for child in node.children(&mut c) {
if child.kind() != "call_expression" {
continue;
}
let is_module = child
.child_by_field_name("function")
.filter(|f| f.kind() == "identifier")
.and_then(|f| f.utf8_text(src.as_bytes()).ok())
== Some("Module");
if is_module {
return Some(child);
}
}
// This decorator isn't `@Module(...)`; keep looking elsewhere.
return None;
}
let mut c = node.walk();
for child in node.children(&mut c) {
if let Some(r) = find_decorator_call(child, src) {
return Some(r);
}
}
None
}
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");
object
}
#[cfg(test)]
mod tests {
use super::*;
const MOD: &str = r#"import { Module } from '@green-tea/core';
import { HomeController } from './controllers/home.controller';
@Module({ controllers: [HomeController] })
export class AppModule {}
"#;
#[test]
fn import_is_added_once() {
let out = add_import(MOD, "UsersController", "./controllers/users.controller");
assert!(out.contains("import { UsersController } from './controllers/users.controller';"));
let twice = add_import(&out, "UsersController", "./controllers/users.controller");
assert_eq!(out, twice); // idempotent
}
#[test]
fn symbol_added_to_controllers_array() {
let out = add_to_module_array(MOD, "controllers", "UsersController").unwrap();
assert!(out.contains("HomeController"));
assert!(out.contains("UsersController"));
// idempotent
let again = add_to_module_array(&out, "controllers", "UsersController").unwrap();
assert_eq!(out, again);
}
#[test]
fn broken_result_is_rejected() {
// 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")
);
}
/// 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.
#[test]
fn revert_on_actual_parse_error() {
// A "symbol" containing stray syntax breaks the array/object/class
// once spliced in, so the edited text must fail to re-parse clean.
let out = add_to_module_array(MOD, "controllers", "X]; class Evil {");
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.
let src = r#"const decoy = { controllers: [Existing] };
@Module({ controllers: [HomeController] })
export class AppModule {}
"#;
let out = add_to_module_array(src, "controllers", "UsersController").unwrap();
// must land in the @Module array, next to HomeController...
assert!(out.contains("HomeController, UsersController"));
// ...and must NOT touch the decoy array
assert!(out.contains("controllers: [Existing] }"));
}
#[test]
fn insert_method_reverts_on_parse_break() {
// a method body that makes the class re-parse fail must yield None (revert guard)
let src = "export class HomeController {\n home() {}\n}\n";
assert!(insert_method(src, "HomeController", " zen() { ]; class Evil {\n").is_none());
}
#[test]
fn insert_method_none_when_class_absent() {
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';"));
}
}
+85
View File
@@ -0,0 +1,85 @@
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 }"));
}
#[test]
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()
.current_dir(d.path())
.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]
fn add_errors_when_multiple_controllers_and_writes_nothing() {
let d = tempdir().unwrap();
let cdir = d.path().join("src/controllers");
std::fs::create_dir_all(&cdir).unwrap();
let original = "export class X {}\n";
for n in ["a", "b"] {
std::fs::write(cdir.join(format!("{n}.controller.ts")), original).unwrap();
}
Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path())
.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
);
}
+14 -6
View File
@@ -3,14 +3,22 @@ use predicates::str::contains;
#[test] #[test]
fn help_lists_all_subcommands() { fn help_lists_all_subcommands() {
Command::cargo_bin("matcha").unwrap() Command::cargo_bin("matcha")
.arg("--help").assert().success() .unwrap()
.stdout(contains("new")).stdout(contains("run")) .arg("--help")
.stdout(contains("create")).stdout(contains("add")); .assert()
.success()
.stdout(contains("new"))
.stdout(contains("run"))
.stdout(contains("create"))
.stdout(contains("add"));
} }
#[test] #[test]
fn new_requires_a_name() { fn new_requires_a_name() {
Command::cargo_bin("matcha").unwrap() Command::cargo_bin("matcha")
.arg("new").assert().failure(); // missing <name> .unwrap()
.arg("new")
.assert()
.failure(); // missing <name>
} }
+32
View File
@@ -0,0 +1,32 @@
use assert_cmd::Command;
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();
}
#[test]
fn create_controller_writes_and_wires() {
let d = tempdir().unwrap();
seed_module(d.path());
Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path())
.args(["create", "controller", "Users"])
.assert()
.success();
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 }"));
}
+48 -8
View File
@@ -1,12 +1,16 @@
use assert_cmd::Command; use assert_cmd::Command;
use std::process::Command as Proc;
use tempfile::tempdir; use tempfile::tempdir;
#[test] #[test]
fn new_scaffolds_into_named_dir() { fn new_scaffolds_into_named_dir() {
let d = tempdir().unwrap(); let d = tempdir().unwrap();
Command::cargo_bin("matcha").unwrap() Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path()) .current_dir(d.path())
.args(["new", "my-api"]).assert().success(); .args(["new", "my-api"])
.assert()
.success();
let root = d.path().join("my-api"); let root = d.path().join("my-api");
assert!(root.join("src/app.module.ts").exists()); assert!(root.join("src/app.module.ts").exists());
assert!(root.join("public/index.html").exists()); assert!(root.join("public/index.html").exists());
@@ -16,16 +20,52 @@ fn new_scaffolds_into_named_dir() {
fn new_refuses_existing_dir() { fn new_refuses_existing_dir() {
let d = tempdir().unwrap(); let d = tempdir().unwrap();
std::fs::create_dir(d.path().join("taken")).unwrap(); std::fs::create_dir(d.path().join("taken")).unwrap();
Command::cargo_bin("matcha").unwrap() Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path()) .current_dir(d.path())
.args(["new", "taken"]).assert().failure(); .args(["new", "taken"])
.assert()
.failure();
} }
#[test] #[test]
fn new_with_template_url_stub_leaves_no_dir() { fn new_clones_local_template() {
let d = tempdir().unwrap(); let d = tempdir().unwrap();
Command::cargo_bin("matcha").unwrap() // build a bare-ish source repo to clone
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();
let url = format!("file://{}", src.display());
Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path()) .current_dir(d.path())
.args(["new", "demo", "--template-url", "gh:x/y"]).assert().failure(); .args(["new", "cloned", "--template-url", &url])
assert!(!d.path().join("demo").exists()); .assert()
.success();
assert!(d.path().join("cloned/public/marker.txt").exists());
assert!(!d.path().join("cloned/.git").exists()); // .git stripped
} }