Compare commits
41
Commits
de000cb27d
...
v26.7.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a3dae99f5 | ||
|
|
c95ca6c812 | ||
|
|
eb65f472dd | ||
|
|
444567ffb3 | ||
|
|
314bf3a4b0 | ||
|
|
3066cc477e | ||
|
|
9fd1181497 | ||
|
|
7c6d01212e | ||
|
|
59967af078 | ||
|
|
ed2deeda1c | ||
|
|
4cf92b18e5 | ||
|
|
77c3c2a0ff | ||
|
|
c7b58db24e | ||
|
|
7080b207a7 | ||
|
|
6d99144a75 | ||
|
|
235b87dcae | ||
|
|
6e84f467a8 | ||
|
|
995c3cd45e | ||
|
|
b630478985 | ||
|
|
7beadde4be | ||
|
|
48276890e8 | ||
|
|
8a282fa9c8 | ||
|
|
02c3c35d87 | ||
|
|
1b0a9b40a6 | ||
|
|
04e20cfccf | ||
|
|
b071896b10 | ||
|
|
4985adad00 | ||
|
|
685c51b7e0 | ||
|
|
3f86841d4b | ||
|
|
f84c50b97e | ||
|
|
277e0bd289 | ||
|
|
757b729986 | ||
|
|
bc013fde9f | ||
|
|
87d7e185d7 | ||
|
|
1b9990f02a | ||
|
|
e99dd58c66 | ||
|
|
13b77b3999 | ||
|
|
4df1e7ce7b | ||
|
|
acaee0d7e0 | ||
|
|
16480db7a2 | ||
|
|
2972326103 |
No files matched your search
@@ -0,0 +1,79 @@
|
|||||||
|
name: Release
|
||||||
|
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
|
||||||
@@ -1 +1,3 @@
|
|||||||
/target
|
/target
|
||||||
|
.superpowers/
|
||||||
|
.specs/
|
||||||
@@ -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 <name> [--template-url gh:owner/repo] # scaffold a project
|
|
||||||
matcha run # detect runtime, run in watch
|
|
||||||
matcha create <module|controller|step> <Name> # generate a piece + auto-wire
|
|
||||||
matcha add <sse|stream|buffer> # 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:
|
|
||||||
|
|
||||||
```
|
|
||||||
<name>/
|
|
||||||
src/app.module.ts # @Module wiring HomeController
|
|
||||||
src/controllers/home.controller.ts
|
|
||||||
public/index.html # logo + EventSource('/zen')
|
|
||||||
<runtime config> # 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).
|
|
||||||
File diff suppressed because it is too large.
Load diff
Generated
+1
-1
@@ -254,7 +254,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "matcha"
|
name = "matcha"
|
||||||
version = "0.1.0"
|
version = "26.7.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"assert_cmd",
|
"assert_cmd",
|
||||||
"clap",
|
"clap",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "matcha"
|
name = "matcha"
|
||||||
version = "0.1.0"
|
version = "26.7.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# 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
|
||||||
|
curl -fsSL https://git.svc.zoit.services/Green-Tea/matcha/raw/branch/main/install.sh | sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Installs a prebuilt binary to `~/.local/bin` — no Rust required. Env vars go on
|
||||||
|
the `sh` side of the pipe:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -fsSL …/install.sh | MATCHA_VERSION=v26.7.0 MATCHA_INSTALL_DIR=/usr/local/bin sh
|
||||||
|
```
|
||||||
|
|
||||||
|
**From source** (requires Rust — compiles and installs):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo install --git https://git.svc.zoit.services/Green-Tea/matcha
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
matcha new my-api # scaffold from the official starter
|
||||||
|
matcha new my-api --template-url gh:owner/repo # scaffold from any git template
|
||||||
|
matcha run # detect node/deno/bun and run in watch
|
||||||
|
matcha create controller Users # generate + auto-wire into @Module
|
||||||
|
matcha add sse # add a capability (sse|stream|buffer) to your controller
|
||||||
|
```
|
||||||
|
|
||||||
|
### The starter
|
||||||
|
|
||||||
|
`matcha new <name>` (no flags) scaffolds a live app: it serves an `index.html`
|
||||||
|
with the green-tea logo and streams a rotating zen message over `@Sse('/zen')`.
|
||||||
|
Open the browser and it's already alive — `matcha run` boots it.
|
||||||
|
|
||||||
|
### `create` / `add` auto-wiring
|
||||||
|
|
||||||
|
`create` and `add` edit your TypeScript with tree-sitter: they insert imports
|
||||||
|
and wire pieces into the right `@Module` array or controller. Edits are
|
||||||
|
idempotent and revert themselves if they would break the file's syntax. Pass
|
||||||
|
`--check` to `create` to type-check with your project's runtime afterward.
|
||||||
|
|
||||||
|
## Runtime detection
|
||||||
|
|
||||||
|
`matcha run` picks the runtime by precedence, first match wins:
|
||||||
|
|
||||||
|
1. `matcha.toml` — `runtime = "node" | "deno" | "bun"`
|
||||||
|
2. `deno.json` / `deno.jsonc` → **deno**
|
||||||
|
3. `bun.lockb` / `bun.lock` → **bun**
|
||||||
|
4. `package.json` → **node**
|
||||||
|
|
||||||
|
Edge is a deploy target, not a `matcha run` target.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT — same as the green-tea framework. Contributions require a DCO sign-off (`git commit -s`).
|
||||||
Executable
+84
@@ -0,0 +1,84 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# matcha installer — downloads a prebuilt binary from Gitea Releases.
|
||||||
|
# curl -fsSL <raw>/install.sh | sh
|
||||||
|
# Env: MATCHA_VERSION (tag, default latest), MATCHA_INSTALL_DIR (default ~/.local/bin),
|
||||||
|
# MATCHA_REPO_BASE (default the Gitea repo URL).
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
REPO_BASE="${MATCHA_REPO_BASE:-https://git.svc.zoit.services/Green-Tea/matcha}"
|
||||||
|
# The API lives at the host root (/api/v1/...), NOT under the repo path. Keep it
|
||||||
|
# separate from REPO_BASE (which is used for release DOWNLOAD urls under the repo).
|
||||||
|
API_BASE="${MATCHA_API_BASE:-https://git.svc.zoit.services/api/v1/repos/Green-Tea/matcha}"
|
||||||
|
INSTALL_DIR="${MATCHA_INSTALL_DIR:-$HOME/.local/bin}"
|
||||||
|
|
||||||
|
err() { echo "matcha-install: $*" >&2; exit 1; }
|
||||||
|
|
||||||
|
if command -v curl >/dev/null 2>&1; then
|
||||||
|
fetch_out() { curl -fsSL "$1" -o "$2"; }
|
||||||
|
fetch() { curl -fsSL "$1"; }
|
||||||
|
elif command -v wget >/dev/null 2>&1; then
|
||||||
|
fetch_out() { wget -qO "$2" "$1"; }
|
||||||
|
fetch() { wget -qO- "$1"; }
|
||||||
|
else
|
||||||
|
err "need curl or wget"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if command -v sha256sum >/dev/null 2>&1; then
|
||||||
|
sha256() { sha256sum "$1" | awk '{print $1}'; }
|
||||||
|
elif command -v shasum >/dev/null 2>&1; then
|
||||||
|
sha256() { shasum -a 256 "$1" | awk '{print $1}'; }
|
||||||
|
else
|
||||||
|
err "need sha256sum or shasum"
|
||||||
|
fi
|
||||||
|
|
||||||
|
os=$(uname -s); arch=$(uname -m)
|
||||||
|
case "$os" in
|
||||||
|
Darwin)
|
||||||
|
case "$arch" in
|
||||||
|
arm64|aarch64) triple="aarch64-apple-darwin" ;;
|
||||||
|
x86_64) triple="x86_64-apple-darwin" ;;
|
||||||
|
*) err "unsupported macOS arch: $arch" ;;
|
||||||
|
esac ;;
|
||||||
|
Linux)
|
||||||
|
case "$arch" in
|
||||||
|
x86_64|amd64) triple="x86_64-unknown-linux-musl" ;;
|
||||||
|
arm64|aarch64) err "linux arm64 has no prebuilt binary yet — use: cargo install --git $REPO_BASE" ;;
|
||||||
|
*) err "unsupported Linux arch: $arch" ;;
|
||||||
|
esac ;;
|
||||||
|
*) err "unsupported OS: $os — try: cargo install --git $REPO_BASE" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
version="${MATCHA_VERSION:-latest}"
|
||||||
|
if [ "$version" = "latest" ]; then
|
||||||
|
tag=$(fetch "$API_BASE/releases/latest" \
|
||||||
|
| grep -o '"tag_name":[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||||
|
[ -n "$tag" ] || err "could not resolve latest release tag"
|
||||||
|
else
|
||||||
|
tag="$version"
|
||||||
|
fi
|
||||||
|
|
||||||
|
asset="matcha-${triple}.tar.gz"
|
||||||
|
url="$REPO_BASE/releases/download/${tag}/${asset}"
|
||||||
|
|
||||||
|
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
|
||||||
|
echo "matcha-install: downloading $asset ($tag)"
|
||||||
|
fetch_out "$url" "$tmp/$asset" || err "download failed: $url"
|
||||||
|
fetch_out "$url.sha256" "$tmp/$asset.sha256" || err "checksum download failed: $url.sha256"
|
||||||
|
|
||||||
|
want=$(awk '{print $1}' < "$tmp/$asset.sha256")
|
||||||
|
got=$(sha256 "$tmp/$asset")
|
||||||
|
[ -n "$want" ] || err "empty checksum file"
|
||||||
|
[ "$want" = "$got" ] || err "checksum mismatch (want $want, got $got)"
|
||||||
|
|
||||||
|
tar -xzf "$tmp/$asset" -C "$tmp"
|
||||||
|
[ -f "$tmp/matcha" ] || err "archive did not contain 'matcha'"
|
||||||
|
mkdir -p "$INSTALL_DIR"
|
||||||
|
chmod +x "$tmp/matcha"
|
||||||
|
mv "$tmp/matcha" "$INSTALL_DIR/matcha"
|
||||||
|
|
||||||
|
echo "matcha-install: installed to $INSTALL_DIR/matcha ($tag)"
|
||||||
|
case ":${PATH}:" in
|
||||||
|
*":$INSTALL_DIR:"*) ;;
|
||||||
|
*) echo "matcha-install: add to PATH -> export PATH=\"$INSTALL_DIR:\$PATH\"" ;;
|
||||||
|
esac
|
||||||
|
"$INSTALL_DIR/matcha" --version 2>/dev/null || true
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
use crate::runtime::{self, Runtime};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
fn check_command(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
||||||
|
match rt {
|
||||||
|
Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]),
|
||||||
|
Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]),
|
||||||
|
Runtime::Node => ("npx", vec!["tsc", "--noEmit"]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(dir: &Path) -> std::io::Result<bool> {
|
||||||
|
let Some(rt) = runtime::detect(dir) else {
|
||||||
|
return Ok(true);
|
||||||
|
}; // nothing to check against
|
||||||
|
let (prog, args) = check_command(rt);
|
||||||
|
let status = std::process::Command::new(prog)
|
||||||
|
.args(&args)
|
||||||
|
.current_dir(dir)
|
||||||
|
.status()?;
|
||||||
|
Ok(status.success())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::runtime::Runtime;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deno_check_cmd() {
|
||||||
|
assert_eq!(
|
||||||
|
check_command(Runtime::Deno),
|
||||||
|
("deno", vec!["check", "src/app.module.ts"])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn node_uses_tsc_noemit() {
|
||||||
|
assert_eq!(
|
||||||
|
check_command(Runtime::Node),
|
||||||
|
("npx", vec!["tsc", "--noEmit"])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bun_uses_bunx_tsc_noemit() {
|
||||||
|
assert_eq!(
|
||||||
|
check_command(Runtime::Bun),
|
||||||
|
("bunx", vec!["tsc", "--noEmit"])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-2
@@ -1,7 +1,7 @@
|
|||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(name = "matcha", about = "green-tea CLI")]
|
#[command(name = "matcha", version, about = "green-tea CLI")]
|
||||||
pub struct Cli {
|
pub struct Cli {
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
pub command: Command,
|
pub command: Command,
|
||||||
@@ -14,12 +14,14 @@ pub enum Command {
|
|||||||
name: String,
|
name: String,
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
template_url: Option<String>,
|
template_url: Option<String>,
|
||||||
|
#[arg(long, default_value = "node", value_parser = ["node", "deno", "bun"])]
|
||||||
|
runtime: String,
|
||||||
},
|
},
|
||||||
/// Detect the runtime and run the project in watch mode
|
/// Detect the runtime and run the project in watch mode
|
||||||
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"])]
|
#[arg(value_parser = ["module", "controller", "step", "provider"])]
|
||||||
kind: String,
|
kind: String,
|
||||||
name: String,
|
name: String,
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
//! `matcha add <sse|stream|buffer>` — appends a capability handler method to
|
||||||
|
//! the single controller found under `src/controllers`, wiring in the
|
||||||
|
//! decorator import via `wire::add_import` and splicing the method body via
|
||||||
|
//! `wire::insert_method`.
|
||||||
|
|
||||||
|
use std::io::{Error, ErrorKind};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use crate::wire;
|
||||||
|
|
||||||
|
/// Returns `(decorator symbol, method source, dedup marker)` for a known
|
||||||
|
/// capability, or `None` for an unrecognized one.
|
||||||
|
///
|
||||||
|
/// The dedup marker is the route-path string literal baked into that
|
||||||
|
/// capability's `handler()` template (e.g. `'/events'`, `'/stream'`,
|
||||||
|
/// `'/data'`). It is unique per capability, unlike the decorator name — both
|
||||||
|
/// `buffer` and any pre-existing handler can legitimately use `@Get` — so
|
||||||
|
/// it's what `run` checks for before inserting, to keep `matcha add <cap>`
|
||||||
|
/// idempotent per capability rather than per decorator.
|
||||||
|
fn handler(cap: &str) -> Option<(&'static str, String, &'static str)> {
|
||||||
|
match cap {
|
||||||
|
"sse" => Some((
|
||||||
|
"Sse",
|
||||||
|
"\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(),
|
||||||
|
"'/events'",
|
||||||
|
)),
|
||||||
|
"stream" => Some((
|
||||||
|
"Stream",
|
||||||
|
"\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(),
|
||||||
|
"'/stream'",
|
||||||
|
)),
|
||||||
|
"buffer" => Some((
|
||||||
|
"Get",
|
||||||
|
"\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(),
|
||||||
|
"'/data'",
|
||||||
|
)),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds the single `*.controller.ts` file in `src/controllers`. Errors if
|
||||||
|
/// there are zero or more than one — this v1 has no way to disambiguate.
|
||||||
|
fn only_controller() -> std::io::Result<PathBuf> {
|
||||||
|
let dir = std::path::Path::new("src/controllers");
|
||||||
|
let mut hits: Vec<PathBuf> = std::fs::read_dir(dir)?
|
||||||
|
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||||
|
.filter(|p| p.to_string_lossy().ends_with(".controller.ts"))
|
||||||
|
.collect();
|
||||||
|
match hits.len() {
|
||||||
|
1 => Ok(hits.pop().unwrap()),
|
||||||
|
0 => Err(Error::new(
|
||||||
|
ErrorKind::NotFound,
|
||||||
|
"no *.controller.ts in src/controllers",
|
||||||
|
)),
|
||||||
|
_ => Err(Error::other(
|
||||||
|
"multiple controllers; specify which (not yet supported)",
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extracts the class name following `export class `. This is a plain text
|
||||||
|
/// scan rather than a tree-sitter query — `insert_method` does the real
|
||||||
|
/// grammar-aware work once the name is known.
|
||||||
|
fn class_name(src: &str) -> Option<String> {
|
||||||
|
let idx = src.find("export class ")? + "export class ".len();
|
||||||
|
let rest = &src[idx..];
|
||||||
|
let end = rest.find(|c: char| !c.is_alphanumeric() && c != '_')?;
|
||||||
|
Some(rest[..end].to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(cap: &str) -> std::io::Result<()> {
|
||||||
|
let (decorator, method, marker) = handler(cap)
|
||||||
|
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("unknown capability {cap}")))?;
|
||||||
|
let path = only_controller()?;
|
||||||
|
let src = std::fs::read_to_string(&path)?;
|
||||||
|
let class = class_name(&src).ok_or_else(|| Error::other("no exported class found"))?;
|
||||||
|
if src.contains(marker) {
|
||||||
|
println!("→ {cap} already present in {class}");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// wire::add_import merges `decorator` into an existing
|
||||||
|
// `import { ... } from '@green-tea/core';` brace when one is already
|
||||||
|
// present, rather than appending a second import line for the same
|
||||||
|
// module (which would be a duplicate ESM binding — a hard SyntaxError,
|
||||||
|
// not a harmless dupe).
|
||||||
|
let with_import = wire::add_import(&src, decorator, "@green-tea/core");
|
||||||
|
match wire::insert_method(&with_import, &class, &method) {
|
||||||
|
Some(out) => {
|
||||||
|
std::fs::write(&path, out)?;
|
||||||
|
println!("✓ added @{decorator} to {class}");
|
||||||
|
}
|
||||||
|
None => println!(
|
||||||
|
"→ could not edit {}; add @{decorator} handler manually",
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
//! `matcha create <kind> <Name>` — generate a stub file for `<kind>` and
|
||||||
|
//! auto-wire it into `src/app.module.ts` via the pure text-editing helpers
|
||||||
|
//! in `wire`.
|
||||||
|
|
||||||
|
use std::io::{Error, ErrorKind};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::wire;
|
||||||
|
|
||||||
|
pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
|
||||||
|
match kind {
|
||||||
|
"controller" => create_piece(
|
||||||
|
name,
|
||||||
|
check,
|
||||||
|
"controllers",
|
||||||
|
"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(
|
||||||
|
ErrorKind::InvalidInput,
|
||||||
|
format!("unknown kind {other}"),
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a piece file under `src/<subdir>/` and wires it into the `@Module`
|
||||||
|
/// in `src/app.module.ts` (`module_key` array). Emit-only + hint on failure.
|
||||||
|
#[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::write(&file, stub)?;
|
||||||
|
println!("✓ {}", file.display());
|
||||||
|
|
||||||
|
let symbol = format!("{name}{suffix}");
|
||||||
|
let from = format!("./{subdir}/{lower}.{ext}");
|
||||||
|
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 maybe_check(check);
|
||||||
|
}
|
||||||
|
let src = std::fs::read_to_string(module_path)?;
|
||||||
|
let imported = wire::add_import(&src, &symbol, &from);
|
||||||
|
match wire::add_to_module_array(&imported, module_key, &symbol) {
|
||||||
|
Some(wired) => {
|
||||||
|
std::fs::write(module_path, wired)?;
|
||||||
|
println!("✓ wired {symbol} into AppModule");
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
println!("→ could not auto-wire; add {symbol} to {module_key}[] 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 {
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
}
|
||||||
+53
-6
@@ -1,23 +1,70 @@
|
|||||||
use std::io::{Error, ErrorKind};
|
use std::io::{Error, ErrorKind};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::runtime::Runtime;
|
||||||
use crate::template;
|
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);
|
let dest = Path::new(name);
|
||||||
if dest.exists() {
|
if dest.exists() {
|
||||||
return Err(Error::new(ErrorKind::AlreadyExists,
|
return Err(Error::new(
|
||||||
format!("'{name}' already exists")));
|
ErrorKind::AlreadyExists,
|
||||||
|
format!("'{name}' already exists"),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
match template_url {
|
match template_url {
|
||||||
None => {
|
None => {
|
||||||
|
let rt = Runtime::from_str(runtime).ok_or_else(|| {
|
||||||
|
Error::new(
|
||||||
|
ErrorKind::InvalidInput,
|
||||||
|
format!("unknown runtime '{runtime}'"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
std::fs::create_dir_all(dest)?;
|
std::fs::create_dir_all(dest)?;
|
||||||
template::write_starter(dest, name)?;
|
template::write_starter(dest, name, rt)?;
|
||||||
}
|
}
|
||||||
Some(_) => return Err(Error::new(ErrorKind::Unsupported,
|
Some(url) => clone_template(url, dest)?,
|
||||||
"--template-url not implemented yet")),
|
|
||||||
}
|
}
|
||||||
println!("✓ created {name}\n cd {name} && matcha run");
|
println!("✓ created {name}\n cd {name} && matcha run");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn resolve_url(spec: &str) -> String {
|
||||||
|
if let Some(rest) = spec.strip_prefix("gh:") {
|
||||||
|
format!("https://github.com/{rest}")
|
||||||
|
} else {
|
||||||
|
spec.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clone_template(url: &str, dest: &Path) -> std::io::Result<()> {
|
||||||
|
let status = std::process::Command::new("git")
|
||||||
|
.args(["clone", "--depth", "1", &resolve_url(url)])
|
||||||
|
.arg(dest)
|
||||||
|
.status()?;
|
||||||
|
if !status.success() {
|
||||||
|
return Err(Error::other("git clone failed"));
|
||||||
|
}
|
||||||
|
std::fs::remove_dir_all(dest.join(".git")).ok();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn gh_shorthand_expands() {
|
||||||
|
assert_eq!(
|
||||||
|
resolve_url("gh:green-tea/tmpl"),
|
||||||
|
"https://github.com/green-tea/tmpl"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn full_url_passes_through() {
|
||||||
|
assert_eq!(
|
||||||
|
resolve_url("https://example.com/x.git"),
|
||||||
|
"https://example.com/x.git"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
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!["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!["run", "dev"]));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn node_watch() {
|
||||||
|
assert_eq!(command_for(Runtime::Node), ("npm", vec!["run", "dev"]));
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
-5
@@ -1,7 +1,12 @@
|
|||||||
|
mod check;
|
||||||
mod cli;
|
mod cli;
|
||||||
|
mod cmd_add;
|
||||||
|
mod cmd_create;
|
||||||
mod cmd_new;
|
mod cmd_new;
|
||||||
|
mod cmd_run;
|
||||||
mod runtime;
|
mod runtime;
|
||||||
mod template;
|
mod template;
|
||||||
|
mod wire;
|
||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use cli::{Cli, Command};
|
use cli::{Cli, Command};
|
||||||
@@ -9,14 +14,33 @@ use cli::{Cli, Command};
|
|||||||
fn main() {
|
fn main() {
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
match cli.command {
|
match cli.command {
|
||||||
Command::New { name, template_url } => {
|
Command::New {
|
||||||
if let Err(e) = cmd_new::run(&name, template_url.as_deref()) {
|
name,
|
||||||
|
template_url,
|
||||||
|
runtime,
|
||||||
|
} => {
|
||||||
|
if let Err(e) = cmd_new::run(&name, template_url.as_deref(), &runtime) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Run => {
|
||||||
|
if let Err(e) = cmd_run::run(std::path::Path::new(".")) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Create { kind, name, check } => {
|
||||||
|
if let Err(e) = cmd_create::run(&kind, &name, check) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Add { capability } => {
|
||||||
|
if let Err(e) = cmd_add::run(&capability) {
|
||||||
eprintln!("error: {e}");
|
eprintln!("error: {e}");
|
||||||
std::process::exit(1);
|
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"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||||
pub enum Runtime {
|
pub enum Runtime {
|
||||||
Node,
|
Node,
|
||||||
@@ -9,7 +8,6 @@ pub enum Runtime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Runtime {
|
impl Runtime {
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn from_str(s: &str) -> Option<Runtime> {
|
pub fn from_str(s: &str) -> Option<Runtime> {
|
||||||
match s.trim() {
|
match s.trim() {
|
||||||
"node" => Some(Runtime::Node),
|
"node" => Some(Runtime::Node),
|
||||||
@@ -20,13 +18,11 @@ impl Runtime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
fn exists(dir: &Path, name: &str) -> bool {
|
fn exists(dir: &Path, name: &str) -> bool {
|
||||||
dir.join(name).exists()
|
dir.join(name).exists()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads `runtime = "..."` from matcha.toml without a TOML dep (one field only).
|
/// Reads `runtime = "..."` from matcha.toml without a TOML dep (one field only).
|
||||||
#[allow(dead_code)]
|
|
||||||
fn override_from_toml(dir: &Path) -> Option<Runtime> {
|
fn override_from_toml(dir: &Path) -> Option<Runtime> {
|
||||||
let text = std::fs::read_to_string(dir.join("matcha.toml")).ok()?;
|
let text = std::fs::read_to_string(dir.join("matcha.toml")).ok()?;
|
||||||
for line in text.lines() {
|
for line in text.lines() {
|
||||||
@@ -39,7 +35,6 @@ fn override_from_toml(dir: &Path) -> Option<Runtime> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn detect(dir: &Path) -> Option<Runtime> {
|
pub fn detect(dir: &Path) -> Option<Runtime> {
|
||||||
if let Some(r) = override_from_toml(dir) {
|
if let Some(r) = override_from_toml(dir) {
|
||||||
return Some(r);
|
return Some(r);
|
||||||
|
|||||||
+59
-7
@@ -1,10 +1,24 @@
|
|||||||
use include_dir::{include_dir, Dir};
|
use include_dir::{include_dir, Dir};
|
||||||
use std::path::Path;
|
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<()> {
|
pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared");
|
||||||
write_dir(&STARTER, dest, project_name)
|
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<()> {
|
fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> {
|
||||||
@@ -36,16 +50,54 @@ mod tests {
|
|||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn writes_starter_and_substitutes_name() {
|
fn deno_writes_shared_and_deno_overlay() {
|
||||||
let d = tempdir().unwrap();
|
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();
|
let html = std::fs::read_to_string(d.path().join("public/index.html")).unwrap();
|
||||||
assert!(html.contains("<title>my-api</title>"));
|
assert!(html.contains("<title>my-api</title>"));
|
||||||
assert!(!html.contains("{{project_name}}"));
|
assert!(!html.contains("{{project_name}}"));
|
||||||
assert!(d.path().join("src/controllers/home.controller.ts").exists());
|
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();
|
let module = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap();
|
||||||
assert!(module.contains("mountpoint"));
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+571
@@ -0,0 +1,571 @@
|
|||||||
|
//! Pure text-editing core for wiring generated TypeScript symbols into an
|
||||||
|
//! existing `@green-tea/core` project: adding `import` statements and
|
||||||
|
//! inserting symbols into a `@Module({...})` array (e.g. `controllers`,
|
||||||
|
//! `providers`).
|
||||||
|
//!
|
||||||
|
//! This module is intentionally free of CLI/I-O concerns — it operates on
|
||||||
|
//! `&str` in, `String`/`Option<String>` out — so it can be exercised with
|
||||||
|
//! plain string fixtures and reused by the `add` command (Task 8) without
|
||||||
|
//! any filesystem coupling.
|
||||||
|
//!
|
||||||
|
//! Resolved crate API notes (tree-sitter 0.22.6 / tree-sitter-typescript
|
||||||
|
//! 0.21.2, confirmed against the installed crate source, not just docs):
|
||||||
|
//! - The language accessor is the function `tree_sitter_typescript::language_typescript()`
|
||||||
|
//! (this crate version does NOT expose a `LANGUAGE_TYPESCRIPT` const).
|
||||||
|
//! - `Parser::set_language` takes `&Language`.
|
||||||
|
//! - Grammar node kinds `import_statement`, `pair`, `array` and field names
|
||||||
|
//! `key`/`value` on `pair` match the brief's assumptions (verified via
|
||||||
|
//! `typescript/src/node-types.json` in the resolved crate).
|
||||||
|
|
||||||
|
use tree_sitter::{Node, Parser};
|
||||||
|
|
||||||
|
/// Builds a fresh parser configured for the TypeScript grammar.
|
||||||
|
fn parser() -> Parser {
|
||||||
|
let mut p = Parser::new();
|
||||||
|
p.set_language(&tree_sitter_typescript::language_typescript())
|
||||||
|
.expect("load ts grammar");
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when tree-sitter parses `src` with no `ERROR`/missing node anywhere
|
||||||
|
/// in the tree. Used as the revert-on-breakage guarantee: if an edit fails
|
||||||
|
/// this check, the caller must discard it.
|
||||||
|
fn parses_clean(src: &str) -> bool {
|
||||||
|
let tree = parser().parse(src, None).unwrap();
|
||||||
|
!has_error(tree.root_node())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_error(node: Node) -> bool {
|
||||||
|
if node.is_error() || node.is_missing() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let mut c = node.walk();
|
||||||
|
for child in node.children(&mut c) {
|
||||||
|
if has_error(child) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wires `symbol` into `src`'s imports from module `from`:
|
||||||
|
///
|
||||||
|
/// 1. If an `import { ... } from '<from>';` statement already exists, merge
|
||||||
|
/// `symbol` into its named-imports brace (`{ A, B } ` → `{ A, B, symbol }`)
|
||||||
|
/// instead of appending a second, colliding `import` line for the same
|
||||||
|
/// module (a duplicate ESM binding is a hard `SyntaxError`/`TS2300`, not a
|
||||||
|
/// harmless dupe). Idempotent: a repeat call with `symbol` already present
|
||||||
|
/// in that brace returns `src` unchanged.
|
||||||
|
/// 2. Otherwise, appends `import { <symbol> } from '<from>';` after the last
|
||||||
|
/// top-level import statement (original behavior, for a module that isn't
|
||||||
|
/// imported yet at all).
|
||||||
|
///
|
||||||
|
/// The brace-merge edit is re-parsed with [`parses_clean`] before being
|
||||||
|
/// accepted; if merging somehow produces broken text, this falls back to
|
||||||
|
/// appending a fresh import line rather than returning broken source.
|
||||||
|
pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
||||||
|
let tree = parser().parse(src, None).unwrap();
|
||||||
|
let root = tree.root_node();
|
||||||
|
|
||||||
|
if let Some(named_imports) = find_named_imports(&root, src, from) {
|
||||||
|
let mut c = named_imports.walk();
|
||||||
|
let already_present = named_imports.named_children(&mut c).any(|spec| {
|
||||||
|
spec.kind() == "import_specifier"
|
||||||
|
&& spec
|
||||||
|
.child_by_field_name("name")
|
||||||
|
.and_then(|n| n.utf8_text(src.as_bytes()).ok())
|
||||||
|
== Some(symbol)
|
||||||
|
});
|
||||||
|
if already_present {
|
||||||
|
return src.to_string();
|
||||||
|
}
|
||||||
|
let open = named_imports.start_byte();
|
||||||
|
let close = named_imports.end_byte() - 1; // the '}'
|
||||||
|
let inner = src[open + 1..close].trim().trim_end_matches(',').trim_end();
|
||||||
|
let joined = if inner.is_empty() {
|
||||||
|
format!(" {symbol} ")
|
||||||
|
} else {
|
||||||
|
format!(" {inner}, {symbol} ")
|
||||||
|
};
|
||||||
|
let mut out = String::with_capacity(src.len() + symbol.len() + 2);
|
||||||
|
out.push_str(&src[..open + 1]);
|
||||||
|
out.push_str(&joined);
|
||||||
|
out.push_str(&src[close..]);
|
||||||
|
if parses_clean(&out) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// Merge produced broken text (shouldn't normally happen) — fall
|
||||||
|
// through to the append-a-new-line path below rather than return it.
|
||||||
|
}
|
||||||
|
|
||||||
|
let line = format!("import {{ {symbol} }} from '{from}';");
|
||||||
|
if src.contains(&line) {
|
||||||
|
return src.to_string();
|
||||||
|
}
|
||||||
|
let mut last_end = 0usize;
|
||||||
|
let mut c = root.walk();
|
||||||
|
for child in root.children(&mut c) {
|
||||||
|
if child.kind() == "import_statement" {
|
||||||
|
last_end = child.end_byte();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if last_end == 0 {
|
||||||
|
return format!("{line}\n{src}");
|
||||||
|
}
|
||||||
|
let mut out = String::with_capacity(src.len() + line.len() + 1);
|
||||||
|
out.push_str(&src[..last_end]);
|
||||||
|
out.push('\n');
|
||||||
|
out.push_str(&line);
|
||||||
|
out.push_str(&src[last_end..]);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds the `named_imports` (`{ A, B, C }`) brace of the top-level `import
|
||||||
|
/// { ... } from '<from>';` statement whose module specifier string literal
|
||||||
|
/// equals `from` exactly. Returns `None` when no import statement has that
|
||||||
|
/// source, or when the matching statement has no named-imports clause at all
|
||||||
|
/// (e.g. a bare default import) — callers treat that as "can't merge, fall
|
||||||
|
/// back to appending a new line".
|
||||||
|
fn find_named_imports<'a>(root: &Node<'a>, src: &str, from: &str) -> Option<Node<'a>> {
|
||||||
|
let mut c = root.walk();
|
||||||
|
for stmt in root.children(&mut c) {
|
||||||
|
if stmt.kind() != "import_statement" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(source) = stmt.child_by_field_name("source") else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Ok(raw) = source.utf8_text(src.as_bytes()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let unquoted = raw
|
||||||
|
.strip_prefix(['\'', '"'])
|
||||||
|
.and_then(|s| s.strip_suffix(['\'', '"']))
|
||||||
|
.unwrap_or(raw);
|
||||||
|
if unquoted != from {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut sc = stmt.walk();
|
||||||
|
for clause in stmt.children(&mut sc) {
|
||||||
|
if clause.kind() != "import_clause" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut cc = clause.walk();
|
||||||
|
for named in clause.children(&mut cc) {
|
||||||
|
if named.kind() == "named_imports" {
|
||||||
|
return Some(named);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds the `key: [ ... ]` array inside the first `@Module({...})` and
|
||||||
|
/// inserts `symbol` into it, creating `key: [symbol]` inside the module
|
||||||
|
/// object when that key is absent entirely. 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), or when there is no
|
||||||
|
/// `@Module(...)` object to target at all.
|
||||||
|
pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option<String> {
|
||||||
|
let tree = parser().parse(src, None).unwrap();
|
||||||
|
let root = tree.root_node();
|
||||||
|
let object = find_module_object(&root, src)?;
|
||||||
|
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
|
||||||
|
}
|
||||||
|
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..]);
|
||||||
|
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) {
|
||||||
|
Some(out)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when `object` has any direct `pair` child whose key text equals `key`,
|
||||||
|
/// regardless of the value's kind. Used to avoid creating a duplicate key when
|
||||||
|
/// an existing pair's value isn't an array literal.
|
||||||
|
fn object_has_key(object: Node, src: &str, key: &str) -> bool {
|
||||||
|
let mut c = object.walk();
|
||||||
|
for child in object.named_children(&mut c) {
|
||||||
|
if child.kind() == "pair"
|
||||||
|
&& child
|
||||||
|
.child_by_field_name("key")
|
||||||
|
.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
|
||||||
|
/// among `object`'s direct `pair` children, or `None` if absent.
|
||||||
|
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" {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
return Some((v.start_byte(), v.end_byte() - 1));
|
||||||
|
}
|
||||||
|
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
|
||||||
|
/// <class>`'s body. Returns `None` — leaving the caller's original text
|
||||||
|
/// untouched — when the edited text fails to re-parse clean, or when no
|
||||||
|
/// `class <class>` is found at all (the splice point can't be located).
|
||||||
|
pub fn insert_method(src: &str, class: &str, method_src: &str) -> Option<String> {
|
||||||
|
let tree = parser().parse(src, None).unwrap();
|
||||||
|
let close = find_class_body_close(&tree.root_node(), src, class)?;
|
||||||
|
let mut out = String::with_capacity(src.len() + method_src.len() + 1);
|
||||||
|
out.push_str(&src[..close]);
|
||||||
|
if !src[..close].ends_with('\n') {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
out.push_str(method_src);
|
||||||
|
out.push_str(&src[close..]);
|
||||||
|
if parses_clean(&out) {
|
||||||
|
Some(out)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds the byte offset of the closing `}` of `class <class>`'s body,
|
||||||
|
/// searching the whole tree in source order (depth-first).
|
||||||
|
fn find_class_body_close(root: &Node, src: &str, class: &str) -> Option<usize> {
|
||||||
|
fn visit(node: Node, src: &str, class: &str) -> Option<usize> {
|
||||||
|
if node.kind() == "class_declaration" {
|
||||||
|
if let Some(n) = node.child_by_field_name("name") {
|
||||||
|
if n.utf8_text(src.as_bytes()).ok() == Some(class) {
|
||||||
|
if let Some(body) = node.child_by_field_name("body") {
|
||||||
|
return Some(body.end_byte() - 1); // the closing '}'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut c = node.walk();
|
||||||
|
for child in node.children(&mut c) {
|
||||||
|
if let Some(r) = visit(child, src, class) {
|
||||||
|
return Some(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
visit(*root, src, class)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Locates the argument object literal of the first `@Module(...)`
|
||||||
|
/// decorator in `src`, in source order. A decorator node is recognized as
|
||||||
|
/// `@Module(...)` when its `call_expression` child has a `function` field
|
||||||
|
/// that is an `identifier` with text `"Module"`; the object literal is the
|
||||||
|
/// first `object`-kind named child of that call's `arguments` node.
|
||||||
|
///
|
||||||
|
/// Returns `None` when there is no `@Module(...)` decorator at all, or when
|
||||||
|
/// one exists but its argument isn't an object literal.
|
||||||
|
fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option<Node<'a>> {
|
||||||
|
fn find_decorator_call<'a>(node: Node<'a>, src: &str) -> Option<Node<'a>> {
|
||||||
|
if node.kind() == "decorator" {
|
||||||
|
let mut c = node.walk();
|
||||||
|
for child in node.children(&mut c) {
|
||||||
|
if child.kind() != "call_expression" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let is_module = child
|
||||||
|
.child_by_field_name("function")
|
||||||
|
.filter(|f| f.kind() == "identifier")
|
||||||
|
.and_then(|f| f.utf8_text(src.as_bytes()).ok())
|
||||||
|
== Some("Module");
|
||||||
|
if is_module {
|
||||||
|
return Some(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// This decorator isn't `@Module(...)`; keep looking elsewhere.
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut c = node.walk();
|
||||||
|
for child in node.children(&mut c) {
|
||||||
|
if let Some(r) = find_decorator_call(child, src) {
|
||||||
|
return Some(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
let call = find_decorator_call(*root, src)?;
|
||||||
|
let args = call.child_by_field_name("arguments")?;
|
||||||
|
let mut ac = args.walk();
|
||||||
|
let object = args
|
||||||
|
.named_children(&mut ac)
|
||||||
|
.find(|&child| child.kind() == "object");
|
||||||
|
object
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const MOD: &str = r#"import { Module } from '@green-tea/core';
|
||||||
|
import { HomeController } from './controllers/home.controller';
|
||||||
|
|
||||||
|
@Module({ controllers: [HomeController] })
|
||||||
|
export class AppModule {}
|
||||||
|
"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn import_is_added_once() {
|
||||||
|
let out = add_import(MOD, "UsersController", "./controllers/users.controller");
|
||||||
|
assert!(out.contains("import { UsersController } from './controllers/users.controller';"));
|
||||||
|
let twice = add_import(&out, "UsersController", "./controllers/users.controller");
|
||||||
|
assert_eq!(out, twice); // idempotent
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn symbol_added_to_controllers_array() {
|
||||||
|
let out = add_to_module_array(MOD, "controllers", "UsersController").unwrap();
|
||||||
|
assert!(out.contains("HomeController"));
|
||||||
|
assert!(out.contains("UsersController"));
|
||||||
|
// idempotent
|
||||||
|
let again = add_to_module_array(&out, "controllers", "UsersController").unwrap();
|
||||||
|
assert_eq!(out, again);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broken_result_is_rejected() {
|
||||||
|
// Predates create-if-absent: `providers` used to be missing entirely,
|
||||||
|
// 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!(
|
||||||
|
add_to_module_array(MOD, "providers", "X").is_none()
|
||||||
|
|| add_to_module_array(MOD, "providers", "X")
|
||||||
|
.unwrap()
|
||||||
|
.contains("providers")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extra coverage beyond the brief: this exercises the `None` path where
|
||||||
|
/// `insert_into_object_array` finds (or creates) the target but the
|
||||||
|
/// splice produces text that no longer parses clean — proving the
|
||||||
|
/// revert-on-ERROR guarantee (`parses_clean` check) is real, not just
|
||||||
|
/// theoretically reachable.
|
||||||
|
#[test]
|
||||||
|
fn revert_on_actual_parse_error() {
|
||||||
|
// A "symbol" containing stray syntax breaks the array/object/class
|
||||||
|
// once spliced in, so the edited text must fail to re-parse clean.
|
||||||
|
let out = add_to_module_array(MOD, "controllers", "X]; class Evil {");
|
||||||
|
assert!(out.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn method_inserted_before_class_close() {
|
||||||
|
let src = "export class HomeController {\n home() {}\n}\n";
|
||||||
|
let out = insert_method(src, "HomeController", " @Sse('/zen')\n zen() {}\n").unwrap();
|
||||||
|
assert!(out.contains("zen()"));
|
||||||
|
assert!(out.trim_end().ends_with('}'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn targets_module_array_not_a_decoy_before_it() {
|
||||||
|
// A decoy object literal with a `controllers:` array appears BEFORE the real @Module.
|
||||||
|
let src = r#"const decoy = { controllers: [Existing] };
|
||||||
|
|
||||||
|
@Module({ controllers: [HomeController] })
|
||||||
|
export class AppModule {}
|
||||||
|
"#;
|
||||||
|
let out = add_to_module_array(src, "controllers", "UsersController").unwrap();
|
||||||
|
// must land in the @Module array, next to HomeController...
|
||||||
|
assert!(out.contains("HomeController, UsersController"));
|
||||||
|
// ...and must NOT touch the decoy array
|
||||||
|
assert!(out.contains("controllers: [Existing] }"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn insert_method_reverts_on_parse_break() {
|
||||||
|
// a method body that makes the class re-parse fail must yield None (revert guard)
|
||||||
|
let src = "export class HomeController {\n home() {}\n}\n";
|
||||||
|
assert!(insert_method(src, "HomeController", " zen() { ]; class Evil {\n").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn insert_method_none_when_class_absent() {
|
||||||
|
let src = "export class HomeController {\n home() {}\n}\n";
|
||||||
|
assert!(insert_method(src, "NotHere", " zen() {}\n").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_import_merges_into_existing_brace() {
|
||||||
|
let src = "import { Route, Get, Html, Sse } from '@green-tea/core';\n\nexport class C {}\n";
|
||||||
|
let out = add_import(src, "Stream", "@green-tea/core");
|
||||||
|
assert!(out.contains("Stream"));
|
||||||
|
assert_eq!(out.matches("from '@green-tea/core'").count(), 1); // NO duplicate import line
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_import_merge_idempotent_when_symbol_present() {
|
||||||
|
let src = "import { Route, Sse } from '@green-tea/core';\nexport class C {}\n";
|
||||||
|
assert_eq!(add_import(src, "Sse", "@green-tea/core"), src);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_import_new_line_when_module_absent() {
|
||||||
|
let src = "export class C {}\n";
|
||||||
|
let out = add_import(src, "Sse", "@green-tea/core");
|
||||||
|
assert!(out.contains("import { Sse } from '@green-tea/core';"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
runtime = "bun"
|
||||||
@@ -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" }
|
||||||
|
}
|
||||||
@@ -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');
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "esnext",
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1 @@
|
|||||||
|
runtime = "node"
|
||||||
@@ -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" }
|
||||||
|
}
|
||||||
@@ -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');
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es2020",
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
Executable
+46
@@ -0,0 +1,46 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Tests install.sh against a local file:// fixture (no network).
|
||||||
|
set -eu
|
||||||
|
here=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
fail() { echo "FAIL: $*" >&2; exit 1; }
|
||||||
|
|
||||||
|
# derive this machine's expected triple the same way install.sh does
|
||||||
|
os=$(uname -s); arch=$(uname -m)
|
||||||
|
case "$os" in
|
||||||
|
Darwin) case "$arch" in arm64|aarch64) triple=aarch64-apple-darwin;; x86_64) triple=x86_64-apple-darwin;; esac;;
|
||||||
|
Linux) case "$arch" in x86_64|amd64) triple=x86_64-unknown-linux-musl;; esac;;
|
||||||
|
esac
|
||||||
|
[ -n "${triple:-}" ] || { echo "SKIP: unsupported test host"; exit 0; }
|
||||||
|
|
||||||
|
work=$(mktemp -d); trap 'rm -rf "$work"' EXIT
|
||||||
|
tag=v0.0.0
|
||||||
|
assetdir="$work/fixture/releases/download/$tag"
|
||||||
|
mkdir -p "$assetdir"
|
||||||
|
|
||||||
|
# build a fake release asset: a tarball containing a 'matcha' executable
|
||||||
|
printf '#!/bin/sh\necho "matcha 0.0.0-test"\n' > "$work/matcha"
|
||||||
|
chmod +x "$work/matcha"
|
||||||
|
tar -czf "$assetdir/matcha-$triple.tar.gz" -C "$work" matcha
|
||||||
|
if command -v sha256sum >/dev/null 2>&1; then
|
||||||
|
( cd "$assetdir" && sha256sum "matcha-$triple.tar.gz" > "matcha-$triple.tar.gz.sha256" )
|
||||||
|
else
|
||||||
|
( cd "$assetdir" && shasum -a 256 "matcha-$triple.tar.gz" > "matcha-$triple.tar.gz.sha256" )
|
||||||
|
fi
|
||||||
|
|
||||||
|
# --- case 1: happy path installs the binary ---
|
||||||
|
bin="$work/bin"
|
||||||
|
MATCHA_REPO_BASE="file://$work/fixture" MATCHA_VERSION="$tag" MATCHA_INSTALL_DIR="$bin" \
|
||||||
|
sh "$here/install.sh" >/dev/null 2>&1 || fail "install.sh exited non-zero on happy path"
|
||||||
|
[ -x "$bin/matcha" ] || fail "matcha not installed to $bin"
|
||||||
|
"$bin/matcha" --version >/dev/null 2>&1 || fail "installed matcha not runnable"
|
||||||
|
|
||||||
|
# --- case 2: checksum mismatch aborts and does NOT install ---
|
||||||
|
echo "deadbeef matcha-$triple.tar.gz" > "$assetdir/matcha-$triple.tar.gz.sha256"
|
||||||
|
bin2="$work/bin2"
|
||||||
|
if MATCHA_REPO_BASE="file://$work/fixture" MATCHA_VERSION="$tag" MATCHA_INSTALL_DIR="$bin2" \
|
||||||
|
sh "$here/install.sh" >/dev/null 2>&1; then
|
||||||
|
fail "install.sh should have failed on checksum mismatch"
|
||||||
|
fi
|
||||||
|
[ -e "$bin2/matcha" ] && fail "matcha must NOT be installed on checksum mismatch"
|
||||||
|
|
||||||
|
echo "PASS: test_install.sh"
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
use assert_cmd::Command;
|
||||||
|
use tempfile::tempdir;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_sse_appends_handler() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
d.path().join("src/controllers/home.controller.ts"),
|
||||||
|
"import { Route, Get } from '@green-tea/core';\n\n\
|
||||||
|
@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
|
.current_dir(d.path())
|
||||||
|
.args(["add", "sse"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
|
||||||
|
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||||
|
assert!(out.contains("@Sse("));
|
||||||
|
assert!(out.contains("import { Route, Get, Sse }") || out.contains("Sse }"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_errors_when_no_controller() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
||||||
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
|
.current_dir(d.path())
|
||||||
|
.args(["add", "sse"])
|
||||||
|
.assert()
|
||||||
|
.failure();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_sse_twice_is_idempotent() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
||||||
|
std::fs::write(d.path().join("src/controllers/home.controller.ts"),
|
||||||
|
"import { Route, Get } from '@green-tea/core';\n\n@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n").unwrap();
|
||||||
|
let run = || {
|
||||||
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
|
.current_dir(d.path())
|
||||||
|
.args(["add", "sse"])
|
||||||
|
.assert()
|
||||||
|
.success()
|
||||||
|
};
|
||||||
|
run();
|
||||||
|
run();
|
||||||
|
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||||
|
// exactly one Sse handler, exactly one @green-tea/core import line
|
||||||
|
assert_eq!(out.matches("@Sse(").count(), 1);
|
||||||
|
assert_eq!(out.matches("from '@green-tea/core'").count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_errors_when_multiple_controllers_and_writes_nothing() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
let cdir = d.path().join("src/controllers");
|
||||||
|
std::fs::create_dir_all(&cdir).unwrap();
|
||||||
|
let original = "export class X {}\n";
|
||||||
|
for n in ["a", "b"] {
|
||||||
|
std::fs::write(cdir.join(format!("{n}.controller.ts")), original).unwrap();
|
||||||
|
}
|
||||||
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
|
.current_dir(d.path())
|
||||||
|
.args(["add", "sse"])
|
||||||
|
.assert()
|
||||||
|
.failure();
|
||||||
|
// no file was modified
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(cdir.join("a.controller.ts")).unwrap(),
|
||||||
|
original
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(cdir.join("b.controller.ts")).unwrap(),
|
||||||
|
original
|
||||||
|
);
|
||||||
|
}
|
||||||
+14
-6
@@ -3,14 +3,22 @@ use predicates::str::contains;
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn help_lists_all_subcommands() {
|
fn help_lists_all_subcommands() {
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
.arg("--help").assert().success()
|
.unwrap()
|
||||||
.stdout(contains("new")).stdout(contains("run"))
|
.arg("--help")
|
||||||
.stdout(contains("create")).stdout(contains("add"));
|
.assert()
|
||||||
|
.success()
|
||||||
|
.stdout(contains("new"))
|
||||||
|
.stdout(contains("run"))
|
||||||
|
.stdout(contains("create"))
|
||||||
|
.stdout(contains("add"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn new_requires_a_name() {
|
fn new_requires_a_name() {
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
.arg("new").assert().failure(); // missing <name>
|
.unwrap()
|
||||||
|
.arg("new")
|
||||||
|
.assert()
|
||||||
|
.failure(); // missing <name>
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
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 }"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 }"));
|
||||||
|
}
|
||||||
+110
-10
@@ -1,31 +1,131 @@
|
|||||||
use assert_cmd::Command;
|
use assert_cmd::Command;
|
||||||
|
use std::process::Command as Proc;
|
||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn new_scaffolds_into_named_dir() {
|
fn new_scaffolds_into_named_dir() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["new", "my-api"]).assert().success();
|
.args(["new", "my-api"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
let root = d.path().join("my-api");
|
let root = d.path().join("my-api");
|
||||||
assert!(root.join("src/app.module.ts").exists());
|
assert!(root.join("src/app.module.ts").exists());
|
||||||
assert!(root.join("public/index.html").exists());
|
assert!(root.join("public/index.html").exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn new_refuses_existing_dir() {
|
fn new_default_runtime_is_node() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
std::fs::create_dir(d.path().join("taken")).unwrap();
|
Command::cargo_bin("matcha")
|
||||||
Command::cargo_bin("matcha").unwrap()
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["new", "taken"]).assert().failure();
|
.args(["new", "demo"])
|
||||||
|
.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("tsconfig.json").exists());
|
||||||
|
assert!(!root.join("deno.json").exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn new_with_template_url_stub_leaves_no_dir() {
|
fn new_with_deno_runtime_produces_deno_json() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["new", "demo", "--template-url", "gh:x/y"]).assert().failure();
|
.args(["new", "demo-deno", "--runtime", "deno"])
|
||||||
assert!(!d.path().join("demo").exists());
|
.assert()
|
||||||
|
.success();
|
||||||
|
let root = d.path().join("demo-deno");
|
||||||
|
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();
|
||||||
|
std::fs::create_dir(d.path().join("taken")).unwrap();
|
||||||
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
|
.current_dir(d.path())
|
||||||
|
.args(["new", "taken"])
|
||||||
|
.assert()
|
||||||
|
.failure();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user