From bbe3e299aeaba0bcb5da9f4a60253d8c25525d8e Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 12:41:27 -0500 Subject: [PATCH 01/22] feat: matcha binary skeleton with clap command surface Signed-off-by: Diego Resendez --- Cargo.toml | 19 +++++++++++++++++++ src/cli.rs | 33 +++++++++++++++++++++++++++++++++ src/main.rs | 14 ++++++++++++++ tests/cli.rs | 16 ++++++++++++++++ 4 files changed, 82 insertions(+) create mode 100644 Cargo.toml create mode 100644 src/cli.rs create mode 100644 src/main.rs create mode 100644 tests/cli.rs diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..234a9a3 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "matcha" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "matcha" +path = "src/main.rs" + +[dependencies] +clap = { version = "4", features = ["derive"] } +include_dir = "0.7" +tree-sitter = "0.22" +tree-sitter-typescript = "0.21" + +[dev-dependencies] +assert_cmd = "2" +predicates = "3" +tempfile = "3" diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..f26f88b --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,33 @@ +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[command(name = "matcha", about = "green-tea CLI")] +pub struct Cli { + #[command(subcommand)] + pub command: Command, +} + +#[derive(Subcommand)] +pub enum Command { + /// Scaffold a new project + New { + name: String, + #[arg(long)] + template_url: Option, + }, + /// Detect the runtime and run the project in watch mode + Run, + /// Generate a piece and auto-wire it into the module + Create { + #[arg(value_parser = ["module", "controller", "step"])] + kind: String, + name: String, + #[arg(long)] + check: bool, + }, + /// Add a capability to a controller + Add { + #[arg(value_parser = ["sse", "stream", "buffer"])] + capability: String, + }, +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..ec242eb --- /dev/null +++ b/src/main.rs @@ -0,0 +1,14 @@ +mod cli; + +use clap::Parser; +use cli::{Cli, Command}; + +fn main() { + let cli = Cli::parse(); + match cli.command { + Command::New { .. } => eprintln!("new: not yet implemented"), + Command::Run => eprintln!("run: not yet implemented"), + Command::Create { .. } => eprintln!("create: not yet implemented"), + Command::Add { .. } => eprintln!("add: not yet implemented"), + } +} diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..8547984 --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,16 @@ +use assert_cmd::Command; +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")); +} + +#[test] +fn new_requires_a_name() { + Command::cargo_bin("matcha").unwrap() + .arg("new").assert().failure(); // missing +} From 4298c0509f8c7d02a3dd9e181c07a3046c759b14 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 12:44:02 -0500 Subject: [PATCH 02/22] chore: track Cargo.lock for reproducible binary builds Signed-off-by: Diego Resendez --- .gitignore | 1 - Cargo.lock | 513 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 513 insertions(+), 1 deletion(-) create mode 100644 Cargo.lock diff --git a/.gitignore b/.gitignore index 96ef6c0..ea8c4bf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ /target -Cargo.lock diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..bb13815 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,513 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "bstr" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "cc" +version = "1.2.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "include_dir" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" +dependencies = [ + "include_dir_macros", +] + +[[package]] +name = "include_dir_macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "matcha" +version = "0.1.0" +dependencies = [ + "assert_cmd", + "clap", + "include_dir", + "predicates", + "tempfile", + "tree-sitter", + "tree-sitter-typescript", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "regex" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f388202e4b80542a0921078cc23b6333bcf1409c1e3f86404cae4766a6131db" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "tree-sitter" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df7cc499ceadd4dcdf7ec6d4cbc34ece92c3fa07821e287aedecd4416c516dca" +dependencies = [ + "cc", + "regex", +] + +[[package]] +name = "tree-sitter-typescript" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecb35d98a688378e56c18c9c159824fd16f730ccbea19aacf4f206e5d5438ed9" +dependencies = [ + "cc", + "tree-sitter", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] From 6ad481eb827ef76501396db2ffe9a665f2d12b2c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 12:46:11 -0500 Subject: [PATCH 03/22] feat: runtime detection with matcha.toml override Signed-off-by: Diego Resendez --- src/main.rs | 1 + src/runtime.rs | 105 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 src/runtime.rs diff --git a/src/main.rs b/src/main.rs index ec242eb..da2d687 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ mod cli; +mod runtime; use clap::Parser; use cli::{Cli, Command}; diff --git a/src/runtime.rs b/src/runtime.rs new file mode 100644 index 0000000..773e1c0 --- /dev/null +++ b/src/runtime.rs @@ -0,0 +1,105 @@ +use std::path::Path; + +#[allow(dead_code)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum Runtime { + Node, + Deno, + Bun, +} + +impl Runtime { + #[allow(dead_code)] + pub fn from_str(s: &str) -> Option { + match s.trim() { + "node" => Some(Runtime::Node), + "deno" => Some(Runtime::Deno), + "bun" => Some(Runtime::Bun), + _ => None, + } + } +} + +#[allow(dead_code)] +fn exists(dir: &Path, name: &str) -> bool { + dir.join(name).exists() +} + +/// Reads `runtime = "..."` from matcha.toml without a TOML dep (one field only). +#[allow(dead_code)] +fn override_from_toml(dir: &Path) -> Option { + let text = std::fs::read_to_string(dir.join("matcha.toml")).ok()?; + for line in text.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("runtime") { + let val = rest.trim().trim_start_matches('=').trim().trim_matches('"'); + return Runtime::from_str(val); + } + } + None +} + +#[allow(dead_code)] +pub fn detect(dir: &Path) -> Option { + if let Some(r) = override_from_toml(dir) { + return Some(r); + } + if exists(dir, "deno.json") || exists(dir, "deno.jsonc") { + return Some(Runtime::Deno); + } + if exists(dir, "bun.lockb") || exists(dir, "bun.lock") { + return Some(Runtime::Bun); + } + if exists(dir, "package.json") { + return Some(Runtime::Node); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use tempfile::tempdir; + + fn touch(dir: &std::path::Path, name: &str) { + fs::write(dir.join(name), "{}").unwrap(); + } + + #[test] + fn deno_wins_over_package_json() { + let d = tempdir().unwrap(); + touch(d.path(), "package.json"); + touch(d.path(), "deno.json"); + assert_eq!(detect(d.path()), Some(Runtime::Deno)); + } + + #[test] + fn bun_lock_selects_bun() { + let d = tempdir().unwrap(); + touch(d.path(), "package.json"); + touch(d.path(), "bun.lockb"); + assert_eq!(detect(d.path()), Some(Runtime::Bun)); + } + + #[test] + fn package_json_falls_back_to_node() { + let d = tempdir().unwrap(); + touch(d.path(), "package.json"); + assert_eq!(detect(d.path()), Some(Runtime::Node)); + } + + #[test] + fn matcha_toml_overrides() { + let d = tempdir().unwrap(); + touch(d.path(), "deno.json"); + fs::write(d.path().join("matcha.toml"), "runtime = \"bun\"\n").unwrap(); + assert_eq!(detect(d.path()), Some(Runtime::Bun)); + } + + #[test] + fn nothing_detected() { + let d = tempdir().unwrap(); + assert_eq!(detect(d.path()), None); + } +} From 456fa106646597c0c86c9c28859c1bd013568a25 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 12:49:53 -0500 Subject: [PATCH 04/22] feat: embed official starter template with token substitution Signed-off-by: Diego Resendez --- src/main.rs | 1 + src/template.rs | 49 +++++++++++++++++++ template/starter/deno.json | 1 + template/starter/matcha.toml | 1 + template/starter/public/index.html | 23 +++++++++ template/starter/src/app.module.ts | 5 ++ .../src/controllers/home.controller.ts | 26 ++++++++++ 7 files changed, 106 insertions(+) create mode 100644 src/template.rs create mode 100644 template/starter/deno.json create mode 100644 template/starter/matcha.toml create mode 100644 template/starter/public/index.html create mode 100644 template/starter/src/app.module.ts create mode 100644 template/starter/src/controllers/home.controller.ts diff --git a/src/main.rs b/src/main.rs index da2d687..bb067cb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ mod cli; mod runtime; +mod template; use clap::Parser; use cli::{Cli, Command}; diff --git a/src/template.rs b/src/template.rs new file mode 100644 index 0000000..1bcf073 --- /dev/null +++ b/src/template.rs @@ -0,0 +1,49 @@ +use include_dir::{include_dir, Dir}; +use std::path::Path; + +pub static STARTER: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/starter"); + +#[allow(dead_code)] +pub fn write_starter(dest: &Path, project_name: &str) -> std::io::Result<()> { + write_dir(&STARTER, dest, project_name) +} + +fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> { + for entry in dir.entries() { + match entry { + include_dir::DirEntry::Dir(d) => { + let sub = dest.join(d.path().file_name().unwrap()); + std::fs::create_dir_all(&sub)?; + write_dir(d, &sub, name)?; + } + include_dir::DirEntry::File(f) => { + let out = dest.join(f.path().file_name().unwrap()); + if let Some(parent) = out.parent() { + std::fs::create_dir_all(parent)?; + } + let contents = std::str::from_utf8(f.contents()) + .map(|s| s.replace("{{project_name}}", name).into_bytes()) + .unwrap_or_else(|_| f.contents().to_vec()); + std::fs::write(out, contents)?; + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + #[test] + fn writes_starter_and_substitutes_name() { + let d = tempdir().unwrap(); + write_starter(d.path(), "my-api").unwrap(); + let html = std::fs::read_to_string(d.path().join("public/index.html")).unwrap(); + assert!(html.contains("my-api")); + assert!(!html.contains("{{project_name}}")); + assert!(d.path().join("src/controllers/home.controller.ts").exists()); + assert!(d.path().join("matcha.toml").exists()); + } +} diff --git a/template/starter/deno.json b/template/starter/deno.json new file mode 100644 index 0000000..92ad661 --- /dev/null +++ b/template/starter/deno.json @@ -0,0 +1 @@ +{ "tasks": { "dev": "deno run --watch --allow-net --allow-read src/main.ts" } } diff --git a/template/starter/matcha.toml b/template/starter/matcha.toml new file mode 100644 index 0000000..0e63dab --- /dev/null +++ b/template/starter/matcha.toml @@ -0,0 +1 @@ +runtime = "deno" diff --git a/template/starter/public/index.html b/template/starter/public/index.html new file mode 100644 index 0000000..f9571d1 --- /dev/null +++ b/template/starter/public/index.html @@ -0,0 +1,23 @@ + + + + + {{project_name}} + + + +
+ +
connecting…
+
+ + + diff --git a/template/starter/src/app.module.ts b/template/starter/src/app.module.ts new file mode 100644 index 0000000..5a4752b --- /dev/null +++ b/template/starter/src/app.module.ts @@ -0,0 +1,5 @@ +import { Module } from '@green-tea/core'; +import { HomeController } from './controllers/home.controller'; + +@Module({ controllers: [HomeController] }) +export class AppModule {} diff --git a/template/starter/src/controllers/home.controller.ts b/template/starter/src/controllers/home.controller.ts new file mode 100644 index 0000000..a828546 --- /dev/null +++ b/template/starter/src/controllers/home.controller.ts @@ -0,0 +1,26 @@ +import { Route, Get, Html, Sse } from '@green-tea/core'; + +const ZEN = [ + 'Simplicity is the ultimate sophistication.', + 'The obstacle is the path.', + 'When you let go, you have two hands to work.', + 'Make it work, make it right, make it fast.', + 'Less, but better.', +]; + +@Route('/') +export class HomeController { + @Get('/') + @Html('public/index.html') + home() {} + + @Sse('/zen') + zen() { + return (async function* () { + for (let i = 0; ; i++) { + yield { zen: ZEN[i % ZEN.length] }; + await new Promise((r) => setTimeout(r, 30_000)); + } + })(); + } +} From caabb51ae0b15f3498c72adc0915ddc2f4178b3b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 12:56:54 -0500 Subject: [PATCH 05/22] =?UTF-8?q?fix(starter):=20make=20scaffolded=20app?= =?UTF-8?q?=20runnable=20=E2=80=94=20mountpoint,=20Deno=20entrypoint,=20im?= =?UTF-8?q?port=20map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- src/template.rs | 3 +++ template/starter/deno.json | 7 ++++++- template/starter/src/app.module.ts | 2 +- template/starter/src/main.ts | 7 +++++++ 4 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 template/starter/src/main.ts diff --git a/src/template.rs b/src/template.rs index 1bcf073..ef97caa 100644 --- a/src/template.rs +++ b/src/template.rs @@ -45,5 +45,8 @@ mod tests { assert!(!html.contains("{{project_name}}")); assert!(d.path().join("src/controllers/home.controller.ts").exists()); assert!(d.path().join("matcha.toml").exists()); + assert!(d.path().join("src/main.ts").exists()); + let module = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap(); + assert!(module.contains("mountpoint")); } } diff --git a/template/starter/deno.json b/template/starter/deno.json index 92ad661..700555c 100644 --- a/template/starter/deno.json +++ b/template/starter/deno.json @@ -1 +1,6 @@ -{ "tasks": { "dev": "deno run --watch --allow-net --allow-read src/main.ts" } } +{ + "compilerOptions": { "experimentalDecorators": true }, + "unstable": ["sloppy-imports"], + "imports": { "@green-tea/core": "npm:@green-tea/core@^26.7.0-beta.0" }, + "tasks": { "dev": "deno run --watch --allow-net --allow-read --allow-env src/main.ts" } +} diff --git a/template/starter/src/app.module.ts b/template/starter/src/app.module.ts index 5a4752b..4d303e0 100644 --- a/template/starter/src/app.module.ts +++ b/template/starter/src/app.module.ts @@ -1,5 +1,5 @@ import { Module } from '@green-tea/core'; import { HomeController } from './controllers/home.controller'; -@Module({ controllers: [HomeController] }) +@Module({ mountpoint: '/', controllers: [HomeController] }) export class AppModule {} diff --git a/template/starter/src/main.ts b/template/starter/src/main.ts new file mode 100644 index 0000000..23445c9 --- /dev/null +++ b/template/starter/src/main.ts @@ -0,0 +1,7 @@ +import { createApp } from '@green-tea/core'; +import { AppModule } from './app.module'; + +const app = createApp({ modules: [AppModule] }); + +Deno.serve({ port: 8000 }, app.fetch); +console.log('🍡 green-tea running on http://localhost:8000'); From 06849ebab4401a210ec3edf10dba7cf232cd6794 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 12:59:38 -0500 Subject: [PATCH 06/22] feat: matcha new scaffolds from embedded starter Signed-off-by: Diego Resendez --- src/cmd_new.rs | 21 +++++++++++++++++++++ src/main.rs | 8 +++++++- tests/new.rs | 22 ++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 src/cmd_new.rs create mode 100644 tests/new.rs diff --git a/src/cmd_new.rs b/src/cmd_new.rs new file mode 100644 index 0000000..872479c --- /dev/null +++ b/src/cmd_new.rs @@ -0,0 +1,21 @@ +use std::io::{Error, ErrorKind}; +use std::path::Path; + +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"))); + } + std::fs::create_dir_all(dest)?; + + match template_url { + None => template::write_starter(dest, name)?, + Some(_) => return Err(Error::new(ErrorKind::Unsupported, + "--template-url not implemented yet")), + } + println!("βœ“ created {name}\n cd {name} && matcha run"); + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index bb067cb..943cca4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ mod cli; +mod cmd_new; mod runtime; mod template; @@ -8,7 +9,12 @@ use cli::{Cli, Command}; fn main() { let cli = Cli::parse(); match cli.command { - Command::New { .. } => eprintln!("new: not yet implemented"), + Command::New { name, template_url } => { + if let Err(e) = cmd_new::run(&name, template_url.as_deref()) { + eprintln!("error: {e}"); + std::process::exit(1); + } + } Command::Run => eprintln!("run: not yet implemented"), Command::Create { .. } => eprintln!("create: not yet implemented"), Command::Add { .. } => eprintln!("add: not yet implemented"), diff --git a/tests/new.rs b/tests/new.rs new file mode 100644 index 0000000..41b85ba --- /dev/null +++ b/tests/new.rs @@ -0,0 +1,22 @@ +use assert_cmd::Command; +use tempfile::tempdir; + +#[test] +fn new_scaffolds_into_named_dir() { + let d = tempdir().unwrap(); + Command::cargo_bin("matcha").unwrap() + .current_dir(d.path()) + .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()); +} + +#[test] +fn new_refuses_existing_dir() { + let d = tempdir().unwrap(); + std::fs::create_dir(d.path().join("taken")).unwrap(); + Command::cargo_bin("matcha").unwrap() + .current_dir(d.path()) + .args(["new", "taken"]).assert().failure(); +} From de000cb27d829881ace3426517580b0b7b262367 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:03:01 -0500 Subject: [PATCH 07/22] fix(new): no orphan dir on error path; drop stale dead_code allow Signed-off-by: Diego Resendez --- src/cmd_new.rs | 6 ++++-- src/template.rs | 1 - tests/new.rs | 9 +++++++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/cmd_new.rs b/src/cmd_new.rs index 872479c..6095268 100644 --- a/src/cmd_new.rs +++ b/src/cmd_new.rs @@ -9,10 +9,12 @@ pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> { return Err(Error::new(ErrorKind::AlreadyExists, format!("'{name}' already exists"))); } - std::fs::create_dir_all(dest)?; match template_url { - None => template::write_starter(dest, name)?, + None => { + std::fs::create_dir_all(dest)?; + template::write_starter(dest, name)?; + } Some(_) => return Err(Error::new(ErrorKind::Unsupported, "--template-url not implemented yet")), } diff --git a/src/template.rs b/src/template.rs index ef97caa..1f180c2 100644 --- a/src/template.rs +++ b/src/template.rs @@ -3,7 +3,6 @@ use std::path::Path; pub static STARTER: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/starter"); -#[allow(dead_code)] pub fn write_starter(dest: &Path, project_name: &str) -> std::io::Result<()> { write_dir(&STARTER, dest, project_name) } diff --git a/tests/new.rs b/tests/new.rs index 41b85ba..c855074 100644 --- a/tests/new.rs +++ b/tests/new.rs @@ -20,3 +20,12 @@ fn new_refuses_existing_dir() { .current_dir(d.path()) .args(["new", "taken"]).assert().failure(); } + +#[test] +fn new_with_template_url_stub_leaves_no_dir() { + let d = tempdir().unwrap(); + Command::cargo_bin("matcha").unwrap() + .current_dir(d.path()) + .args(["new", "demo", "--template-url", "gh:x/y"]).assert().failure(); + assert!(!d.path().join("demo").exists()); +} From 2972326103ca5f26ed8ec4717841d604175d294b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:06:19 -0500 Subject: [PATCH 08/22] feat: matcha new --template-url via shallow git clone Signed-off-by: Diego Resendez --- src/cmd_new.rs | 38 ++++++++++++++++++++++++++++++++++++-- tests/new.rs | 18 +++++++++++++++--- 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/src/cmd_new.rs b/src/cmd_new.rs index 6095268..e9b5786 100644 --- a/src/cmd_new.rs +++ b/src/cmd_new.rs @@ -15,9 +15,43 @@ pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> { std::fs::create_dir_all(dest)?; template::write_starter(dest, name)?; } - Some(_) => return Err(Error::new(ErrorKind::Unsupported, - "--template-url not implemented yet")), + Some(url) => clone_template(url, dest)?, } println!("βœ“ created {name}\n cd {name} && matcha run"); 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"); + } +} diff --git a/tests/new.rs b/tests/new.rs index c855074..66e9f20 100644 --- a/tests/new.rs +++ b/tests/new.rs @@ -1,4 +1,5 @@ use assert_cmd::Command; +use std::process::Command as Proc; use tempfile::tempdir; #[test] @@ -22,10 +23,21 @@ fn new_refuses_existing_dir() { } #[test] -fn new_with_template_url_stub_leaves_no_dir() { +fn new_clones_local_template() { let d = tempdir().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()) - .args(["new", "demo", "--template-url", "gh:x/y"]).assert().failure(); - assert!(!d.path().join("demo").exists()); + .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 } From 16480db7a2ff15a4cfc560938f714c6991a2e978 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:09:08 -0500 Subject: [PATCH 09/22] feat: matcha run detects runtime and spawns watch Signed-off-by: Diego Resendez --- src/cmd_run.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 8 +++++++- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 src/cmd_run.rs diff --git a/src/cmd_run.rs b/src/cmd_run.rs new file mode 100644 index 0000000..35b3686 --- /dev/null +++ b/src/cmd_run.rs @@ -0,0 +1,42 @@ +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"])); + } +} diff --git a/src/main.rs b/src/main.rs index 943cca4..b08d5eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ mod cli; mod cmd_new; +mod cmd_run; mod runtime; mod template; @@ -15,7 +16,12 @@ fn main() { std::process::exit(1); } } - Command::Run => eprintln!("run: not yet implemented"), + Command::Run => { + if let Err(e) = cmd_run::run(std::path::Path::new(".")) { + eprintln!("error: {e}"); + std::process::exit(1); + } + } Command::Create { .. } => eprintln!("create: not yet implemented"), Command::Add { .. } => eprintln!("add: not yet implemented"), } From acaee0d7e0d6f3c8dc26055a30ff98e6f2a2d51f Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:13:38 -0500 Subject: [PATCH 10/22] feat: tree-sitter import + @Module array wiring with revert-on-break Signed-off-by: Diego Resendez --- src/main.rs | 1 + src/wire.rs | 191 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 192 insertions(+) create mode 100644 src/wire.rs diff --git a/src/main.rs b/src/main.rs index b08d5eb..3bae357 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ mod cmd_new; mod cmd_run; mod runtime; mod template; +mod wire; use clap::Parser; use cli::{Cli, Command}; diff --git a/src/wire.rs b/src/wire.rs new file mode 100644 index 0000000..a75ceca --- /dev/null +++ b/src/wire.rs @@ -0,0 +1,191 @@ +//! 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` 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. +#[allow(dead_code)] +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 +} + +/// 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. +#[allow(dead_code)] +pub fn add_import(src: &str, symbol: &str, from: &str) -> String { + 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) { + 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 `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). +#[allow(dead_code)] +pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> 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 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 anywhere in the tree (first match wins). +fn find_array(root: &Node, src: &str, key: &str) -> Option<(usize, usize, String)> { + fn visit(node: Node, src: &str, key: &str) -> Option<(usize, usize, String)> { + if node.kind() == "pair" { + if let Some(k) = node.child_by_field_name("key") { + if k.utf8_text(src.as_bytes()).ok() == Some(key) { + if let Some(v) = node.child_by_field_name("value") { + if v.kind() == "array" { + 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)); + } + } + } + } + } + let mut c = node.walk(); + for child in node.children(&mut c) { + if let Some(r) = visit(child, src, key) { + return Some(r); + } + } + None + } + visit(*root, src, key) +} + +#[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()); + } +} From 4df1e7ce7bc279928f0b0411607a90822ca3c4f7 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:20:39 -0500 Subject: [PATCH 11/22] fix(wire): scope @Module array search to the Module decorator, not any object literal Signed-off-by: Diego Resendez --- src/wire.rs | 95 ++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 80 insertions(+), 15 deletions(-) diff --git a/src/wire.rs b/src/wire.rs index a75ceca..de65ec0 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -109,32 +109,82 @@ 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 anywhere in the tree (first match wins). +/// `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)> { - fn visit(node: Node, src: &str, key: &str) -> Option<(usize, usize, String)> { - if node.kind() == "pair" { - if let Some(k) = node.child_by_field_name("key") { - if k.utf8_text(src.as_bytes()).ok() == Some(key) { - if let Some(v) = node.child_by_field_name("value") { - if v.kind() == "array" { - 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)); - } - } + 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 +} + +/// 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> { + fn find_decorator_call<'a>(node: Node<'a>, src: &str) -> Option> { + 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) = visit(child, src, key) { + if let Some(r) = find_decorator_call(child, src) { return Some(r); } } None } - visit(*root, src, key) + + 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)] @@ -188,4 +238,19 @@ export class AppModule {} let out = add_to_module_array(MOD, "controllers", "X]; class Evil {"); assert!(out.is_none()); } + + #[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] }")); + } } From 13b77b39994bcd1b39f437c44b78e2ad4d5b5ac2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:24:29 -0500 Subject: [PATCH 12/22] feat: matcha create controller with tree-sitter auto-wire + emit-only fallback Signed-off-by: Diego Resendez --- src/cmd_create.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 8 ++++++- src/wire.rs | 2 -- tests/create.rs | 23 +++++++++++++++++++ 4 files changed, 88 insertions(+), 3 deletions(-) create mode 100644 src/cmd_create.rs create mode 100644 tests/create.rs diff --git a/src/cmd_create.rs b/src/cmd_create.rs new file mode 100644 index 0000000..5bece6a --- /dev/null +++ b/src/cmd_create.rs @@ -0,0 +1,58 @@ +//! `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), + "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) -> 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"); + } + } + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index 3bae357..808e1e7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ mod cli; +mod cmd_create; mod cmd_new; mod cmd_run; mod runtime; @@ -23,7 +24,12 @@ fn main() { std::process::exit(1); } } - Command::Create { .. } => eprintln!("create: not yet implemented"), + Command::Create { kind, name, check } => { + if let Err(e) = cmd_create::run(&kind, &name, check) { + eprintln!("error: {e}"); + std::process::exit(1); + } + } Command::Add { .. } => eprintln!("add: not yet implemented"), } } diff --git a/src/wire.rs b/src/wire.rs index de65ec0..068b47a 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -52,7 +52,6 @@ fn has_error(node: Node) -> bool { /// 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. -#[allow(dead_code)] pub fn add_import(src: &str, symbol: &str, from: &str) -> String { let line = format!("import {{ {symbol} }} from '{from}';"); if src.contains(&line) { @@ -84,7 +83,6 @@ pub fn add_import(src: &str, symbol: &str, from: &str) -> String { /// 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). -#[allow(dead_code)] pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option { let tree = parser().parse(src, None).unwrap(); let (open, close, existing) = find_array(&tree.root_node(), src, key)?; diff --git a/tests/create.rs b/tests/create.rs new file mode 100644 index 0000000..fb747bf --- /dev/null +++ b/tests/create.rs @@ -0,0 +1,23 @@ +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 }")); +} From e99dd58c669f1891e6dce936dad30961ba1c3e10 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:28:40 -0500 Subject: [PATCH 13/22] feat: optional --check delegates type-check to detected runtime Signed-off-by: Diego Resendez --- src/check.rs | 38 ++++++++++++++++++++++++++++++++++++++ src/cmd_create.rs | 15 ++++++++++++--- src/main.rs | 1 + 3 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 src/check.rs diff --git a/src/check.rs b/src/check.rs new file mode 100644 index 0000000..6327efc --- /dev/null +++ b/src/check.rs @@ -0,0 +1,38 @@ +use std::path::Path; +use crate::runtime::{self, Runtime}; + +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 { + 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"])); + } +} diff --git a/src/cmd_create.rs b/src/cmd_create.rs index 5bece6a..ada2ac4 100644 --- a/src/cmd_create.rs +++ b/src/cmd_create.rs @@ -19,16 +19,16 @@ fn controller_stub(name: &str) -> String { lower = name.to_lowercase(), name = name) } -pub fn run(kind: &str, name: &str, _check: bool) -> std::io::Result<()> { +pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> { match kind { - "controller" => create_controller(name), + "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) -> 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())); std::fs::create_dir_all(file.parent().unwrap())?; @@ -54,5 +54,14 @@ fn create_controller(name: &str) -> std::io::Result<()> { 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(()) } diff --git a/src/main.rs b/src/main.rs index 808e1e7..8a665f4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod check; mod cli; mod cmd_create; mod cmd_new; From 1b9990f02a3dc17c2c15beabf464e47b49416f8c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:33:32 -0500 Subject: [PATCH 14/22] feat: matcha add appends capability handler to the controller Signed-off-by: Diego Resendez --- src/cmd_add.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 8 +++++- src/wire.rs | 53 +++++++++++++++++++++++++++++++++++ tests/add.rs | 19 +++++++++++++ 4 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 src/cmd_add.rs create mode 100644 tests/add.rs 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 }")); +} From 87d7e185d7c6967cd20154a30696d5b16e9f4132 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:38:09 -0500 Subject: [PATCH 15/22] test(add): cover insert_method revert/not-found paths and only_controller errors Signed-off-by: Diego Resendez --- src/wire.rs | 13 +++++++++++++ tests/add.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/wire.rs b/src/wire.rs index e8b88ee..38709c7 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -304,4 +304,17 @@ export class AppModule {} // ...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()); + } } diff --git a/tests/add.rs b/tests/add.rs index 988836a..f093b20 100644 --- a/tests/add.rs +++ b/tests/add.rs @@ -17,3 +17,29 @@ fn add_sse_appends_handler() { 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_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); +} From bc013fde9f06c2f3802a37a59980f9b76d27a011 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:39:37 -0500 Subject: [PATCH 16/22] docs: matcha README with usage and runtime detection Signed-off-by: Diego Resendez --- .gitignore | 1 + README.md | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 README.md diff --git a/.gitignore b/.gitignore index ea8c4bf..0f987d2 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +.superpowers/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..73f5dfc --- /dev/null +++ b/README.md @@ -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 ` (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`). From 757b72998682c3f88a22334c0b9bb6e74f1272ab Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 11 Jul 2026 13:52:21 -0500 Subject: [PATCH 17/22] fix(add): merge imports into existing brace + capability idempotency; fmt - wire::add_import now merges a new symbol into an already-present `import { ... } 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 ` 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 --- src/check.rs | 28 ++++++++--- src/cmd_add.rs | 46 ++++++++++++----- src/cmd_create.rs | 20 +++++--- src/cmd_new.rs | 18 ++++--- src/cmd_run.rs | 20 +++++--- src/wire.rs | 125 +++++++++++++++++++++++++++++++++++++++++++--- tests/add.rs | 62 +++++++++++++++++++---- tests/cli.rs | 20 +++++--- tests/create.rs | 21 +++++--- tests/new.rs | 48 ++++++++++++++---- 10 files changed, 329 insertions(+), 79 deletions(-) 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 } From 277e0bd289d8c412b7409337eabd8ca0c2e89742 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 13:01:34 -0500 Subject: [PATCH 18/22] chore: adopt calver versioning (26.7.0) Signed-off-by: Diego Resendez --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bb13815..8ce9aa7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -254,7 +254,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "matcha" -version = "0.1.0" +version = "26.7.0" dependencies = [ "assert_cmd", "clap", diff --git a/Cargo.toml b/Cargo.toml index 234a9a3..018d6f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "matcha" -version = "0.1.0" +version = "26.7.0" edition = "2021" [[bin]] From 3f86841d4b4560637d6254383703f7f6d9bbf1d9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 13:11:12 -0500 Subject: [PATCH 19/22] feat(new): multi-runtime starter (node/deno/bun) via --runtime, shared + overlay templates Signed-off-by: Diego Resendez --- .specs/2026-07-12-matcha-multi-runtime.md | 152 ++++++++++++++++++ src/cli.rs | 2 + src/cmd_new.rs | 11 +- src/cmd_run.rs | 7 +- src/main.rs | 8 +- src/template.rs | 66 +++++++- template/runtimes/bun/matcha.toml | 1 + template/runtimes/bun/package.json | 7 + template/runtimes/bun/src/main.ts | 7 + template/runtimes/bun/tsconfig.json | 10 ++ template/{starter => runtimes/deno}/deno.json | 0 .../{starter => runtimes/deno}/matcha.toml | 0 .../{starter => runtimes/deno}/src/main.ts | 0 template/runtimes/node/matcha.toml | 1 + template/runtimes/node/package.json | 8 + template/runtimes/node/src/main.ts | 7 + template/runtimes/node/tsconfig.json | 10 ++ .../{starter => shared}/public/index.html | 0 .../{starter => shared}/src/app.module.ts | 0 .../src/controllers/home.controller.ts | 0 tests/new.rs | 44 +++++ 21 files changed, 325 insertions(+), 16 deletions(-) create mode 100644 .specs/2026-07-12-matcha-multi-runtime.md create mode 100644 template/runtimes/bun/matcha.toml create mode 100644 template/runtimes/bun/package.json create mode 100644 template/runtimes/bun/src/main.ts create mode 100644 template/runtimes/bun/tsconfig.json rename template/{starter => runtimes/deno}/deno.json (100%) rename template/{starter => runtimes/deno}/matcha.toml (100%) rename template/{starter => runtimes/deno}/src/main.ts (100%) create mode 100644 template/runtimes/node/matcha.toml create mode 100644 template/runtimes/node/package.json create mode 100644 template/runtimes/node/src/main.ts create mode 100644 template/runtimes/node/tsconfig.json rename template/{starter => shared}/public/index.html (100%) rename template/{starter => shared}/src/app.module.ts (100%) rename template/{starter => shared}/src/controllers/home.controller.ts (100%) diff --git a/.specs/2026-07-12-matcha-multi-runtime.md b/.specs/2026-07-12-matcha-multi-runtime.md new file mode 100644 index 0000000..72f52d0 --- /dev/null +++ b/.specs/2026-07-12-matcha-multi-runtime.md @@ -0,0 +1,152 @@ +# matcha β€” multi-runtime starter (node/deno/bun) Β· Spec + +**Date:** 2026-07-12 +**Branch:** `feature/matcha-multi-runtime` (off `develop`) +**Goal:** `matcha new --runtime ` scaffolds the starter for the chosen runtime. Shared app files are written once; only `main.ts` + runtime config + `matcha.toml` differ per runtime. Default runtime: **deno**. + +## Verified framework facts (from Green-Tea/core) +- `@green-tea/core` imports `reflect-metadata` internally (`src/index.ts:6`) β€” consumers need NO explicit import; it installs transitively with the package. +- Serve per runtime: Node `app.listen(3000)`; Deno `Deno.serve({ port }, app.fetch)`; Bun `Bun.serve({ port, fetch: app.fetch })`. Starter has no WebSocket, so `app.fetch` is sufficient (no `serveDeno`/`serveBun`). +- `@Module` requires `mountpoint`. Package version pin: `^26.7.0-beta.0`. + +## New template layout (replaces `template/starter/`) +``` +template/ + shared/ + public/index.html + src/app.module.ts + src/controllers/home.controller.ts + runtimes/ + deno/ { matcha.toml, deno.json, src/main.ts } + node/ { matcha.toml, package.json, tsconfig.json, src/main.ts } + bun/ { matcha.toml, package.json, tsconfig.json, src/main.ts } +``` +`write_starter` writes `shared` then overlays the chosen runtime dir on top (both go into the same project dir; `src/main.ts` from the overlay lands beside `src/app.module.ts` from shared). Token substitution `{{project_name}}` applies to every copied file (now also `package.json` "name"). + +## Exact file contents + +### shared/ (moved verbatim from current `template/starter/`) +- `public/index.html` β€” unchanged (keep `{{project_name}}` title + `EventSource('/zen')`). +- `src/app.module.ts` β€” unchanged (`@Module({ mountpoint: '/', controllers: [HomeController] })`). +- `src/controllers/home.controller.ts` β€” unchanged (`@Route('/')`, `@Get('/') @Html('public/index.html')`, `@Sse('/zen')` rotating zen every 30s). + +### runtimes/deno/ (moved from current starter) +- `matcha.toml`: `runtime = "deno"` +- `deno.json` (unchanged from current starter): +```json +{ + "compilerOptions": { "experimentalDecorators": true }, + "unstable": ["sloppy-imports"], + "imports": { "@green-tea/core": "npm:@green-tea/core@^26.7.0-beta.0" }, + "tasks": { "dev": "deno run --watch --allow-net --allow-read --allow-env src/main.ts" } +} +``` +- `src/main.ts`: +```ts +import { createApp } from '@green-tea/core'; +import { AppModule } from './app.module'; + +const app = createApp({ modules: [AppModule] }); + +Deno.serve({ port: 8000 }, app.fetch); +console.log('🍡 green-tea running on http://localhost:8000'); +``` + +### runtimes/node/ +- `matcha.toml`: `runtime = "node"` +- `package.json`: +```json +{ + "name": "{{project_name}}", + "type": "module", + "private": true, + "scripts": { "dev": "tsx watch src/main.ts" }, + "dependencies": { "@green-tea/core": "^26.7.0-beta.0" }, + "devDependencies": { "tsx": "^4", "typescript": "^5" } +} +``` +- `tsconfig.json`: +```json +{ + "compilerOptions": { + "target": "es2020", + "module": "esnext", + "moduleResolution": "bundler", + "experimentalDecorators": true, + "strict": true, + "skipLibCheck": true + } +} +``` +- `src/main.ts`: +```ts +import { createApp } from '@green-tea/core'; +import { AppModule } from './app.module'; + +const app = createApp({ modules: [AppModule] }); + +app.listen(3000); +console.log('🍡 green-tea running on http://localhost:3000'); +``` + +### runtimes/bun/ +- `matcha.toml`: `runtime = "bun"` +- `package.json`: +```json +{ + "name": "{{project_name}}", + "type": "module", + "private": true, + "scripts": { "dev": "bun --watch run src/main.ts" }, + "dependencies": { "@green-tea/core": "^26.7.0-beta.0" } +} +``` +- `tsconfig.json`: +```json +{ + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "experimentalDecorators": true, + "strict": true, + "skipLibCheck": true + } +} +``` +- `src/main.ts`: +```ts +import { createApp } from '@green-tea/core'; +import { AppModule } from './app.module'; + +const app = createApp({ modules: [AppModule] }); + +Bun.serve({ port: 8000, fetch: app.fetch }); +console.log('🍡 green-tea running on http://localhost:8000'); +``` + +## Code changes + +### `src/template.rs` +- Replace the single `STARTER` embed with `SHARED` + three runtime overlays (`include_dir!` each). +- `pub fn write_starter(dest: &Path, project_name: &str, runtime: Runtime) -> io::Result<()>` β€” write `SHARED`, then the overlay for `runtime`. Keep `write_dir` substitution logic. + +### `src/cli.rs` +- `Command::New` gains `#[arg(long, default_value = "deno", value_parser = ["node", "deno", "bun"])] runtime: String`. + +### `src/cmd_new.rs` +- `run(name, template_url, runtime: &str)`: parse `runtime` via `Runtime::from_str` (already in `runtime.rs`); for the starter (no `--template-url`) path, call `write_starter(dest, name, rt)`. `--template-url` path ignores `--runtime`. + +### `src/cmd_run.rs` +- Change the Bun mapping from `("bun", vec!["--watch", "run", "dev"])` to `("bun", vec!["run", "dev"])` so all three uniformly run their `dev` script (deno.json/package.json define the watch). Update the `bun_watch` unit test accordingly. + +### `src/main.rs` +- Pass the new `runtime` arg through the `Command::New` dispatch. + +## Tests +- `template.rs`: parametrize the write test β€” assert deno writes `deno.json` + `src/main.ts` containing `Deno.serve`; node writes `package.json` (with substituted name) + `tsconfig.json` + `main.ts` containing `app.listen`; bun writes `package.json` + `main.ts` containing `Bun.serve`. All three write the shared `src/app.module.ts` and `public/index.html`. +- `tests/new.rs`: `matcha new demo --runtime node` produces `package.json` with `"name": "demo"` and no `deno.json`; default (no flag) produces `deno.json`. +- `cmd_run.rs`: bun mapping test expects `("bun", vec!["run", "dev"])`. + +## Out of scope +Edge starter (deploy target, not `run`). Per-runtime lockfiles. `serveDeno`/`serveBun` (no WS in starter). diff --git a/src/cli.rs b/src/cli.rs index f26f88b..80b17e3 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -14,6 +14,8 @@ pub enum Command { name: String, #[arg(long)] template_url: Option, + #[arg(long, default_value = "deno", value_parser = ["node", "deno", "bun"])] + runtime: String, }, /// Detect the runtime and run the project in watch mode Run, diff --git a/src/cmd_new.rs b/src/cmd_new.rs index 4d0072d..0b111ab 100644 --- a/src/cmd_new.rs +++ b/src/cmd_new.rs @@ -1,9 +1,10 @@ use std::io::{Error, ErrorKind}; use std::path::Path; +use crate::runtime::Runtime; use crate::template; -pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> { +pub fn run(name: &str, template_url: Option<&str>, runtime: &str) -> std::io::Result<()> { let dest = Path::new(name); if dest.exists() { return Err(Error::new( @@ -14,8 +15,14 @@ pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> { match template_url { None => { + let rt = Runtime::from_str(runtime).ok_or_else(|| { + Error::new( + ErrorKind::InvalidInput, + format!("unknown runtime '{runtime}'"), + ) + })?; std::fs::create_dir_all(dest)?; - template::write_starter(dest, name)?; + template::write_starter(dest, name, rt)?; } Some(url) => clone_template(url, dest)?, } diff --git a/src/cmd_run.rs b/src/cmd_run.rs index 28cb2df..8b6d7f5 100644 --- a/src/cmd_run.rs +++ b/src/cmd_run.rs @@ -6,7 +6,7 @@ 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::Bun => ("bun", vec!["run", "dev"]), Runtime::Node => ("npm", vec!["run", "dev"]), } } @@ -38,10 +38,7 @@ 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!["run", "dev"])); } #[test] fn node_watch() { diff --git a/src/main.rs b/src/main.rs index ea02138..ce41459 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,8 +14,12 @@ use cli::{Cli, Command}; fn main() { let cli = Cli::parse(); match cli.command { - Command::New { name, template_url } => { - if let Err(e) = cmd_new::run(&name, template_url.as_deref()) { + Command::New { + name, + template_url, + runtime, + } => { + if let Err(e) = cmd_new::run(&name, template_url.as_deref(), &runtime) { eprintln!("error: {e}"); std::process::exit(1); } diff --git a/src/template.rs b/src/template.rs index 1f180c2..267ff60 100644 --- a/src/template.rs +++ b/src/template.rs @@ -1,10 +1,24 @@ use include_dir::{include_dir, Dir}; use std::path::Path; -pub static STARTER: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/starter"); +use crate::runtime::Runtime; -pub fn write_starter(dest: &Path, project_name: &str) -> std::io::Result<()> { - write_dir(&STARTER, dest, project_name) +pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared"); +pub static RUNTIME_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno"); +pub static RUNTIME_NODE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/node"); +pub static RUNTIME_BUN: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/bun"); + +fn overlay_for(runtime: Runtime) -> &'static Dir<'static> { + match runtime { + Runtime::Deno => &RUNTIME_DENO, + Runtime::Node => &RUNTIME_NODE, + Runtime::Bun => &RUNTIME_BUN, + } +} + +pub fn write_starter(dest: &Path, project_name: &str, runtime: Runtime) -> std::io::Result<()> { + write_dir(&SHARED, dest, project_name)?; + write_dir(overlay_for(runtime), dest, project_name) } fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> { @@ -36,16 +50,54 @@ mod tests { use tempfile::tempdir; #[test] - fn writes_starter_and_substitutes_name() { + fn deno_writes_shared_and_deno_overlay() { let d = tempdir().unwrap(); - write_starter(d.path(), "my-api").unwrap(); + write_starter(d.path(), "my-api", Runtime::Deno).unwrap(); + let html = std::fs::read_to_string(d.path().join("public/index.html")).unwrap(); assert!(html.contains("my-api")); assert!(!html.contains("{{project_name}}")); assert!(d.path().join("src/controllers/home.controller.ts").exists()); - assert!(d.path().join("matcha.toml").exists()); - assert!(d.path().join("src/main.ts").exists()); let module = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap(); assert!(module.contains("mountpoint")); + + assert!(d.path().join("deno.json").exists()); + assert!(d.path().join("matcha.toml").exists()); + let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap(); + assert!(main.contains("Deno.serve")); + assert!(!d.path().join("package.json").exists()); + } + + #[test] + fn node_writes_shared_and_node_overlay() { + let d = tempdir().unwrap(); + write_starter(d.path(), "my-api", Runtime::Node).unwrap(); + + assert!(d.path().join("public/index.html").exists()); + assert!(d.path().join("src/app.module.ts").exists()); + + let pkg = std::fs::read_to_string(d.path().join("package.json")).unwrap(); + assert!(pkg.contains("\"name\": \"my-api\"")); + assert!(!pkg.contains("{{project_name}}")); + assert!(d.path().join("tsconfig.json").exists()); + let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap(); + assert!(main.contains("app.listen")); + assert!(!d.path().join("deno.json").exists()); + } + + #[test] + fn bun_writes_shared_and_bun_overlay() { + let d = tempdir().unwrap(); + write_starter(d.path(), "my-api", Runtime::Bun).unwrap(); + + assert!(d.path().join("public/index.html").exists()); + assert!(d.path().join("src/app.module.ts").exists()); + + let pkg = std::fs::read_to_string(d.path().join("package.json")).unwrap(); + assert!(pkg.contains("\"name\": \"my-api\"")); + assert!(!pkg.contains("{{project_name}}")); + let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap(); + assert!(main.contains("Bun.serve")); + assert!(!d.path().join("deno.json").exists()); } } diff --git a/template/runtimes/bun/matcha.toml b/template/runtimes/bun/matcha.toml new file mode 100644 index 0000000..a426864 --- /dev/null +++ b/template/runtimes/bun/matcha.toml @@ -0,0 +1 @@ +runtime = "bun" diff --git a/template/runtimes/bun/package.json b/template/runtimes/bun/package.json new file mode 100644 index 0000000..b8b3863 --- /dev/null +++ b/template/runtimes/bun/package.json @@ -0,0 +1,7 @@ +{ + "name": "{{project_name}}", + "type": "module", + "private": true, + "scripts": { "dev": "bun --watch run src/main.ts" }, + "dependencies": { "@green-tea/core": "^26.7.0-beta.0" } +} diff --git a/template/runtimes/bun/src/main.ts b/template/runtimes/bun/src/main.ts new file mode 100644 index 0000000..34586a8 --- /dev/null +++ b/template/runtimes/bun/src/main.ts @@ -0,0 +1,7 @@ +import { createApp } from '@green-tea/core'; +import { AppModule } from './app.module'; + +const app = createApp({ modules: [AppModule] }); + +Bun.serve({ port: 8000, fetch: app.fetch }); +console.log('🍡 green-tea running on http://localhost:8000'); diff --git a/template/runtimes/bun/tsconfig.json b/template/runtimes/bun/tsconfig.json new file mode 100644 index 0000000..4974940 --- /dev/null +++ b/template/runtimes/bun/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "experimentalDecorators": true, + "strict": true, + "skipLibCheck": true + } +} diff --git a/template/starter/deno.json b/template/runtimes/deno/deno.json similarity index 100% rename from template/starter/deno.json rename to template/runtimes/deno/deno.json diff --git a/template/starter/matcha.toml b/template/runtimes/deno/matcha.toml similarity index 100% rename from template/starter/matcha.toml rename to template/runtimes/deno/matcha.toml diff --git a/template/starter/src/main.ts b/template/runtimes/deno/src/main.ts similarity index 100% rename from template/starter/src/main.ts rename to template/runtimes/deno/src/main.ts diff --git a/template/runtimes/node/matcha.toml b/template/runtimes/node/matcha.toml new file mode 100644 index 0000000..0d7f6fa --- /dev/null +++ b/template/runtimes/node/matcha.toml @@ -0,0 +1 @@ +runtime = "node" diff --git a/template/runtimes/node/package.json b/template/runtimes/node/package.json new file mode 100644 index 0000000..69f153d --- /dev/null +++ b/template/runtimes/node/package.json @@ -0,0 +1,8 @@ +{ + "name": "{{project_name}}", + "type": "module", + "private": true, + "scripts": { "dev": "tsx watch src/main.ts" }, + "dependencies": { "@green-tea/core": "^26.7.0-beta.0" }, + "devDependencies": { "tsx": "^4", "typescript": "^5" } +} diff --git a/template/runtimes/node/src/main.ts b/template/runtimes/node/src/main.ts new file mode 100644 index 0000000..c7521ae --- /dev/null +++ b/template/runtimes/node/src/main.ts @@ -0,0 +1,7 @@ +import { createApp } from '@green-tea/core'; +import { AppModule } from './app.module'; + +const app = createApp({ modules: [AppModule] }); + +app.listen(3000); +console.log('🍡 green-tea running on http://localhost:3000'); diff --git a/template/runtimes/node/tsconfig.json b/template/runtimes/node/tsconfig.json new file mode 100644 index 0000000..4a15361 --- /dev/null +++ b/template/runtimes/node/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "es2020", + "module": "esnext", + "moduleResolution": "bundler", + "experimentalDecorators": true, + "strict": true, + "skipLibCheck": true + } +} diff --git a/template/starter/public/index.html b/template/shared/public/index.html similarity index 100% rename from template/starter/public/index.html rename to template/shared/public/index.html diff --git a/template/starter/src/app.module.ts b/template/shared/src/app.module.ts similarity index 100% rename from template/starter/src/app.module.ts rename to template/shared/src/app.module.ts diff --git a/template/starter/src/controllers/home.controller.ts b/template/shared/src/controllers/home.controller.ts similarity index 100% rename from template/starter/src/controllers/home.controller.ts rename to template/shared/src/controllers/home.controller.ts diff --git a/tests/new.rs b/tests/new.rs index 4f34b40..e5e2083 100644 --- a/tests/new.rs +++ b/tests/new.rs @@ -16,6 +16,50 @@ fn new_scaffolds_into_named_dir() { assert!(root.join("public/index.html").exists()); } +#[test] +fn new_default_runtime_is_deno() { + let d = tempdir().unwrap(); + Command::cargo_bin("matcha") + .unwrap() + .current_dir(d.path()) + .args(["new", "my-api"]) + .assert() + .success(); + let root = d.path().join("my-api"); + assert!(root.join("deno.json").exists()); + assert!(!root.join("package.json").exists()); +} + +#[test] +fn new_with_node_runtime_produces_package_json() { + let d = tempdir().unwrap(); + Command::cargo_bin("matcha") + .unwrap() + .current_dir(d.path()) + .args(["new", "demo", "--runtime", "node"]) + .assert() + .success(); + let root = d.path().join("demo"); + let pkg = std::fs::read_to_string(root.join("package.json")).unwrap(); + assert!(pkg.contains("\"name\": \"demo\"")); + assert!(!root.join("deno.json").exists()); +} + +#[test] +fn new_with_bun_runtime_produces_package_json() { + let d = tempdir().unwrap(); + Command::cargo_bin("matcha") + .unwrap() + .current_dir(d.path()) + .args(["new", "demo-bun", "--runtime", "bun"]) + .assert() + .success(); + let root = d.path().join("demo-bun"); + let pkg = std::fs::read_to_string(root.join("package.json")).unwrap(); + assert!(pkg.contains("\"name\": \"demo-bun\"")); + assert!(!root.join("deno.json").exists()); +} + #[test] fn new_refuses_existing_dir() { let d = tempdir().unwrap(); From 685c51b7e06ab24ed79f5a77857320a704b76806 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 13:13:02 -0500 Subject: [PATCH 20/22] fix(new): default runtime is node (framework is node-first) Signed-off-by: Diego Resendez --- src/cli.rs | 2 +- tests/new.rs | 22 +++++++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 80b17e3..553806f 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -14,7 +14,7 @@ pub enum Command { name: String, #[arg(long)] template_url: Option, - #[arg(long, default_value = "deno", value_parser = ["node", "deno", "bun"])] + #[arg(long, default_value = "node", value_parser = ["node", "deno", "bun"])] runtime: String, }, /// Detect the runtime and run the project in watch mode diff --git a/tests/new.rs b/tests/new.rs index e5e2083..f5d1cb5 100644 --- a/tests/new.rs +++ b/tests/new.rs @@ -17,15 +17,31 @@ fn new_scaffolds_into_named_dir() { } #[test] -fn new_default_runtime_is_deno() { +fn new_default_runtime_is_node() { let d = tempdir().unwrap(); Command::cargo_bin("matcha") .unwrap() .current_dir(d.path()) - .args(["new", "my-api"]) + .args(["new", "demo"]) .assert() .success(); - let root = d.path().join("my-api"); + let root = d.path().join("demo"); + let pkg = std::fs::read_to_string(root.join("package.json")).unwrap(); + assert!(pkg.contains("\"name\": \"demo\"")); + assert!(root.join("tsconfig.json").exists()); + assert!(!root.join("deno.json").exists()); +} + +#[test] +fn new_with_deno_runtime_produces_deno_json() { + let d = tempdir().unwrap(); + Command::cargo_bin("matcha") + .unwrap() + .current_dir(d.path()) + .args(["new", "demo-deno", "--runtime", "deno"]) + .assert() + .success(); + let root = d.path().join("demo-deno"); assert!(root.join("deno.json").exists()); assert!(!root.join("package.json").exists()); } From 4985adad00cedbd00dc715883d32cd57690ce608 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 13:16:27 -0500 Subject: [PATCH 21/22] chore: drop now-stale dead_code allows in runtime.rs; spec default=node erratum Signed-off-by: Diego Resendez --- .specs/2026-07-12-matcha-multi-runtime.md | 2 +- src/runtime.rs | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/.specs/2026-07-12-matcha-multi-runtime.md b/.specs/2026-07-12-matcha-multi-runtime.md index 72f52d0..b2f1beb 100644 --- a/.specs/2026-07-12-matcha-multi-runtime.md +++ b/.specs/2026-07-12-matcha-multi-runtime.md @@ -2,7 +2,7 @@ **Date:** 2026-07-12 **Branch:** `feature/matcha-multi-runtime` (off `develop`) -**Goal:** `matcha new --runtime ` scaffolds the starter for the chosen runtime. Shared app files are written once; only `main.ts` + runtime config + `matcha.toml` differ per runtime. Default runtime: **deno**. +**Goal:** `matcha new --runtime ` scaffolds the starter for the chosen runtime. Shared app files are written once; only `main.ts` + runtime config + `matcha.toml` differ per runtime. Default runtime: **node** (green-tea is developed node-first; Node is the reference implementation. deno/bun via `--runtime`). ## Verified framework facts (from Green-Tea/core) - `@green-tea/core` imports `reflect-metadata` internally (`src/index.ts:6`) β€” consumers need NO explicit import; it installs transitively with the package. diff --git a/src/runtime.rs b/src/runtime.rs index 773e1c0..99070b7 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -1,6 +1,5 @@ use std::path::Path; -#[allow(dead_code)] #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Runtime { Node, @@ -9,7 +8,6 @@ pub enum Runtime { } impl Runtime { - #[allow(dead_code)] pub fn from_str(s: &str) -> Option { match s.trim() { "node" => Some(Runtime::Node), @@ -20,13 +18,11 @@ impl Runtime { } } -#[allow(dead_code)] fn exists(dir: &Path, name: &str) -> bool { dir.join(name).exists() } /// Reads `runtime = "..."` from matcha.toml without a TOML dep (one field only). -#[allow(dead_code)] fn override_from_toml(dir: &Path) -> Option { let text = std::fs::read_to_string(dir.join("matcha.toml")).ok()?; for line in text.lines() { @@ -39,7 +35,6 @@ fn override_from_toml(dir: &Path) -> Option { None } -#[allow(dead_code)] pub fn detect(dir: &Path) -> Option { if let Some(r) = override_from_toml(dir) { return Some(r); From 04e20cfccfa3b2684e3554f3b709c2fd8599bb1c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 12 Jul 2026 16:35:21 -0500 Subject: [PATCH 22/22] chore: stop tracking AI/scratch docs (.specs); keep tree to project docs only Signed-off-by: Diego Resendez --- .gitignore | 1 + .specs/2026-07-11-matcha-cli-design.md | 141 --- .specs/2026-07-11-matcha-cli-plan.md | 1402 --------------------- .specs/2026-07-12-matcha-multi-runtime.md | 152 --- 4 files changed, 1 insertion(+), 1695 deletions(-) delete mode 100644 .specs/2026-07-11-matcha-cli-design.md delete mode 100644 .specs/2026-07-11-matcha-cli-plan.md delete mode 100644 .specs/2026-07-12-matcha-multi-runtime.md diff --git a/.gitignore b/.gitignore index 0f987d2..7631c5e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target .superpowers/ +.specs/ diff --git a/.specs/2026-07-11-matcha-cli-design.md b/.specs/2026-07-11-matcha-cli-design.md deleted file mode 100644 index 208f3c8..0000000 --- a/.specs/2026-07-11-matcha-cli-design.md +++ /dev/null @@ -1,141 +0,0 @@ -# matcha β€” green-tea CLI Β· Design - -**Date:** 2026-07-11 -**Status:** Approved (brainstorming), pending spec review -**Repo:** `Green-Tea/matcha` (separate repo, Rust β€” created by Diego) -**Relates to:** `Green-Tea/core` (the green-tea framework) - -## 1. What it is - -`matcha` is the developer-experience CLI for the green-tea HTTP framework. A -single **native binary written in Rust**, distributed independently of the -framework. It does not require a JS runtime to *install or operate*; it only -*delegates* to the project's runtime when it needs to run or type-check the -project. - -**Name rationale:** matcha *is* premium green tea β€” on-brand, distinctive, no -CLI collision (`gt`=Graphite, `tea`=Gitea's CLI, `gtea`β‰ˆgitea were all ruled -out). Crate `matcha`, brew `matcha`, repo `Green-Tea/matcha`. - -## 2. Command surface - -``` -matcha new [--template-url gh:owner/repo] # scaffold a project -matcha run # detect runtime, run in watch -matcha create # generate a piece + auto-wire -matcha add # add a capability to a file -``` - -`new` scaffolds **projects**; `create` scaffolds **pieces inside** a project. -This split retires the earlier ambiguous `create app`. - -## 3. `matcha new` - -- No flag β†’ **official `starter` template, embedded in the binary** - (`include_dir!`), zero network. -- `--template-url gh:owner/repo` β†’ `git clone --depth 1` of the given repo. - `git` is ubiquitous on dev machines, so the binary carries **no HTTP/TLS - dependency**. This opens a bring-your-own-template ecosystem while we - maintain only one official template. -- Token substitution on copy is minimal: `{{project_name}}`. Nothing more. - -### The official `starter` (the "wow") - -A live app the moment you run it β€” the create-react-app effect: - -- Serves an `index.html` showing the **green-tea logo** (demonstrates - `@Html` static serving). -- A `@Sse('/zen')` endpoint that streams a **rotating zen message every 30 - seconds** (demonstrates live streaming). The page subscribes via - `EventSource('/zen')` and updates the zen line under the logo, untouched by - the user. - -Faithful to the real framework API (verified in `core`): - -```ts -@Route('/') -class HomeController { - @Get('/') - @Html('public/index.html') - home() {} - - @Sse('/zen') - zen() { - const messages = [/* zen lines */]; - return (async function* () { - for (let i = 0; ; i++) { - yield { zen: messages[i % messages.length] }; - await new Promise((r) => setTimeout(r, 30_000)); - } - })(); - } -} -``` - -Starter layout: - -``` -/ - src/app.module.ts # @Module wiring HomeController - src/controllers/home.controller.ts - public/index.html # logo + EventSource('/zen') - # deno.json | package.json | ... - matcha.toml # optional runtime override -``` - -## 4. `matcha run` β€” runtime detection - -Precedence (first match wins): - -1. `matcha.toml` `runtime` field β€” explicit override -2. `deno.json(c)` β†’ **deno** -3. `bun.lock(b)` β†’ **bun** -4. `package.json` β†’ **node** - -Runs the project's entry in watch mode by wrapping the detected runtime. -**Edge is not a `run` target in v1** β€” it deploys, it does not run locally. - -## 5. `create` / `add` β€” codegen - -Three distinct jobs, three tools: - -- **Edit** β†’ `tree-sitter` + `tree-sitter-typescript` (in-process, no runtime). - Inserts the `import` and adds the class to the right `@Module` array - (`controllers` / `providers` / steps) via range-based splice that preserves - the file's existing formatting byte-for-byte. -- **Syntax check** β†’ re-parse with tree-sitter. If an `ERROR` node appears, the - edit broke structure β†’ **revert, leave the file untouched**. Free, in-process. -- **Semantic check (optional)** β†’ if a `tsconfig` / `deno.json` is present, run - `tsc --noEmit` / `deno check` with the detected runtime. Behind `--check` - (or automatic when config is present). This is the lazy-correct alternative - to an LSP: an LSP is built for interactive editing, cannot insert into an - array, and would reintroduce a runtime dependency β€” a one-shot `tsc`/`deno - check` gives the same diagnostics with none of the plumbing. - -**Idempotent:** if the piece is already registered, do not duplicate. - -**Agreed fallback:** if auto-wire proves fragile ("truena como ejote"), -degrade to emit-only β€” write the file and print "add it to your module." -Auto-wire stays, but is allowed to become opt-in rather than a blocker. - -## 6. Architecture (Rust) - -- Command parsing: `clap`. -- Templates: `include_dir!` embeds the starter; `--template-url` shells to - `git clone --depth 1`. -- Codegen: `tree-sitter` + `tree-sitter-typescript`, range-based edits. -- Validation: spawn detected runtime for `tsc --noEmit` / `deno check`. -- Runtime detection: filesystem probes in the precedence order above. - -Each command is an isolated unit: parse args β†’ do one job β†’ report. No shared -mutable state between commands. - -## 7. Out of scope for v1 (YAGNI) - -Template catalog (one starter + BYO url is enough), edge as a `run` target, -plugin system, custom LSP, custom bundler/dev-server. - -## 8. Open handoff items - -- Diego creates the `Green-Tea/matcha` repo; this spec moves there. -- green-tea logo asset for the starter (`assets/` in `core` has branding). diff --git a/.specs/2026-07-11-matcha-cli-plan.md b/.specs/2026-07-11-matcha-cli-plan.md deleted file mode 100644 index 74a9b3e..0000000 --- a/.specs/2026-07-11-matcha-cli-plan.md +++ /dev/null @@ -1,1402 +0,0 @@ -# matcha CLI Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Ship `matcha`, the green-tea CLI β€” a native Rust binary that scaffolds projects, runs them against the detected JS runtime, and generates/auto-wires framework pieces. - -**Architecture:** Single `clap`-based binary. Each subcommand is an isolated unit (`new`, `run`, `create`, `add`) sharing two support modules: `runtime` (filesystem probes β†’ node/deno/bun) and `wire` (tree-sitter TypeScript edits with syntax-check-and-revert). The starter template is embedded via `include_dir!`; remote templates come from `git clone --depth 1`. - -**Tech Stack:** Rust, `clap` (derive), `include_dir`, `tree-sitter` + `tree-sitter-typescript`. Tests: `assert_cmd` + `predicates` + `tempfile`. - -## Global Constraints - -- Binary/crate/repo name: `matcha` β€” exact, lowercase. -- No HTTP/TLS dependency in the binary. Remote templates use `git clone --depth 1` (shell out to system `git`). -- The binary must not require a JS runtime to install or operate. It only *delegates* to the project's runtime for `run` and the optional semantic check. -- Runtime detection precedence (first match wins): `matcha.toml` `runtime` field β†’ `deno.json(c)` β†’ `bun.lock(b)` β†’ `package.json`. -- `create`/`add` edits are **idempotent** and must **revert on syntax breakage** (tree-sitter `ERROR` node β‡’ leave file untouched). -- Framework API is fixed (verified in `Green-Tea/core`): `@Sse('/path')` returns an async generator; `@Html('path')` serves a file; `@Get`/`@Route`/`@Provider`/`@Module` per `core/src/index.ts`. -- Edge is **not** a `run` target in v1. - ---- - -### Task 1: Binary skeleton + clap command surface - -**Files:** -- Create: `Cargo.toml` -- Create: `src/main.rs` -- Create: `src/cli.rs` -- Test: `tests/cli.rs` - -**Interfaces:** -- Produces: `enum Command { New, Run, Create, Add }` parsed by clap; binary named `matcha`. Later tasks fill each arm. - -- [ ] **Step 1: Write the failing test** - -```rust -// tests/cli.rs -use assert_cmd::Command; -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")); -} - -#[test] -fn new_requires_a_name() { - Command::cargo_bin("matcha").unwrap() - .arg("new").assert().failure(); // missing -} -``` - -- [ ] **Step 2: Run to verify it fails** - -Run: `cargo test` -Expected: FAIL β€” no binary / `matcha` target not found. - -- [ ] **Step 3: Write `Cargo.toml`** - -```toml -[package] -name = "matcha" -version = "0.1.0" -edition = "2021" - -[[bin]] -name = "matcha" -path = "src/main.rs" - -[dependencies] -clap = { version = "4", features = ["derive"] } -include_dir = "0.7" -tree-sitter = "0.22" -tree-sitter-typescript = "0.21" - -[dev-dependencies] -assert_cmd = "2" -predicates = "3" -tempfile = "3" -``` - -- [ ] **Step 4: Write `src/cli.rs`** - -```rust -use clap::{Parser, Subcommand}; - -#[derive(Parser)] -#[command(name = "matcha", about = "green-tea CLI")] -pub struct Cli { - #[command(subcommand)] - pub command: Command, -} - -#[derive(Subcommand)] -pub enum Command { - /// Scaffold a new project - New { - name: String, - #[arg(long)] - template_url: Option, - }, - /// Detect the runtime and run the project in watch mode - Run, - /// Generate a piece and auto-wire it into the module - Create { - #[arg(value_parser = ["module", "controller", "step"])] - kind: String, - name: String, - #[arg(long)] - check: bool, - }, - /// Add a capability to a controller - Add { - #[arg(value_parser = ["sse", "stream", "buffer"])] - capability: String, - }, -} -``` - -- [ ] **Step 5: Write `src/main.rs`** - -```rust -mod cli; - -use clap::Parser; -use cli::{Cli, Command}; - -fn main() { - let cli = Cli::parse(); - match cli.command { - Command::New { .. } => eprintln!("new: not yet implemented"), - Command::Run => eprintln!("run: not yet implemented"), - Command::Create { .. } => eprintln!("create: not yet implemented"), - Command::Add { .. } => eprintln!("add: not yet implemented"), - } -} -``` - -- [ ] **Step 6: Run tests to verify they pass** - -Run: `cargo test` -Expected: PASS (both tests). - -- [ ] **Step 7: Commit** - -```bash -git add Cargo.toml src/main.rs src/cli.rs tests/cli.rs -git commit -s -m "feat: matcha binary skeleton with clap command surface" -``` - ---- - -### Task 2: Runtime detection - -**Files:** -- Create: `src/runtime.rs` -- Modify: `src/main.rs` (add `mod runtime;`) -- Test: `src/runtime.rs` (inline `#[cfg(test)]`) - -**Interfaces:** -- Produces: `pub enum Runtime { Node, Deno, Bun }` and `pub fn detect(dir: &Path) -> Option`. Consumed by `run` (Task 6) and the semantic check (Task 9). - -- [ ] **Step 1: Write the failing test** - -```rust -// bottom of src/runtime.rs -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - use tempfile::tempdir; - - fn touch(dir: &std::path::Path, name: &str) { - fs::write(dir.join(name), "{}").unwrap(); - } - - #[test] - fn deno_wins_over_package_json() { - let d = tempdir().unwrap(); - touch(d.path(), "package.json"); - touch(d.path(), "deno.json"); - assert_eq!(detect(d.path()), Some(Runtime::Deno)); - } - - #[test] - fn bun_lock_selects_bun() { - let d = tempdir().unwrap(); - touch(d.path(), "package.json"); - touch(d.path(), "bun.lockb"); - assert_eq!(detect(d.path()), Some(Runtime::Bun)); - } - - #[test] - fn package_json_falls_back_to_node() { - let d = tempdir().unwrap(); - touch(d.path(), "package.json"); - assert_eq!(detect(d.path()), Some(Runtime::Node)); - } - - #[test] - fn matcha_toml_overrides() { - let d = tempdir().unwrap(); - touch(d.path(), "deno.json"); - fs::write(d.path().join("matcha.toml"), "runtime = \"bun\"\n").unwrap(); - assert_eq!(detect(d.path()), Some(Runtime::Bun)); - } - - #[test] - fn nothing_detected() { - let d = tempdir().unwrap(); - assert_eq!(detect(d.path()), None); - } -} -``` - -- [ ] **Step 2: Run to verify it fails** - -Run: `cargo test runtime` -Expected: FAIL β€” `detect` not defined. - -- [ ] **Step 3: Implement `src/runtime.rs`** - -```rust -use std::path::Path; - -#[derive(Debug, PartialEq, Eq, Clone, Copy)] -pub enum Runtime { Node, Deno, Bun } - -impl Runtime { - pub fn from_str(s: &str) -> Option { - match s.trim() { - "node" => Some(Runtime::Node), - "deno" => Some(Runtime::Deno), - "bun" => Some(Runtime::Bun), - _ => None, - } - } -} - -fn exists(dir: &Path, name: &str) -> bool { - dir.join(name).exists() -} - -/// Reads `runtime = "..."` from matcha.toml without a TOML dep (one field only). -fn override_from_toml(dir: &Path) -> Option { - let text = std::fs::read_to_string(dir.join("matcha.toml")).ok()?; - for line in text.lines() { - let line = line.trim(); - if let Some(rest) = line.strip_prefix("runtime") { - let val = rest.trim_start_matches('=').trim().trim_matches('"'); - return Runtime::from_str(val); - } - } - None -} - -pub fn detect(dir: &Path) -> Option { - if let Some(r) = override_from_toml(dir) { return Some(r); } - if exists(dir, "deno.json") || exists(dir, "deno.jsonc") { return Some(Runtime::Deno); } - if exists(dir, "bun.lockb") || exists(dir, "bun.lock") { return Some(Runtime::Bun); } - if exists(dir, "package.json") { return Some(Runtime::Node); } - None -} -``` - -- [ ] **Step 4: Wire the module** - -In `src/main.rs`, add near the other `mod` lines: - -```rust -mod runtime; -``` - -- [ ] **Step 5: Run tests to verify they pass** - -Run: `cargo test runtime` -Expected: PASS (all five). - -- [ ] **Step 6: Commit** - -```bash -git add src/runtime.rs src/main.rs -git commit -s -m "feat: runtime detection with matcha.toml override" -``` - ---- - -### Task 3: Embed the official starter template - -**Files:** -- Create: `template/starter/src/app.module.ts` -- Create: `template/starter/src/controllers/home.controller.ts` -- Create: `template/starter/public/index.html` -- Create: `template/starter/deno.json` -- Create: `template/starter/matcha.toml` -- Create: `src/template.rs` -- Modify: `src/main.rs` (add `mod template;`) -- Test: `src/template.rs` (inline) - -**Interfaces:** -- Produces: `pub static STARTER: include_dir::Dir` and `pub fn write_starter(dest: &Path, project_name: &str) -> std::io::Result<()>`. Consumed by Task 4. - -- [ ] **Step 1: Write the starter files** - -`template/starter/src/controllers/home.controller.ts`: - -```ts -import { Route, Get, Html, Sse } from '@green-tea/core'; - -const ZEN = [ - 'Simplicity is the ultimate sophistication.', - 'The obstacle is the path.', - 'When you let go, you have two hands to work.', - 'Make it work, make it right, make it fast.', - 'Less, but better.', -]; - -@Route('/') -export class HomeController { - @Get('/') - @Html('public/index.html') - home() {} - - @Sse('/zen') - zen() { - return (async function* () { - for (let i = 0; ; i++) { - yield { zen: ZEN[i % ZEN.length] }; - await new Promise((r) => setTimeout(r, 30_000)); - } - })(); - } -} -``` - -`template/starter/src/app.module.ts`: - -```ts -import { Module } from '@green-tea/core'; -import { HomeController } from './controllers/home.controller'; - -@Module({ controllers: [HomeController] }) -export class AppModule {} -``` - -`template/starter/public/index.html`: - -```html - - - - - {{project_name}} - - - -
- -
connecting…
-
- - - -``` - -`template/starter/deno.json`: - -```json -{ "tasks": { "dev": "deno run --watch --allow-net --allow-read src/main.ts" } } -``` - -`template/starter/matcha.toml`: - -```toml -runtime = "deno" -``` - -- [ ] **Step 2: Write the failing test** - -```rust -// bottom of src/template.rs -#[cfg(test)] -mod tests { - use super::*; - use tempfile::tempdir; - - #[test] - fn writes_starter_and_substitutes_name() { - let d = tempdir().unwrap(); - write_starter(d.path(), "my-api").unwrap(); - let html = std::fs::read_to_string(d.path().join("public/index.html")).unwrap(); - assert!(html.contains("my-api")); - assert!(!html.contains("{{project_name}}")); - assert!(d.path().join("src/controllers/home.controller.ts").exists()); - assert!(d.path().join("matcha.toml").exists()); - } -} -``` - -- [ ] **Step 3: Run to verify it fails** - -Run: `cargo test template` -Expected: FAIL β€” `write_starter` not defined. - -- [ ] **Step 4: Implement `src/template.rs`** - -```rust -use include_dir::{include_dir, Dir}; -use std::path::Path; - -pub static STARTER: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/starter"); - -pub fn write_starter(dest: &Path, project_name: &str) -> std::io::Result<()> { - write_dir(&STARTER, dest, project_name) -} - -fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> { - for entry in dir.entries() { - match entry { - include_dir::DirEntry::Dir(d) => { - let sub = dest.join(d.path().file_name().unwrap()); - std::fs::create_dir_all(&sub)?; - write_dir(d, &sub, name)?; - } - include_dir::DirEntry::File(f) => { - let out = dest.join(f.path().file_name().unwrap()); - if let Some(parent) = out.parent() { std::fs::create_dir_all(parent)?; } - let contents = std::str::from_utf8(f.contents()) - .map(|s| s.replace("{{project_name}}", name).into_bytes()) - .unwrap_or_else(|_| f.contents().to_vec()); - std::fs::write(out, contents)?; - } - } - } - Ok(()) -} -``` - -> Note: `write_dir` rebuilds paths from `file_name()` so nested dirs land correctly relative to `dest`. If a deeper nesting bug shows up during the test, switch to `f.path()` relative to `STARTER.path()`. - -- [ ] **Step 5: Wire the module** - -In `src/main.rs` add: `mod template;` - -- [ ] **Step 6: Run tests to verify they pass** - -Run: `cargo test template` -Expected: PASS. - -- [ ] **Step 7: Commit** - -```bash -git add template src/template.rs src/main.rs -git commit -s -m "feat: embed official starter template with token substitution" -``` - ---- - -### Task 4: `matcha new ` from embedded starter - -**Files:** -- Create: `src/cmd_new.rs` -- Modify: `src/main.rs` (add `mod cmd_new;`, dispatch `Command::New`) -- Test: `tests/new.rs` - -**Interfaces:** -- Consumes: `template::write_starter` (Task 3). -- Produces: `pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()>`. The `template_url` arm is filled in Task 5 (return an error for now). - -- [ ] **Step 1: Write the failing test** - -```rust -// tests/new.rs -use assert_cmd::Command; -use tempfile::tempdir; - -#[test] -fn new_scaffolds_into_named_dir() { - let d = tempdir().unwrap(); - Command::cargo_bin("matcha").unwrap() - .current_dir(d.path()) - .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()); -} - -#[test] -fn new_refuses_existing_dir() { - let d = tempdir().unwrap(); - std::fs::create_dir(d.path().join("taken")).unwrap(); - Command::cargo_bin("matcha").unwrap() - .current_dir(d.path()) - .args(["new", "taken"]).assert().failure(); -} -``` - -- [ ] **Step 2: Run to verify it fails** - -Run: `cargo test --test new` -Expected: FAIL β€” command prints "not yet implemented", dir not created. - -- [ ] **Step 3: Implement `src/cmd_new.rs`** - -```rust -use std::io::{Error, ErrorKind}; -use std::path::Path; - -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"))); - } - std::fs::create_dir_all(dest)?; - - match template_url { - None => template::write_starter(dest, name)?, - Some(_) => return Err(Error::new(ErrorKind::Unsupported, - "--template-url not implemented yet")), - } - println!("βœ“ created {name}\n cd {name} && matcha run"); - Ok(()) -} -``` - -- [ ] **Step 4: Dispatch in `src/main.rs`** - -Replace the `Command::New` arm: - -```rust -Command::New { name, template_url } => { - if let Err(e) = cmd_new::run(&name, template_url.as_deref()) { - eprintln!("error: {e}"); - std::process::exit(1); - } -} -``` - -And add `mod cmd_new;` near the top. - -- [ ] **Step 5: Run tests to verify they pass** - -Run: `cargo test --test new` -Expected: PASS (both). - -- [ ] **Step 6: Commit** - -```bash -git add src/cmd_new.rs src/main.rs tests/new.rs -git commit -s -m "feat: matcha new scaffolds from embedded starter" -``` - ---- - -### Task 5: `matcha new --template-url gh:owner/repo` - -**Files:** -- Modify: `src/cmd_new.rs` (fill the `Some` arm, add `resolve_url`) -- Test: `src/cmd_new.rs` (inline unit test for URL mapping) + `tests/new.rs` (clone from a local git fixture) - -**Interfaces:** -- Consumes: system `git`. -- Produces: `fn resolve_url(spec: &str) -> String` β€” `gh:owner/repo` β†’ `https://github.com/owner/repo`, otherwise passthrough. - -- [ ] **Step 1: Write the failing unit test** - -```rust -// bottom of src/cmd_new.rs -#[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"); - } -} -``` - -- [ ] **Step 2: Write the failing integration test** - -```rust -// add to tests/new.rs -use std::process::Command as Proc; - -#[test] -fn new_clones_local_template() { - let d = tempdir().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()) - .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 -} -``` - -- [ ] **Step 3: Run to verify both fail** - -Run: `cargo test` -Expected: FAIL β€” `resolve_url` missing; clone arm returns "not implemented". - -- [ ] **Step 4: Implement clone in `src/cmd_new.rs`** - -Add the function and replace the `Some` arm: - -```rust -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::new(ErrorKind::Other, "git clone failed")); - } - std::fs::remove_dir_all(dest.join(".git")).ok(); - Ok(()) -} -``` - -Replace the `Some(_)` arm from Task 4: - -```rust -Some(url) => clone_template(url, dest)?, -``` - -(`dest` is created empty by `create_dir_all`; `git clone ` clones into it.) - -- [ ] **Step 5: Run tests to verify they pass** - -Run: `cargo test` -Expected: PASS (unit + integration). - -- [ ] **Step 6: Commit** - -```bash -git add src/cmd_new.rs tests/new.rs -git commit -s -m "feat: matcha new --template-url via shallow git clone" -``` - ---- - -### Task 6: `matcha run` β€” detect runtime and spawn watch - -**Files:** -- Create: `src/cmd_run.rs` -- Modify: `src/main.rs` (add `mod cmd_run;`, dispatch) -- Test: `src/cmd_run.rs` (inline unit test for argv construction) - -**Interfaces:** -- Consumes: `runtime::detect` (Task 2). -- Produces: `fn command_for(rt: Runtime) -> (&'static str, Vec<&'static str>)` β€” the program + args to spawn. `pub fn run(dir: &Path) -> std::io::Result<()>` execs it. - -Testing note: we unit-test the **argv we build** (deterministic, no runtime needed), not a live process. Spawning is a thin wrapper around a tested value. - -- [ ] **Step 1: Write the failing test** - -```rust -// bottom of src/cmd_run.rs -#[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"])); - } -} -``` - -- [ ] **Step 2: Run to verify it fails** - -Run: `cargo test cmd_run` -Expected: FAIL β€” `command_for` not defined. - -- [ ] **Step 3: Implement `src/cmd_run.rs`** - -```rust -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)); -} -``` - -- [ ] **Step 4: Dispatch in `src/main.rs`** - -```rust -Command::Run => { - if let Err(e) = cmd_run::run(std::path::Path::new(".")) { - eprintln!("error: {e}"); - std::process::exit(1); - } -} -``` - -Add `mod cmd_run;`. - -- [ ] **Step 5: Run tests to verify they pass** - -Run: `cargo test cmd_run` -Expected: PASS. - -- [ ] **Step 6: Commit** - -```bash -git add src/cmd_run.rs src/main.rs -git commit -s -m "feat: matcha run detects runtime and spawns watch" -``` - ---- - -### Task 7: Wiring core β€” tree-sitter import + @Module array edit - -**Files:** -- Create: `src/wire.rs` -- Modify: `src/main.rs` (add `mod wire;`) -- Test: `src/wire.rs` (inline, string fixtures) - -**Interfaces:** -- Produces: - - `pub fn add_import(src: &str, symbol: &str, from: &str) -> String` β€” inserts `import { } from '';` after the last import; no-op if already present. - - `pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option` β€” inserts `` into the `key: [...]` array of the first `@Module({...})`; `None` if the resulting text fails to re-parse (`ERROR` node); no-op-returns-`Some(src)` if already present. - - `fn parses_clean(src: &str) -> bool` β€” true when tree-sitter finds no `ERROR` node. -- Consumed by Task 8. - -- [ ] **Step 1: Write the failing tests** - -```rust -// bottom of src/wire.rs -#[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")); - } -} -``` - -- [ ] **Step 2: Run to verify it fails** - -Run: `cargo test wire` -Expected: FAIL β€” functions not defined. - -- [ ] **Step 3: Implement `src/wire.rs`** - -```rust -use tree_sitter::{Parser, Node}; - -fn parser() -> Parser { - let mut p = Parser::new(); - p.set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()) - .expect("load ts grammar"); - p -} - -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(); - node.children(&mut c).any(has_error) -} - -pub fn add_import(src: &str, symbol: &str, from: &str) -> String { - let line = format!("import {{ {symbol} }} from '{from}';"); - if src.contains(&line) { return src.to_string(); } - // insert after the last import statement's line - 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) { - 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 `key: [ ... ]` array inside the first `@Module({...})` and inserts `symbol`. -pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> 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 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 `key: [...]`. -fn find_array(root: &Node, src: &str, key: &str) -> Option<(usize, usize, String)> { - // Walk every pair `key: array` in the tree; pick the first matching key. - fn visit(node: Node, src: &str, key: &str) -> Option<(usize, usize, String)> { - if node.kind() == "pair" { - if let Some(k) = node.child_by_field_name("key") { - if k.utf8_text(src.as_bytes()).ok() == Some(key) { - if let Some(v) = node.child_by_field_name("value") { - if v.kind() == "array" { - 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)); - } - } - } - } - } - let mut c = node.walk(); - for child in node.children(&mut c) { - if let Some(r) = visit(child, src, key) { return Some(r); } - } - None - } - visit(*root, src, key) -} -``` - -> Grammar note: `tree-sitter-typescript` 0.21+ exposes `LANGUAGE_TYPESCRIPT`. If the linked version instead exposes `language_typescript()`, use `p.set_language(&tree_sitter_typescript::language_typescript())`. The failingβ†’passing test loop will surface which one this crate version ships. - -- [ ] **Step 4: Wire the module** - -In `src/main.rs`: `mod wire;` - -- [ ] **Step 5: Run tests to verify they pass** - -Run: `cargo test wire` -Expected: PASS. - -- [ ] **Step 6: Commit** - -```bash -git add src/wire.rs src/main.rs -git commit -s -m "feat: tree-sitter import + @Module array wiring with revert-on-break" -``` - ---- - -### Task 8: `matcha create ` β€” generate + auto-wire - -**Files:** -- Create: `src/cmd_create.rs` -- Modify: `src/main.rs` (add `mod cmd_create;`, dispatch) -- Test: `tests/create.rs` - -**Interfaces:** -- Consumes: `wire::add_import`, `wire::add_to_module_array` (Task 7). -- Produces: `pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()>`. Fallback: if `add_to_module_array` returns `None`, write the file and print a manual-wire hint instead of failing (the agreed "emit-only" degrade). - -- [ ] **Step 1: Write the failing test** - -```rust -// tests/create.rs -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 }")); -} -``` - -- [ ] **Step 2: Run to verify it fails** - -Run: `cargo test --test create` -Expected: FAIL β€” "not yet implemented". - -- [ ] **Step 3: Implement `src/cmd_create.rs`** - -```rust -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), - "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) -> 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"); - } - } - Ok(()) -} -``` - -- [ ] **Step 4: Dispatch in `src/main.rs`** - -```rust -Command::Create { kind, name, check } => { - if let Err(e) = cmd_create::run(&kind, &name, check) { - eprintln!("error: {e}"); - std::process::exit(1); - } -} -``` - -Add `mod cmd_create;`. - -- [ ] **Step 5: Run tests to verify they pass** - -Run: `cargo test --test create` -Expected: PASS. - -- [ ] **Step 6: Commit** - -```bash -git add src/cmd_create.rs src/main.rs tests/create.rs -git commit -s -m "feat: matcha create controller with tree-sitter auto-wire + emit-only fallback" -``` - ---- - -### Task 9: Optional semantic check (`--check`) - -**Files:** -- Create: `src/check.rs` -- Modify: `src/cmd_create.rs` (call check when `check == true` and config present), `src/main.rs` (`mod check;`) -- Test: `src/check.rs` (inline, argv construction) - -**Interfaces:** -- Consumes: `runtime::detect` (Task 2). -- Produces: `fn check_command(rt: Runtime) -> (&'static str, Vec<&'static str>)`; `pub fn run(dir: &Path) -> std::io::Result` returns `true` when the type-check passes (or is unavailable β†’ skip, `true`). - -- [ ] **Step 1: Write the failing test** - -```rust -// bottom of src/check.rs -#[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"])); - } -} -``` - -- [ ] **Step 2: Run to verify it fails** - -Run: `cargo test check` -Expected: FAIL β€” `check_command` not defined. - -- [ ] **Step 3: Implement `src/check.rs`** - -```rust -use std::path::Path; -use crate::runtime::{self, Runtime}; - -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 { - 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()) -} -``` - -- [ ] **Step 4: Call it from `cmd_create.rs`** - -At the end of `create_controller`, before `Ok(())`, add a `check: bool` param threaded from `run` and: - -```rust - 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}"), - } - } -``` - -Update `create_controller(name)` β†’ `create_controller(name, check)` and pass `_check` through as `check`. - -- [ ] **Step 5: Run tests + build to verify** - -Run: `cargo test check && cargo build` -Expected: PASS + clean build. - -- [ ] **Step 6: Commit** - -```bash -git add src/check.rs src/cmd_create.rs src/main.rs -git commit -s -m "feat: optional --check delegates type-check to detected runtime" -``` - ---- - -### Task 10: `matcha add ` β€” append a handler to a controller - -**Files:** -- Create: `src/cmd_add.rs` -- Modify: `src/main.rs` (`mod cmd_add;`, dispatch), `src/wire.rs` (add `insert_method`) -- Test: `src/wire.rs` (inline) + `tests/add.rs` - -**Interfaces:** -- Consumes: `wire::add_import`, plus new `wire::insert_method`. -- Produces: `pub fn insert_method(src: &str, class: &str, method_src: &str) -> Option` β€” inserts `method_src` before the closing `}` of `class `; `None` if re-parse fails. `cmd_add::run(cap: &str) -> std::io::Result<()>` targets the single `*.controller.ts` in `src/controllers` (errors if 0 or >1). - -- [ ] **Step 1: Write the failing wire test** - -```rust -// add to src/wire.rs tests module -#[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('}')); -} -``` - -- [ ] **Step 2: Write the failing integration test** - -```rust -// tests/add.rs -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 }")); -} -``` - -- [ ] **Step 3: Run to verify both fail** - -Run: `cargo test` -Expected: FAIL β€” `insert_method` missing; `add` not implemented. - -- [ ] **Step 4: Add `insert_method` to `src/wire.rs`** - -```rust -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 } -} - -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) -} -``` - -- [ ] **Step 5: Implement `src/cmd_add.rs`** - -```rust -use std::io::{Error, ErrorKind}; -use std::path::PathBuf; - -use crate::wire; - -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, - } -} - -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::new(ErrorKind::Other, "multiple controllers; specify which (not yet supported)")), - } -} - -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)?; - // class name = file stem PascalCased + "Controller" β€” but read it from the source instead: - let class = class_name(&src) - .ok_or_else(|| Error::new(ErrorKind::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' already imported, - // we still append a second import line β€” acceptable, tsc merges. Keep lazy for v1. - 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(()) -} - -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()) -} -``` - -> `add_import` reuse note: for `@green-tea/core` the symbol may already be imported under a shared `{ ... }`. v1 keeps it lazy (a duplicate named import line is legal TS and tsc dedups at type level). Merging into the existing brace is a Task-for-later; not worth tree-sitter surgery now. - -- [ ] **Step 6: Dispatch in `src/main.rs`** - -```rust -Command::Add { capability } => { - if let Err(e) = cmd_add::run(&capability) { - eprintln!("error: {e}"); - std::process::exit(1); - } -} -``` - -Add `mod cmd_add;`. - -- [ ] **Step 7: Run tests to verify they pass** - -Run: `cargo test` -Expected: PASS (wire unit + add integration + everything prior). - -- [ ] **Step 8: Commit** - -```bash -git add src/cmd_add.rs src/wire.rs src/main.rs tests/add.rs -git commit -s -m "feat: matcha add appends capability handler to the controller" -``` - ---- - -### Task 11: README + install docs - -**Files:** -- Create: `README.md` -- Test: none (docs). - -**Interfaces:** none. - -- [ ] **Step 1: Write `README.md`** - -```markdown -# matcha - -The green-tea CLI. - -## Install - - cargo install matcha # or: brew install matcha (once published) - -## Usage - - matcha new my-api # scaffold from the official starter - matcha new my-api --template-url gh:owner/repo - 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 to your controller - -## Runtime detection - -Precedence: `matcha.toml` (`runtime = "..."`) β†’ `deno.json` β†’ `bun.lock(b)` β†’ `package.json`. -Edge is a deploy target, not a `run` target. -``` - -- [ ] **Step 2: Commit** - -```bash -git add README.md -git commit -s -m "docs: matcha README with usage and runtime detection" -``` - ---- - -## Self-Review - -**Spec coverage:** -- Β§2 command surface β†’ Tasks 1, 4, 5, 6, 8, 10. βœ“ -- Β§3 `new` embedded starter + `--template-url` + starter "wow" β†’ Tasks 3, 4, 5. βœ“ -- Β§4 runtime detection β†’ Task 2; used in Tasks 6, 9. βœ“ -- Β§5 codegen (tree-sitter edit + syntax-check revert + optional semantic check + idempotent + fallback) β†’ Tasks 7, 8, 9. βœ“ -- Β§6 Rust architecture (clap, include_dir, tree-sitter, git clone) β†’ Tasks 1, 3, 5, 7. βœ“ -- Β§7 out of scope respected (no catalog, no edge run, no plugin/LSP/bundler). βœ“ -- Gap: `create module`/`create step` are stubbed as "not implemented" in Task 8 β€” spec lists them in the command surface. **Deliberate:** v1 proves the wiring pipeline with `controller`; `module`/`step` reuse the same `wire` primitives and are fast follow-ups. Flagged here rather than silently dropped. - -**Placeholder scan:** No TBD/TODO left as work items; every code step is complete and runnable. Grammar-version and import-merge notes are explicit engineering caveats with the resolution path, not placeholders. - -**Type consistency:** `runtime::detect`/`Runtime` used identically in Tasks 2/6/9. `wire::add_import`, `add_to_module_array`, `insert_method` signatures match between Task 7/10 definitions and Task 8/10 call sites. `cmd_*::run` signatures match their `main.rs` dispatch. - -**Known execution-time unknowns (converge via the test loop):** -- `tree-sitter-typescript` language accessor name (`LANGUAGE_TYPESCRIPT` vs `language_typescript()`) β€” Task 7 note. -- `pair`/`array`/`class_declaration` node/field names in the grammar version pulled β€” the first `cargo test wire` run confirms or corrects them. diff --git a/.specs/2026-07-12-matcha-multi-runtime.md b/.specs/2026-07-12-matcha-multi-runtime.md deleted file mode 100644 index b2f1beb..0000000 --- a/.specs/2026-07-12-matcha-multi-runtime.md +++ /dev/null @@ -1,152 +0,0 @@ -# matcha β€” multi-runtime starter (node/deno/bun) Β· Spec - -**Date:** 2026-07-12 -**Branch:** `feature/matcha-multi-runtime` (off `develop`) -**Goal:** `matcha new --runtime ` scaffolds the starter for the chosen runtime. Shared app files are written once; only `main.ts` + runtime config + `matcha.toml` differ per runtime. Default runtime: **node** (green-tea is developed node-first; Node is the reference implementation. deno/bun via `--runtime`). - -## Verified framework facts (from Green-Tea/core) -- `@green-tea/core` imports `reflect-metadata` internally (`src/index.ts:6`) β€” consumers need NO explicit import; it installs transitively with the package. -- Serve per runtime: Node `app.listen(3000)`; Deno `Deno.serve({ port }, app.fetch)`; Bun `Bun.serve({ port, fetch: app.fetch })`. Starter has no WebSocket, so `app.fetch` is sufficient (no `serveDeno`/`serveBun`). -- `@Module` requires `mountpoint`. Package version pin: `^26.7.0-beta.0`. - -## New template layout (replaces `template/starter/`) -``` -template/ - shared/ - public/index.html - src/app.module.ts - src/controllers/home.controller.ts - runtimes/ - deno/ { matcha.toml, deno.json, src/main.ts } - node/ { matcha.toml, package.json, tsconfig.json, src/main.ts } - bun/ { matcha.toml, package.json, tsconfig.json, src/main.ts } -``` -`write_starter` writes `shared` then overlays the chosen runtime dir on top (both go into the same project dir; `src/main.ts` from the overlay lands beside `src/app.module.ts` from shared). Token substitution `{{project_name}}` applies to every copied file (now also `package.json` "name"). - -## Exact file contents - -### shared/ (moved verbatim from current `template/starter/`) -- `public/index.html` β€” unchanged (keep `{{project_name}}` title + `EventSource('/zen')`). -- `src/app.module.ts` β€” unchanged (`@Module({ mountpoint: '/', controllers: [HomeController] })`). -- `src/controllers/home.controller.ts` β€” unchanged (`@Route('/')`, `@Get('/') @Html('public/index.html')`, `@Sse('/zen')` rotating zen every 30s). - -### runtimes/deno/ (moved from current starter) -- `matcha.toml`: `runtime = "deno"` -- `deno.json` (unchanged from current starter): -```json -{ - "compilerOptions": { "experimentalDecorators": true }, - "unstable": ["sloppy-imports"], - "imports": { "@green-tea/core": "npm:@green-tea/core@^26.7.0-beta.0" }, - "tasks": { "dev": "deno run --watch --allow-net --allow-read --allow-env src/main.ts" } -} -``` -- `src/main.ts`: -```ts -import { createApp } from '@green-tea/core'; -import { AppModule } from './app.module'; - -const app = createApp({ modules: [AppModule] }); - -Deno.serve({ port: 8000 }, app.fetch); -console.log('🍡 green-tea running on http://localhost:8000'); -``` - -### runtimes/node/ -- `matcha.toml`: `runtime = "node"` -- `package.json`: -```json -{ - "name": "{{project_name}}", - "type": "module", - "private": true, - "scripts": { "dev": "tsx watch src/main.ts" }, - "dependencies": { "@green-tea/core": "^26.7.0-beta.0" }, - "devDependencies": { "tsx": "^4", "typescript": "^5" } -} -``` -- `tsconfig.json`: -```json -{ - "compilerOptions": { - "target": "es2020", - "module": "esnext", - "moduleResolution": "bundler", - "experimentalDecorators": true, - "strict": true, - "skipLibCheck": true - } -} -``` -- `src/main.ts`: -```ts -import { createApp } from '@green-tea/core'; -import { AppModule } from './app.module'; - -const app = createApp({ modules: [AppModule] }); - -app.listen(3000); -console.log('🍡 green-tea running on http://localhost:3000'); -``` - -### runtimes/bun/ -- `matcha.toml`: `runtime = "bun"` -- `package.json`: -```json -{ - "name": "{{project_name}}", - "type": "module", - "private": true, - "scripts": { "dev": "bun --watch run src/main.ts" }, - "dependencies": { "@green-tea/core": "^26.7.0-beta.0" } -} -``` -- `tsconfig.json`: -```json -{ - "compilerOptions": { - "target": "esnext", - "module": "esnext", - "moduleResolution": "bundler", - "experimentalDecorators": true, - "strict": true, - "skipLibCheck": true - } -} -``` -- `src/main.ts`: -```ts -import { createApp } from '@green-tea/core'; -import { AppModule } from './app.module'; - -const app = createApp({ modules: [AppModule] }); - -Bun.serve({ port: 8000, fetch: app.fetch }); -console.log('🍡 green-tea running on http://localhost:8000'); -``` - -## Code changes - -### `src/template.rs` -- Replace the single `STARTER` embed with `SHARED` + three runtime overlays (`include_dir!` each). -- `pub fn write_starter(dest: &Path, project_name: &str, runtime: Runtime) -> io::Result<()>` β€” write `SHARED`, then the overlay for `runtime`. Keep `write_dir` substitution logic. - -### `src/cli.rs` -- `Command::New` gains `#[arg(long, default_value = "deno", value_parser = ["node", "deno", "bun"])] runtime: String`. - -### `src/cmd_new.rs` -- `run(name, template_url, runtime: &str)`: parse `runtime` via `Runtime::from_str` (already in `runtime.rs`); for the starter (no `--template-url`) path, call `write_starter(dest, name, rt)`. `--template-url` path ignores `--runtime`. - -### `src/cmd_run.rs` -- Change the Bun mapping from `("bun", vec!["--watch", "run", "dev"])` to `("bun", vec!["run", "dev"])` so all three uniformly run their `dev` script (deno.json/package.json define the watch). Update the `bun_watch` unit test accordingly. - -### `src/main.rs` -- Pass the new `runtime` arg through the `Command::New` dispatch. - -## Tests -- `template.rs`: parametrize the write test β€” assert deno writes `deno.json` + `src/main.ts` containing `Deno.serve`; node writes `package.json` (with substituted name) + `tsconfig.json` + `main.ts` containing `app.listen`; bun writes `package.json` + `main.ts` containing `Bun.serve`. All three write the shared `src/app.module.ts` and `public/index.html`. -- `tests/new.rs`: `matcha new demo --runtime node` produces `package.json` with `"name": "demo"` and no `deno.json`; default (no flag) produces `deno.json`. -- `cmd_run.rs`: bun mapping test expects `("bun", vec!["run", "dev"])`. - -## Out of scope -Edge starter (deploy target, not `run`). Per-runtime lockfiles. `serveDeno`/`serveBun` (no WS in starter).