Author SHA1 Message Date
chrnx 77c3c2a0ff Merge branch 'develop' of ssh://git.svc.zoit.services:2232/Green-Tea/matcha into develop 2026-07-12 18:14:38 -05:00
chrnx c7b58db24e Merge fix/installer-latest-url: installer latest-URL fix + matcha --version 2026-07-12 18:14:04 -05:00
chrnx 7080b207a7 fix: installer resolves latest via host-root API (was 404 on repo-path); add matcha --version
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 18:13:54 -05:00
chrnx 235b87dcae Merge branch 'main' into develop 2026-07-12 23:03:43 +00:00
chrnx 6e84f467a8 Merge feature/matcha-installer: curl|sh installer + release CI 2026-07-12 18:00:39 -05:00
chrnx 995c3cd45e fix(install): tolerate whitespace in latest-tag JSON; doc env vars on pipe
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 18:00:29 -05:00
chrnx b630478985 docs: install via curl|sh, cargo install --git as from-source
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 17:57:06 -05:00
chrnx 7beadde4be ci: fail-fast=false so a flaky leg can't publish a partial release
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 17:56:40 -05:00
chrnx 48276890e8 ci: release workflow builds binaries and publishes to Gitea Releases
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 17:52:23 -05:00
chrnx 8a282fa9c8 test: shellcheck-clean fixture checksum generation (SC2015)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 17:51:30 -05:00
chrnx 02c3c35d87 feat: curl|sh installer with sha256 verification
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 17:46:42 -05:00
chrnx 1b0a9b40a6 Merge pull request 'Develop' (#1) from develop into main
Reviewed-on: #1
2026-07-12 21:37:14 +00:00
chrnx 04e20cfccf chore: stop tracking AI/scratch docs (.specs); keep tree to project docs only
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 16:35:21 -05:00
chrnx b071896b10 Merge feature/matcha-multi-runtime: node/deno/bun starters via --runtime (default node) 2026-07-12 13:16:39 -05:00
chrnx 4985adad00 chore: drop now-stale dead_code allows in runtime.rs; spec default=node erratum
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 13:16:27 -05:00
chrnx 685c51b7e0 fix(new): default runtime is node (framework is node-first)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 13:13:02 -05:00
chrnx 3f86841d4b feat(new): multi-runtime starter (node/deno/bun) via --runtime, shared + overlay templates
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 13:11:12 -05:00
chrnx f84c50b97e Merge feature/matcha-v1-cli: matcha v1 CLI (new/run/create/add) 2026-07-12 13:01:34 -05:00
chrnx 277e0bd289 chore: adopt calver versioning (26.7.0)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-12 13:01:34 -05:00
chrnx 757b729986 fix(add): merge imports into existing brace + capability idempotency; fmt
- wire::add_import now merges a new symbol into an already-present
  `import { ... } from '<from>';` brace instead of appending a second,
  colliding import line for the same module (a duplicate ESM binding
  is a hard SyntaxError/TS2300, not a harmless dupe as previously
  assumed). Falls back to appending a new line when the module isn't
  imported yet, or if the brace-merge edit fails the parses_clean
  guard.
- cmd_add::run gains a capability-level idempotency guard, keyed on
  each capability's unique route-path literal, so `matcha add <cap>`
  run twice no longer appends a duplicate handler + route.
- cargo fmt --all across the crate; drop the stale #[allow(dead_code)]
  on wire::parses_clean now that it's demonstrably live.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:52:21 -05:00
chrnx bc013fde9f docs: matcha README with usage and runtime detection
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:39:37 -05:00
chrnx 87d7e185d7 test(add): cover insert_method revert/not-found paths and only_controller errors
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:38:09 -05:00
chrnx 1b9990f02a feat: matcha add appends capability handler to the controller
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:33:32 -05:00
chrnx e99dd58c66 feat: optional --check delegates type-check to detected runtime
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:28:40 -05:00
chrnx 13b77b3999 feat: matcha create controller with tree-sitter auto-wire + emit-only fallback
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:24:29 -05:00
chrnx 4df1e7ce7b fix(wire): scope @Module array search to the Module decorator, not any object literal
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:20:39 -05:00
chrnx acaee0d7e0 feat: tree-sitter import + @Module array wiring with revert-on-break
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:13:38 -05:00
chrnx 16480db7a2 feat: matcha run detects runtime and spawns watch
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:09:08 -05:00
chrnx 2972326103 feat: matcha new --template-url via shallow git clone
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:06:19 -05:00
chrnx de000cb27d fix(new): no orphan dir on error path; drop stale dead_code allow
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 13:03:01 -05:00
chrnx 06849ebab4 feat: matcha new scaffolds from embedded starter
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 12:59:38 -05:00
chrnx caabb51ae0 fix(starter): make scaffolded app runnable — mountpoint, Deno entrypoint, import map
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 12:56:54 -05:00
chrnx 456fa10664 feat: embed official starter template with token substitution
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 12:49:53 -05:00
chrnx 6ad481eb82 feat: runtime detection with matcha.toml override
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 12:46:11 -05:00
chrnx 4298c0509f chore: track Cargo.lock for reproducible binary builds
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 12:44:02 -05:00
chrnx bbe3e299ae feat: matcha binary skeleton with clap command surface
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 12:41:27 -05:00
chrnx 7b1debd6d2 chore: bootstrap matcha repo with design spec and plan
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-11 12:39:35 -05:00
12 changed files with 131 additions and 525 deletions

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
name: Release
on:
push:
tags: ['v*']
permissions:
contents: write
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- target: aarch64-apple-darwin
os: macos-14
- target: x86_64-apple-darwin
os: macos-14
- target: x86_64-unknown-linux-musl
os: ubuntu-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Add target + musl tooling
run: |
rustup target add ${{ matrix.target }}
if [ "${{ matrix.target }}" = "x86_64-unknown-linux-musl" ]; then
sudo apt-get update && sudo apt-get install -y musl-tools
fi
- name: Build
run: cargo build --release --locked --target ${{ matrix.target }}
- name: Package
run: |
TAR="matcha-${{ matrix.target }}.tar.gz"
tar -czf "$TAR" -C "target/${{ matrix.target }}/release" matcha
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$TAR" > "$TAR.sha256"
else
shasum -a 256 "$TAR" > "$TAR.sha256"
fi
- name: Upload to release
uses: softprops/action-gh-release@v2
with:
files: |
matcha-${{ matrix.target }}.tar.gz
matcha-${{ matrix.target }}.tar.gz.sha256
-23
View File
@@ -1,23 +0,0 @@
name: CI
# Rust gate. Lives in .github/workflows so both Gitea and GitHub run it.
on:
pull_request:
branches: [develop, main]
push:
branches: [develop, main]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Add clippy + rustfmt
run: rustup component add clippy rustfmt
- run: cargo fmt --check
- run: cargo clippy --all-targets -- -D warnings
- run: cargo test --locked
-27
View File
@@ -1,27 +0,0 @@
name: Promote → GitHub
# Runs on GITEA ONLY. Mirrors only main + version tags to the public GitHub repo.
on:
push:
branches: [main]
tags: ['v*']
jobs:
push-github:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Push main + tags to GitHub
env:
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
run: |
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/matcha.git"
if [ "${{ github.ref_type }}" = "tag" ]; then
git push github "refs/tags/${{ github.ref_name }}"
else
git push github "HEAD:refs/heads/main"
git push github --tags
fi
-105
View File
@@ -1,105 +0,0 @@
name: Release
# On a version tag: build cross-platform binaries and attach them to the release (on
# whichever forge fired — the release API calls are portable). ADDITIONALLY, on GitHub
# only (production), publish the crate to crates.io.
on:
push:
tags: ['v*']
permissions:
contents: write
jobs:
# Gitea's delete-asset API differs from GitHub's (it requires the release id in the
# path), so softprops' delete-then-reupload 404s when re-releasing an existing tag.
# Delete the whole release first so every run's uploads are fresh. Portable: the
# get-by-tag + delete-by-id endpoints exist on both Gitea and GitHub, and deleting
# first is harmless on GitHub (softprops just recreates it).
prepare:
runs-on: ubuntu-latest
steps:
- name: Delete existing release for this tag
env:
GT_TOKEN: ${{ github.token }}
run: |
tag="$GITHUB_REF_NAME"
api="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY"
id=$(curl -sSL -H "Authorization: token $GT_TOKEN" "$api/releases/tags/$tag" \
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true)
if [ -n "${id:-}" ]; then
echo "deleting existing release id=$id for $tag"
curl -sS -X DELETE -H "Authorization: token $GT_TOKEN" "$api/releases/$id" || true
else
echo "no existing release for $tag — nothing to delete"
fi
build:
needs: prepare
strategy:
fail-fast: false
matrix:
include:
- target: aarch64-apple-darwin
os: macos-14
- target: x86_64-apple-darwin
os: macos-14
- target: x86_64-unknown-linux-musl
os: ubuntu-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Add target + musl tooling
run: |
rustup target add ${{ matrix.target }}
if [ "${{ matrix.target }}" = "x86_64-unknown-linux-musl" ]; then
sudo apt-get update && sudo apt-get install -y musl-tools
fi
- name: Build
run: cargo build --release --locked --target ${{ matrix.target }}
- name: Package
run: |
TAR="matcha-${{ matrix.target }}.tar.gz"
tar -czf "$TAR" -C "target/${{ matrix.target }}/release" matcha
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$TAR" > "$TAR.sha256"
else
shasum -a 256 "$TAR" > "$TAR.sha256"
fi
- name: Upload to release
uses: softprops/action-gh-release@v2
with:
files: |
matcha-${{ matrix.target }}.tar.gz
matcha-${{ matrix.target }}.tar.gz.sha256
# crates.io = production only.
# crates.io = production only, via OIDC Trusted Publishing (no CARGO_TOKEN).
# Requires a trusted publisher configured on crates.io (Expressive-Tea/matcha, release.yml).
publish-crate:
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest
permissions:
id-token: write
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
# Exchanges the OIDC id-token for a short-lived crates.io token.
- uses: rust-lang/crates-io-auth-action@v1
id: auth
- name: cargo publish
env:
CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
run: cargo publish --locked
Generated
+2 -2
View File
@@ -253,8 +253,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]] [[package]]
name = "matcha-cli" name = "matcha"
version = "26.8.0-beta.0" version = "26.7.0"
dependencies = [ dependencies = [
"assert_cmd", "assert_cmd",
"clap", "clap",
+2 -7
View File
@@ -1,13 +1,8 @@
[package] [package]
name = "matcha-cli" name = "matcha"
version = "26.8.0-beta.0" version = "26.7.0"
edition = "2021" edition = "2021"
description = "The green-tea CLI: scaffold a project, generate controllers, steps and providers already wired into their module, and run with your runtime detected. One native binary, no JS runtime needed to install it."
license = "MIT"
repository = "https://github.com/Expressive-Tea/matcha"
# The crate is `matcha-cli` on crates.io (the name `matcha` is taken), but the
# installed binary stays `matcha` — `cargo install matcha-cli` gives you `matcha`.
[[bin]] [[bin]]
name = "matcha" name = "matcha"
path = "src/main.rs" path = "src/main.rs"
+6 -14
View File
@@ -1,32 +1,24 @@
# matcha # matcha
The [green-tea](https://github.com/Expressive-Tea/green-tea) CLI — scaffold, run, and generate green-tea apps from a single native binary. No JS runtime required to install or operate. 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 ## Install
```bash ```bash
cargo install matcha-cli curl -fsSL https://git.svc.zoit.services/Green-Tea/matcha/raw/branch/main/install.sh | sh
``` ```
Builds from [crates.io](https://crates.io/crates/matcha-cli) and installs the `matcha` Installs a prebuilt binary to `~/.local/bin` — no Rust required. Env vars go on
binary. Needs a Rust toolchain; takes a few seconds. the `sh` side of the pipe:
**Prebuilt binary** (no Rust), from the latest GitHub release:
```bash
curl -fsSL https://raw.githubusercontent.com/Expressive-Tea/matcha/main/install.sh | sh
```
Drops the binary in `~/.local/bin`. Env vars go on the `sh` side of the pipe:
```bash ```bash
curl -fsSL …/install.sh | MATCHA_VERSION=v26.7.0 MATCHA_INSTALL_DIR=/usr/local/bin sh curl -fsSL …/install.sh | MATCHA_VERSION=v26.7.0 MATCHA_INSTALL_DIR=/usr/local/bin sh
``` ```
**From git** (compiles the default branch): **From source** (requires Rust — compiles and installs):
```bash ```bash
cargo install --git https://github.com/Expressive-Tea/matcha cargo install --git https://git.svc.zoit.services/Green-Tea/matcha
``` ```
## Usage ## Usage
+6 -9
View File
@@ -1,17 +1,14 @@
#!/bin/sh #!/bin/sh
# matcha installer — downloads a prebuilt binary from GitHub Releases. # matcha installer — downloads a prebuilt binary from Gitea Releases.
# curl -fsSL <raw>/install.sh | sh # curl -fsSL <raw>/install.sh | sh
# Env: MATCHA_VERSION (tag, default latest), MATCHA_INSTALL_DIR (default ~/.local/bin), # Env: MATCHA_VERSION (tag, default latest), MATCHA_INSTALL_DIR (default ~/.local/bin),
# MATCHA_REPO_BASE / MATCHA_API_BASE (override to install from the internal Gitea, # MATCHA_REPO_BASE (default the Gitea repo URL).
# whose release API is GitHub-compatible for everything this script touches).
set -eu set -eu
# Public by default: the Gitea host is unreachable outside the network, and this script REPO_BASE="${MATCHA_REPO_BASE:-https://git.svc.zoit.services/Green-Tea/matcha}"
# is what crates.io and the README point people at. # The API lives at the host root (/api/v1/...), NOT under the repo path. Keep it
REPO_BASE="${MATCHA_REPO_BASE:-https://github.com/Expressive-Tea/matcha}" # separate from REPO_BASE (which is used for release DOWNLOAD urls under the repo).
# The API lives on its own host, NOT under the repo path. Keep it separate from API_BASE="${MATCHA_API_BASE:-https://git.svc.zoit.services/api/v1/repos/Green-Tea/matcha}"
# REPO_BASE (which is used for release DOWNLOAD urls under the repo).
API_BASE="${MATCHA_API_BASE:-https://api.github.com/repos/Expressive-Tea/matcha}"
INSTALL_DIR="${MATCHA_INSTALL_DIR:-$HOME/.local/bin}" INSTALL_DIR="${MATCHA_INSTALL_DIR:-$HOME/.local/bin}"
err() { echo "matcha-install: $*" >&2; exit 1; } err() { echo "matcha-install: $*" >&2; exit 1; }
+1 -1
View File
@@ -21,7 +21,7 @@ pub enum Command {
Run, Run,
/// Generate a piece and auto-wire it into the module /// Generate a piece and auto-wire it into the module
Create { Create {
#[arg(value_parser = ["module", "controller", "step", "provider"])] #[arg(value_parser = ["module", "controller", "step"])]
kind: String, kind: String,
name: String, name: String,
#[arg(long)] #[arg(long)]
+29 -111
View File
@@ -1,42 +1,33 @@
//! `matcha create <kind> <Name>` — generate a stub file for `<kind>` and //! `matcha create <kind> <Name>` — generate a stub file for `<kind>` and
//! auto-wire it into `src/app.module.ts` via the pure text-editing helpers //! auto-wire it into `src/app.module.ts` via the pure text-editing helpers
//! in `wire`. //! 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::io::{Error, ErrorKind};
use std::path::Path; use std::path::Path;
use crate::wire; 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<()> { pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
match kind { match kind {
"controller" => create_piece( "controller" => create_controller(name, check),
name, "module" | "step" => Err(Error::new(
check, ErrorKind::Unsupported,
"controllers", format!("create {kind} not implemented yet"),
"controller", )),
"Controller",
"controllers",
controller_stub(name),
),
"step" => create_piece(
name,
check,
"steps",
"step",
"Step",
"steps",
step_stub(name),
),
"provider" => create_piece(
name,
check,
"providers",
"provider",
"Provider",
"providers",
provider_stub(name),
),
"module" => create_module(name, check),
other => Err(Error::new( other => Err(Error::new(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
format!("unknown kind {other}"), format!("unknown kind {other}"),
@@ -44,78 +35,32 @@ pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
} }
} }
/// Writes a piece file under `src/<subdir>/` and wires it into the `@Module` fn create_controller(name: &str, check: bool) -> std::io::Result<()> {
/// in `src/app.module.ts` (`module_key` array). Emit-only + hint on failure. let file = Path::new("src/controllers").join(format!("{}.controller.ts", name.to_lowercase()));
#[allow(clippy::too_many_arguments)]
fn create_piece(
name: &str,
check: bool,
subdir: &str,
ext: &str,
suffix: &str,
module_key: &str,
stub: String,
) -> std::io::Result<()> {
let lower = name.to_lowercase();
let file = Path::new("src")
.join(subdir)
.join(format!("{lower}.{ext}.ts"));
std::fs::create_dir_all(file.parent().unwrap())?; std::fs::create_dir_all(file.parent().unwrap())?;
std::fs::write(&file, stub)?; std::fs::write(&file, controller_stub(name))?;
println!("✓ {}", file.display()); println!("✓ {}", file.display());
let symbol = format!("{name}{suffix}"); let symbol = format!("{name}Controller");
let from = format!("./{subdir}/{lower}.{ext}"); let from = format!("./controllers/{}.controller", name.to_lowercase());
let module_path = Path::new("src/app.module.ts"); let module_path = Path::new("src/app.module.ts");
if !module_path.exists() { if !module_path.exists() {
println!("→ add {symbol} to your @Module manually (no src/app.module.ts found)"); println!("→ add {symbol} to your @Module manually (no src/app.module.ts found)");
return maybe_check(check); return Ok(());
} }
let src = std::fs::read_to_string(module_path)?; let src = std::fs::read_to_string(module_path)?;
let imported = wire::add_import(&src, &symbol, &from); let imported = wire::add_import(&src, &symbol, &from);
match wire::add_to_module_array(&imported, module_key, &symbol) { match wire::add_to_module_array(&imported, "controllers", &symbol) {
Some(wired) => { Some(wired) => {
std::fs::write(module_path, wired)?; std::fs::write(module_path, wired)?;
println!("✓ wired {symbol} into AppModule"); println!("✓ wired {symbol} into AppModule");
} }
None => { None => {
println!("→ could not auto-wire; add {symbol} to {module_key}[] in src/app.module.ts") // agreed fallback: emit-only, do NOT corrupt the module
println!("→ could not auto-wire; add {symbol} to controllers[] in src/app.module.ts");
} }
} }
maybe_check(check)
}
/// Writes `src/<name>.module.ts` and registers it in the `createApp({ modules })`
/// call in `src/main.ts`. Emit-only + hint on failure.
fn create_module(name: &str, check: bool) -> std::io::Result<()> {
let lower = name.to_lowercase();
let file = Path::new("src").join(format!("{lower}.module.ts"));
std::fs::create_dir_all(file.parent().unwrap())?;
std::fs::write(&file, module_stub(name))?;
println!("✓ {}", file.display());
let symbol = format!("{name}Module");
let from = format!("./{lower}.module");
let main_path = Path::new("src/main.ts");
if !main_path.exists() {
println!("→ register {symbol} in createApp({{ modules }}) manually (no src/main.ts found)");
return maybe_check(check);
}
let src = std::fs::read_to_string(main_path)?;
let imported = wire::add_import(&src, &symbol, &from);
match wire::add_to_createapp_modules(&imported, &symbol) {
Some(wired) => {
std::fs::write(main_path, wired)?;
println!("✓ registered {symbol} in createApp");
}
None => println!(
"→ could not auto-register; add {symbol} to createApp modules[] in src/main.ts"
),
}
maybe_check(check)
}
fn maybe_check(check: bool) -> std::io::Result<()> {
if check { if check {
match crate::check::run(Path::new(".")) { match crate::check::run(Path::new(".")) {
Ok(true) => println!("✓ type-check passed"), Ok(true) => println!("✓ type-check passed"),
@@ -123,33 +68,6 @@ fn maybe_check(check: bool) -> std::io::Result<()> {
Err(e) => println!("⚠ could not run type-check: {e}"), Err(e) => println!("⚠ could not run type-check: {e}"),
} }
} }
Ok(()) Ok(())
} }
fn controller_stub(name: &str) -> String {
let lower = name.to_lowercase();
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"
)
}
fn step_stub(name: &str) -> String {
let lower = name.to_lowercase();
format!(
"import {{ Step }} from '@green-tea/core';\n\n@Step({{ provides: '{lower}', needs: [] }})\nexport class {name}Step {{\n run(ctx: Record<string, unknown>) {{\n return {{ {lower}: null }};\n }}\n}}\n"
)
}
fn provider_stub(name: &str) -> String {
let lower = name.to_lowercase();
format!(
"import {{ Provider }} from '@green-tea/core';\n\n@Provider({{ provides: '{lower}' }})\nexport class {name}Provider {{\n provide() {{\n return {{ {lower}: null }};\n }}\n}}\n"
)
}
fn module_stub(name: &str) -> String {
let lower = name.to_lowercase();
format!(
"import {{ Module }} from '@green-tea/core';\n\n@Module({{ mountpoint: '/{lower}', controllers: [], providers: [], steps: [] }})\nexport class {name}Module {{}}\n"
)
}
+30 -172
View File
@@ -162,40 +162,18 @@ fn find_named_imports<'a>(root: &Node<'a>, src: &str, from: &str) -> Option<Node
} }
/// Finds the `key: [ ... ]` array inside the first `@Module({...})` and /// Finds the `key: [ ... ]` array inside the first `@Module({...})` and
/// inserts `symbol` into it, creating `key: [symbol]` inside the module /// inserts `symbol` into it. Idempotent: a repeat call that would insert an
/// object when that key is absent entirely. Idempotent: a repeat call that /// already-present symbol is a no-op. Returns `None` — leaving the caller's
/// would insert an already-present symbol is a no-op. Returns `None` — /// original text untouched — when the edited text fails to re-parse clean
/// leaving the caller's original text untouched — when the edited text fails /// (an `ERROR`/missing node appears), which is also what happens when `key`
/// to re-parse clean (an `ERROR`/missing node appears), or when there is no /// doesn't exist in the module object at all (the splice can't be located).
/// `@Module(...)` object to target at all.
pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option<String> { pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option<String> {
let tree = parser().parse(src, None).unwrap(); let tree = parser().parse(src, None).unwrap();
let root = tree.root_node(); let (open, close, existing) = find_array(&tree.root_node(), src, key)?;
let object = find_module_object(&root, src)?; if existing.split(',').map(str::trim).any(|s| s == symbol) {
insert_into_object_array(src, object, key, symbol)
}
/// Inserts `symbol` into the `modules` array of the first `createApp(...)`
/// call's argument object (creating the `modules` key if absent). Idempotent;
/// reverts (returns `None`) on parse breakage or when no `createApp(...)` call
/// with an object argument is found.
pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option<String> {
let tree = parser().parse(src, None).unwrap();
let root = tree.root_node();
let object = find_createapp_object(&root, src)?;
insert_into_object_array(src, object, "modules", symbol)
}
/// Inserts `symbol` into the `key: [...]` array directly inside `object`
/// (an object-literal node). If that `key` pair is absent, a new
/// `key: [symbol]` pair is inserted into the object. Idempotent; re-parses and
/// returns `None` on breakage.
fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> Option<String> {
if let Some((open, close)) = find_key_array_span(object, src, key) {
let inner = &src[open + 1..close];
if inner.split(',').map(str::trim).any(|s| s == symbol) {
return Some(src.to_string()); // idempotent return Some(src.to_string()); // idempotent
} }
let inner = &src[open + 1..close]; // between [ ]
let joined = if inner.trim().is_empty() { let joined = if inner.trim().is_empty() {
symbol.to_string() symbol.to_string()
} else { } else {
@@ -205,31 +183,6 @@ fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) ->
out.push_str(&src[..open + 1]); out.push_str(&src[..open + 1]);
out.push_str(&joined); out.push_str(&joined);
out.push_str(&src[close..]); out.push_str(&src[close..]);
return if parses_clean(&out) { Some(out) } else { None };
}
// The key exists but its value isn't an array literal (e.g. `controllers: SHARED`
// or `modules: MODULES`). Creating a second `key: [...]` pair parses clean yet
// silently shadows the user's value at runtime (JS keeps the last duplicate key),
// so `parses_clean` can't catch it. Refuse — the caller falls back to emit-only.
if object_has_key(object, src, key) {
return None;
}
// key absent → create `key: [symbol]` inside the object, before its '}'
let obj_open = object.start_byte();
let obj_close = object.end_byte() - 1; // the '}'
let existing = src[obj_open + 1..obj_close].trim();
let pair = format!("{key}: [{symbol}]");
let new_inner = if existing.is_empty() {
format!(" {pair} ")
} else {
format!(" {}, {pair} ", existing.trim_end_matches(','))
};
let mut out = String::with_capacity(src.len() + pair.len() + 4);
out.push_str(&src[..obj_open + 1]);
out.push_str(&new_inner);
out.push_str(&src[obj_close..]);
if parses_clean(&out) { if parses_clean(&out) {
Some(out) Some(out)
} else { } else {
@@ -237,29 +190,18 @@ fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) ->
} }
} }
/// True when `object` has any direct `pair` child whose key text equals `key`, /// Returns `(open_bracket_byte, close_bracket_byte, inner_text)` for the
/// regardless of the value's kind. Used to avoid creating a duplicate key when /// `key: [...]` pair found directly inside the first `@Module({...})`
/// an existing pair's value isn't an array literal. /// decorator's argument object. Unscoped searches over the whole tree would
fn object_has_key(object: Node, src: &str, key: &str) -> bool { /// risk matching a same-named key in an unrelated object literal (e.g. a
let mut c = object.walk(); /// nested `providers:`/`controllers:` array inside `imports: [X.register({
for child in object.named_children(&mut c) { /// ... })]`, or a decoy object literal elsewhere in the file) — scoping to
if child.kind() == "pair" /// the `@Module(...)` object's own pairs avoids that.
&& child fn find_array(root: &Node, src: &str, key: &str) -> Option<(usize, usize, String)> {
.child_by_field_name("key") let module_object = find_module_object(root, src)?;
.and_then(|k| k.utf8_text(src.as_bytes()).ok())
== Some(key)
{
return true;
}
}
false
}
/// Returns `(open_bracket_byte, close_bracket_byte)` of the `key: [...]` array let mut c = module_object.walk();
/// among `object`'s direct `pair` children, or `None` if absent. for child in module_object.named_children(&mut c) {
fn find_key_array_span(object: Node, src: &str, key: &str) -> Option<(usize, usize)> {
let mut c = object.walk();
for child in object.named_children(&mut c) {
if child.kind() != "pair" { if child.kind() != "pair" {
continue; continue;
} }
@@ -275,43 +217,14 @@ fn find_key_array_span(object: Node, src: &str, key: &str) -> Option<(usize, usi
if v.kind() != "array" { if v.kind() != "array" {
continue; continue;
} }
return Some((v.start_byte(), v.end_byte() - 1)); 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 None
} }
/// Locates the argument object literal of the first `createApp(...)` call
/// expression (function identifier `createApp`), in source order.
fn find_createapp_object<'a>(root: &Node<'a>, src: &str) -> Option<Node<'a>> {
fn visit<'a>(node: Node<'a>, src: &str) -> Option<Node<'a>> {
if node.kind() == "call_expression" {
let is_createapp = node
.child_by_field_name("function")
.filter(|f| f.kind() == "identifier")
.and_then(|f| f.utf8_text(src.as_bytes()).ok())
== Some("createApp");
if is_createapp {
if let Some(args) = node.child_by_field_name("arguments") {
let mut ac = args.walk();
for child in args.named_children(&mut ac) {
if child.kind() == "object" {
return Some(child);
}
}
}
}
}
let mut c = node.walk();
for child in node.children(&mut c) {
if let Some(r) = visit(child, src) {
return Some(r);
}
}
None
}
visit(*root, src)
}
/// Inserts `method_src` immediately before the closing `}` of `class /// Inserts `method_src` immediately before the closing `}` of `class
/// <class>`'s body. Returns `None` — leaving the caller's original text /// <class>`'s body. Returns `None` — leaving the caller's original text
/// untouched — when the edited text fails to re-parse clean, or when no /// untouched — when the edited text fails to re-parse clean, or when no
@@ -434,11 +347,7 @@ export class AppModule {}
#[test] #[test]
fn broken_result_is_rejected() { fn broken_result_is_rejected() {
// Predates create-if-absent: `providers` used to be missing entirely, // key missing entirely → our splice can't find it → None, file untouched upstream
// so the old `find_array` couldn't locate it → None. Now the key is
// created instead, so either outcome is accepted here; the dedicated
// `creates_providers_key_and_reverts_on_break` test above covers the
// create-if-absent behavior explicitly.
assert!( assert!(
add_to_module_array(MOD, "providers", "X").is_none() add_to_module_array(MOD, "providers", "X").is_none()
|| add_to_module_array(MOD, "providers", "X") || add_to_module_array(MOD, "providers", "X")
@@ -447,11 +356,12 @@ export class AppModule {}
); );
} }
/// Extra coverage beyond the brief: this exercises the `None` path where /// Extra coverage beyond the brief: `broken_result_is_rejected` above only
/// `insert_into_object_array` finds (or creates) the target but the /// exercises the "key not found" `None` path (via `find_array`). This
/// splice produces text that no longer parses clean — proving the /// exercises the *other* `None` path — a splice that finds the array but
/// revert-on-ERROR guarantee (`parses_clean` check) is real, not just /// produces text that no longer parses clean — proving the revert-on-ERROR
/// theoretically reachable. /// guarantee (`parses_clean` check in `add_to_module_array`) is real, not
/// just theoretically reachable.
#[test] #[test]
fn revert_on_actual_parse_error() { fn revert_on_actual_parse_error() {
// A "symbol" containing stray syntax breaks the array/object/class // A "symbol" containing stray syntax breaks the array/object/class
@@ -516,56 +426,4 @@ export class AppModule {}
let out = add_import(src, "Sse", "@green-tea/core"); let out = add_import(src, "Sse", "@green-tea/core");
assert!(out.contains("import { Sse } from '@green-tea/core';")); assert!(out.contains("import { Sse } from '@green-tea/core';"));
} }
#[test]
fn creates_steps_key_when_absent() {
// MOD has only `controllers` — adding a step must CREATE `steps: [...]`
let out = add_to_module_array(MOD, "steps", "PasitoStep").unwrap();
assert!(out.contains("steps: [PasitoStep]"));
assert!(out.contains("controllers: [HomeController]")); // untouched
// idempotent
assert_eq!(
add_to_module_array(&out, "steps", "PasitoStep").unwrap(),
out
);
}
#[test]
fn creates_providers_key_and_reverts_on_break() {
let out = add_to_module_array(MOD, "providers", "ConfigProvider").unwrap();
assert!(out.contains("providers: [ConfigProvider]"));
// a symbol with stray syntax must still be rejected (revert guard)
assert!(add_to_module_array(MOD, "providers", "X]; class Evil {").is_none());
}
const MAIN: &str = "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nconst app = createApp({ modules: [AppModule] });\n";
#[test]
fn adds_module_to_createapp() {
let out = add_to_createapp_modules(MAIN, "UsersModule").unwrap();
assert!(out.contains("AppModule, UsersModule"));
assert_eq!(add_to_createapp_modules(&out, "UsersModule").unwrap(), out);
// idempotent
}
#[test]
fn createapp_creates_modules_key_when_absent() {
let src = "const app = createApp({});\n";
let out = add_to_createapp_modules(src, "AppModule").unwrap();
assert!(out.contains("modules: [AppModule]"));
}
#[test]
fn refuses_duplicate_key_when_module_value_not_array() {
// `controllers` exists but its value is an identifier, not an array literal.
// Adding must NOT create a second `controllers` pair (silent runtime shadowing).
let src = "@Module({ mountpoint: '/', controllers: SHARED })\nexport class AppModule {}\n";
assert!(add_to_module_array(src, "controllers", "X").is_none());
}
#[test]
fn refuses_duplicate_modules_when_createapp_value_not_array() {
let src = "const app = createApp({ modules: MODULES });\n";
assert!(add_to_createapp_modules(src, "UsersModule").is_none());
}
} }
-54
View File
@@ -30,57 +30,3 @@ fn create_controller_writes_and_wires() {
assert!(module.contains("UsersController")); assert!(module.contains("UsersController"));
assert!(module.contains("import { UsersController }")); assert!(module.contains("import { UsersController }"));
} }
#[test]
fn create_step_writes_and_wires() {
let d = tempdir().unwrap();
seed_module(d.path()); // writes src/app.module.ts with `@Module({ controllers: [] })`
Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path())
.args(["create", "step", "Pasito"])
.assert()
.success();
assert!(d.path().join("src/steps/pasito.step.ts").exists());
let m = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap();
assert!(m.contains("PasitoStep"));
assert!(m.contains("import { PasitoStep }"));
assert!(m.contains("steps: [PasitoStep]"));
}
#[test]
fn create_provider_writes_and_wires() {
let d = tempdir().unwrap();
seed_module(d.path());
Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path())
.args(["create", "provider", "Config"])
.assert()
.success();
assert!(d.path().join("src/providers/config.provider.ts").exists());
let m = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap();
assert!(m.contains("providers: [ConfigProvider]"));
assert!(m.contains("import { ConfigProvider }"));
}
#[test]
fn create_module_writes_and_registers_in_createapp() {
let d = tempdir().unwrap();
std::fs::create_dir_all(d.path().join("src")).unwrap();
std::fs::write(
d.path().join("src/main.ts"),
"import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nconst app = createApp({ modules: [AppModule] });\n",
)
.unwrap();
Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path())
.args(["create", "module", "Users"])
.assert()
.success();
assert!(d.path().join("src/users.module.ts").exists());
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
assert!(main.contains("AppModule, UsersModule"));
assert!(main.contains("import { UsersModule }"));
}