feat(openapi): the OpenAPI document, and the paperwork the crate shipped without
`Cargo.toml` has declared `license = "MIT"` since the first release and the published crate carried no license text, so anyone vendoring the source had the claim without the grant. `LICENSE` is that text. `DCO` is the certificate the README has been requiring a sign-off against without shipping, and `CONTRIBUTING.md` says how — including that GitHub is a mirror of `main` and tags, so a pull request there is carried upstream by a maintainer rather than merged, which would put the two forges out of sync. `CHANGELOG.md` reconstructs 26.7.0 and 26.8.0-beta.0 from their tags. The CLI ships on its own version line, so the header says what that does and does not mean about the core version a scaffold is pinned to, and each entry says when that pin moved. `matcha openapi` prints core's structural OpenAPI 3.1 for the route table — `--title`, `--api-version`, `--out`. It reuses the entry resolution and the generated-script runner that `graph` and `explain` already had, so it is the same `app.ready()` that resolves the graph without booting providers. Structural is the honest word: paths, methods and parameters come from the decorators, and nothing invents a response schema. The loose end from the capability table is closed. `cli.rs` still carried its own copies of the `create` kinds and the `add` capabilities, so adding either meant editing two files that could disagree — a value the parser accepts and the dispatcher rejects. Both now read the list from the module that owns it, and the three `create` piece kinds became rows in a table rather than near-identical match arms, which also retires a `too_many_arguments` allow. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
12 files changed
+542
-47
No files matched your search
+150
@@ -0,0 +1,150 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to `matcha-cli` are documented here.
|
||||
|
||||
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
matcha uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, matching
|
||||
green-tea's convention. **The CLI ships on its own version line**: `matcha` 26.8 does not
|
||||
mean `@green-tea/core` 26.8, and the two release independently. The core version a scaffold
|
||||
is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says when it moved.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **`matcha graph` and `matcha explain <pattern>`.** green-tea derives execution order from
|
||||
what each node declares it `needs` and `provides`, which makes the graph a real artifact
|
||||
rather than a diagram someone drew — and the CLI could not draw any of it, though
|
||||
`toMermaid`, `toDOT`, `graph` and `explain` had been exported all along. `graph` prints
|
||||
Mermaid, Graphviz DOT or the raw `GraphView` (`--format`, `--out`); `explain` prints one
|
||||
route's chain in execution order with each node's needs and provides.
|
||||
|
||||
Both import the app and call `app.ready()`, which resolves the graph and is documented as
|
||||
deliberately *not* running provider factories — asking for a diagram must not open your
|
||||
database connections. `explain` takes the route pattern as declared (`/users/:id`, not
|
||||
`/users/42`), and a miss lists the patterns that are registered.
|
||||
|
||||
- **`matcha doctor`** — the misconfigurations that fail confusingly rather than loudly:
|
||||
`experimentalDecorators` missing, which turns every `@Route` into a syntax error that
|
||||
blames the decorator; a core pin that cannot resolve, or that does not match what is
|
||||
installed; an entry that does not export `app`; and `@Ws` or multipart routes whose
|
||||
lazy-loaded peer dependency is absent, which compile and then fail at the first request.
|
||||
Every check is a file read — no runtime spawned, nothing fetched — so it works before the
|
||||
project installs. Exits non-zero on a failure.
|
||||
|
||||
- **`matcha new --runtime edge`** — a Cloudflare Worker: `wrangler.toml` with
|
||||
`nodejs_compat`, `edgeHandler(app)` as the default export, and wrangler's `[assets]`
|
||||
serving `./public`, so `/` is the same page as on the other three runtimes and `/zen` the
|
||||
same stream from the worker. `matcha run` is `wrangler dev`, which boots real workerd, so
|
||||
edge stops being a deploy-only target. Detection puts `wrangler.toml` ahead of
|
||||
`package.json`, since an edge project has both.
|
||||
|
||||
Core is installed from **JSR** on this runtime alone. The npm ESM build carries tsup's
|
||||
`createRequire(import.meta.url)` banner at module scope and `import.meta.url` is undefined
|
||||
on workerd, so `@green-tea/core/edge` from npm throws before any of its own code runs
|
||||
([green-tea#93](https://github.com/Expressive-Tea/green-tea/issues/93)). The scaffolded
|
||||
`.npmrc` says so; it and the alias can both go once that is fixed.
|
||||
|
||||
- **`matcha add ws` and `matcha add upload`**, and **`--controller <path>`**. `add` used to
|
||||
refuse outright when a project had more than one controller; it still declines to guess,
|
||||
but it lists the candidates and the flag picks. Both new capabilities name the optional
|
||||
peer dependency they need on success — core lazy-requires `ws` and `busboy`, so a missing
|
||||
one is an error at the first request rather than at boot, and the moment to mention it is
|
||||
when the handler is written.
|
||||
|
||||
- **`scripts/starter-smoke.sh`** — scaffolds, installs, type-checks, boots, curls `/` and the
|
||||
`/zen` stream, introspects, and adds every capability, per runtime. CI runs it on a matrix
|
||||
of all four, and a weekly job fails when the scaffold's core pin falls behind the `beta`
|
||||
dist-tag.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The scaffold composes its graph in `src/app.ts`.** `src/main.ts` now holds only the
|
||||
runtime's serve call and imports the app from it. The split is what lets `graph`, `explain`
|
||||
and `doctor` read an application without binding a port. `create module` follows, preferring
|
||||
`src/app.ts` and falling back to `src/main.ts` so projects scaffolded before the split keep
|
||||
working.
|
||||
|
||||
- **`add sse` generates a resumable stream.** The stub predates green-tea 26.9: it yielded
|
||||
bare values, so an `EventSource` reconnect restarted the iterable from its beginning and
|
||||
lost the gap in silence. It now tags each event with `sse(data, { id })` and reads
|
||||
`@header('last-event-id')` to resume from it.
|
||||
|
||||
- **`add buffer` demonstrates `@Transformer`.** It used to return `Buffer.from('hello')`,
|
||||
which is not what the capability's name means — "buffer" is the *transport*, the whole
|
||||
response at once — and never worked: `TransformerFn` returns `body: string` and the default
|
||||
`JsonTransformer` is `JSON.stringify`, so the route answered
|
||||
`{"type":"Buffer","data":[104,...]}`. It now shapes a `text/csv` response through the
|
||||
extension point that actually governs one.
|
||||
|
||||
- **Types in a decorated signature are imported with `import type`.** `wire`'s import
|
||||
handling became type-aware in both directions: merging a value symbol into an
|
||||
`import type` line would erase the decorator at runtime, and merging a type into a value
|
||||
line is TS1272 under `isolatedModules` with `emitDecoratorMetadata` — which node's and
|
||||
bun's `tsc` accept and Deno rejects, so the same generated handler compiled on two runtimes
|
||||
and failed on the third.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The scaffold no longer pins `@green-tea/core` two releases behind.** Every runtime
|
||||
overlay carried `^26.7.0-beta.0`. Core is prerelease-only, and npm's semver excludes a
|
||||
prerelease from any range whose comparators carry a different `major.minor.patch` — so that
|
||||
caret was not a loose pin but a pin to the oldest matching prerelease that nothing could
|
||||
move off. Every project `matcha new` produced since July installed 26.7.0-beta.0 and could
|
||||
not upgrade to it: no logger, no request budget, no resumable `@Sse` id, and none of the
|
||||
crashes 26.9 fixed. The pin is exact now, lives in one `CORE_VERSION` constant, and the
|
||||
scaffold is on **26.9.0-beta.1**.
|
||||
|
||||
- **The Deno scaffold resolves core through JSR** rather than `npm:`. JSR is core's native
|
||||
path for Deno and the one green-tea 26.9 repaired; the npm build's `createRequire` banner
|
||||
never existed there, which is what used to break `@Html` and multipart at boot.
|
||||
|
||||
- **The bun scaffold type-checks.** Its `tsconfig.json` declared no Bun types, so `Bun.serve`
|
||||
was `TS2868: Cannot find name 'Bun'` — meaning `tsc --noEmit`, and therefore
|
||||
`matcha create --check`, failed on every bun project the CLI has ever scaffolded.
|
||||
|
||||
- **`MIT` is a file, not just a manifest field.** `Cargo.toml` declared `license = "MIT"` and
|
||||
the published crate carried no license text. Added along with the `DCO` the README has been
|
||||
requiring sign-off against, and a `CONTRIBUTING.md` saying how.
|
||||
|
||||
## [26.8.0-beta.0] - 2026-08-07
|
||||
|
||||
### Added
|
||||
|
||||
- Publishing to crates.io via OIDC Trusted Publishing — no token in CI.
|
||||
|
||||
### Changed
|
||||
|
||||
- The crate is `matcha-cli` on crates.io (the name `matcha` was taken); the installed binary
|
||||
stays `matcha`, so `cargo install matcha-cli` still gives you `matcha`. Two-forge CI/CD:
|
||||
Gitea is origin, GitHub is the public mirror that release tags are promoted to.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The README's install paths point at hosts that actually resolve.
|
||||
|
||||
## [26.7.0] - 2026-07-13
|
||||
|
||||
First tagged release. A single native binary, no JS runtime needed to install it.
|
||||
|
||||
### Added
|
||||
|
||||
- **`matcha new`** — scaffolds from an embedded starter that is alive on first boot: it serves
|
||||
an `index.html` and streams a rotating zen message over `@Sse('/zen')`. `--runtime` picks
|
||||
node (the default), deno or bun through a shared template plus a per-runtime overlay;
|
||||
`--template-url` scaffolds from any git template, with a `gh:owner/repo` shorthand.
|
||||
- **`matcha run`** — detects the runtime and spawns it in watch mode. Precedence, first match
|
||||
wins: `matcha.toml`, then `deno.json`, then a bun lockfile, then `package.json`.
|
||||
- **`matcha create <controller|step|provider|module>`** — generates the piece and wires it in
|
||||
with tree-sitter: imports merge into an existing brace rather than adding a second binding
|
||||
for the same module, and an edit that would break the file's syntax reverts itself instead
|
||||
of being written. `--check` type-checks afterwards with the project's own runtime.
|
||||
- **`matcha add <sse|stream|buffer>`** — appends a capability handler to the controller,
|
||||
idempotent per capability.
|
||||
- **A `curl | sh` installer** with sha256 verification, and cross-platform binaries attached
|
||||
to each release.
|
||||
|
||||
[Unreleased]: https://github.com/Expressive-Tea/matcha/compare/v26.8.0-beta.0...HEAD
|
||||
[26.8.0-beta.0]: https://github.com/Expressive-Tea/matcha/compare/v26.7.0...v26.8.0-beta.0
|
||||
[26.7.0]: https://github.com/Expressive-Tea/matcha/releases/tag/v26.7.0
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
# Contributing to matcha
|
||||
|
||||
matcha is the [green-tea](https://github.com/Expressive-Tea/green-tea) CLI. It is open
|
||||
source, but nobody pushes directly — changes land through reviewed pull requests with a
|
||||
**DCO sign-off**.
|
||||
|
||||
## Where to send your changes
|
||||
|
||||
Development happens on a private Gitea instance. **GitHub is a downstream mirror**: the
|
||||
promote workflow pushes `main` and version tags to it and nothing else, so there is no
|
||||
`develop` there and no long-lived branch for contributions.
|
||||
|
||||
**From GitHub:** open your pull request against `main` and say in the description that it
|
||||
is a contribution rather than a release. A maintainer carries the commits upstream into
|
||||
Gitea's `develop` with your authorship and your sign-off intact, and the change reaches
|
||||
GitHub again through the normal promotion. Nothing is merged into the GitHub `main`
|
||||
directly — that would put the two forges out of sync and break the next release push.
|
||||
|
||||
**From Gitea, if you have access:** follow the branch model below.
|
||||
|
||||
## Developer Certificate of Origin (DCO)
|
||||
|
||||
We use the [Developer Certificate of Origin](./DCO) instead of a CLA — a per-commit
|
||||
affirmation that you have the right to submit your work under this project's license. No
|
||||
copyright assignment, no paperwork.
|
||||
|
||||
**Every commit must be signed off:**
|
||||
|
||||
```bash
|
||||
git commit -s -m "fix(wire): keep a type import out of the value brace"
|
||||
```
|
||||
|
||||
That appends `Signed-off-by: Your Name <your@email>`, which has to match your commit
|
||||
author. Forgot it on the last commit:
|
||||
|
||||
```bash
|
||||
git commit --amend -s
|
||||
git push --force-with-lease
|
||||
```
|
||||
|
||||
## Working with AI assistance
|
||||
|
||||
Use one if it helps. There is no permission to ask for and nothing to declare.
|
||||
|
||||
What we do ask is that you read what it hands you before it becomes a pull request. Every
|
||||
line here is reviewed by a person, by hand, and usually that person is one person. A diff
|
||||
its own author has not read moves that work onto them and turns review into proofreading,
|
||||
which is the thing review is worst at.
|
||||
|
||||
**What assistants tend to get wrong in this repository in particular:**
|
||||
|
||||
- **They test the CLI instead of its output.** `cargo test` proves matcha writes the files
|
||||
it means to write. It cannot prove those files describe a project that runs. That gap is
|
||||
why the templates sat two core releases behind for two months with a green build.
|
||||
`scripts/starter-smoke.sh` is the check that closes it; run it for the runtime you touched.
|
||||
- **They write for Node and assume the rest follows.** matcha scaffolds for node, deno, bun
|
||||
and the edge, and the four differ in ways that bite. A generated handler that compiles
|
||||
under `tsc` can still be TS1272 under Deno's `isolatedModules` + `emitDecoratorMetadata`.
|
||||
- **They reach for a crate.** matcha has four dependencies and reads TOML and JSON with
|
||||
line scans on purpose. A new dependency for a value that is always written one per line
|
||||
is not a trade worth making.
|
||||
- **They pin `@green-tea/core` with a caret.** Core is prerelease-only, and npm excludes a
|
||||
prerelease from any range whose comparators carry a different `major.minor.patch`. A
|
||||
caret there is a pin to the oldest matching prerelease that nothing can move off. There
|
||||
is a test for this.
|
||||
- **They delete comments they read as redundant.** A comment here usually carries reasoning
|
||||
the code cannot show on its own — why a marker is a route literal rather than a decorator
|
||||
name, why the edge scaffold installs from JSR.
|
||||
|
||||
**Where you are unsure, say so** — not as a disclosure, as a pointer. "I did not run the
|
||||
bun leg" tells a reviewer where to spend their attention.
|
||||
|
||||
None of this changes the sign-off. `Signed-off-by` says you have the right to submit the
|
||||
work under this project's license, and that stays true however the text was produced.
|
||||
|
||||
## Branch model (GitFlow)
|
||||
|
||||
- `main` — production-ready, protected. No direct pushes. Tags are cut here.
|
||||
- `develop` — active development, protected. Feature branches merge here.
|
||||
- `feature/<name>` — branch from `develop`.
|
||||
- `hotfix/<name>` — branch from `main`.
|
||||
- `release/<version>` — release stabilization.
|
||||
|
||||
## Commits
|
||||
|
||||
Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`,
|
||||
`chore:`, `docs:`, `test:`, `refactor:`, `ci:`. Focus the message on the *why*. Do not add
|
||||
AI co-authoring attribution.
|
||||
|
||||
Anything user-visible gets a `CHANGELOG.md` entry under `## [Unreleased]`, in the same
|
||||
voice as the entries around it: what changed, and what it was before.
|
||||
|
||||
## Local setup
|
||||
|
||||
A stable Rust toolchain is all that is required to build and test the CLI:
|
||||
|
||||
```bash
|
||||
cargo build
|
||||
cargo test
|
||||
```
|
||||
|
||||
The starter smoke needs the runtime it exercises — node, deno, bun or wrangler (which
|
||||
`npm install` brings in for the edge scaffold). You are not expected to install all four to
|
||||
fix a typo; you are expected to run the one your change touches, and to say which in the
|
||||
pull request.
|
||||
|
||||
```bash
|
||||
cargo build
|
||||
scripts/starter-smoke.sh node # also: deno, bun, edge
|
||||
```
|
||||
|
||||
It scaffolds into a temp directory, installs, type-checks, boots, curls `/` and the `/zen`
|
||||
stream, runs `matcha graph`/`explain`, then adds every `matcha add` capability and
|
||||
type-checks them together. It picks a random high port, so it does not collide with a
|
||||
server you already have running; `PORT=4567 scripts/starter-smoke.sh node` overrides.
|
||||
|
||||
## Before you open a pull request
|
||||
|
||||
Run what CI runs:
|
||||
|
||||
```bash
|
||||
cargo fmt --check
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
cargo test --locked
|
||||
scripts/starter-smoke.sh <the runtime you touched>
|
||||
```
|
||||
|
||||
CI runs the smoke for all four runtimes on a matrix, plus a weekly `core-freshness` job
|
||||
that fails when `CORE_VERSION` in `src/template.rs` falls behind core's `beta` dist-tag.
|
||||
|
||||
**Non-trivial logic leaves a check behind.** Not a suite — the smallest thing that fails if
|
||||
the logic breaks. A generator gets a test that the generated code carries what it must; a
|
||||
parser gets a test for the case that motivated it.
|
||||
|
||||
## Reporting issues
|
||||
|
||||
Bugs and feature requests go to
|
||||
[GitHub issues](https://github.com/Expressive-Tea/matcha/issues). A report that says what
|
||||
you ran, what you expected, and what happened — with the runtime and the matcha version
|
||||
from `matcha --version` — is worth several that do not.
|
||||
|
||||
Defects in the framework itself belong in the
|
||||
[green-tea repository](https://github.com/Expressive-Tea/green-tea/issues), not here.
|
||||
|
||||
## Code of conduct
|
||||
|
||||
Be decent. Assume good faith, keep criticism about the code, and take the hint when someone
|
||||
asks you to drop it.
|
||||
@@ -0,0 +1,37 @@
|
||||
Developer Certificate of Origin
|
||||
Version 1.1
|
||||
|
||||
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
|
||||
1 Letterman Drive
|
||||
Suite D4700
|
||||
San Francisco, CA, 94129
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this
|
||||
license document, but changing it is not allowed.
|
||||
|
||||
|
||||
Developer's Certificate of Origin 1.1
|
||||
|
||||
By making a contribution to this project, I certify that:
|
||||
|
||||
(a) The contribution was created in whole or in part by me and I
|
||||
have the right to submit it under the open source license
|
||||
indicated in the file; or
|
||||
|
||||
(b) The contribution is based upon previous work that, to the best
|
||||
of my knowledge, is covered under an appropriate open source
|
||||
license and I have the right under that license to submit that
|
||||
work with modifications, whether created in whole or in part
|
||||
by me, under the same open source license (unless I am
|
||||
permitted to submit under a different license), as indicated
|
||||
in the file; or
|
||||
|
||||
(c) The contribution was provided directly to me by some other
|
||||
person who certified (a), (b) or (c) and I have not modified
|
||||
it.
|
||||
|
||||
(d) I understand and agree that this project and the contribution
|
||||
are public and that a record of the contribution (including all
|
||||
personal information I submit with it, including my sign-off) is
|
||||
maintained indefinitely and may be redistributed consistent with
|
||||
this project or the open source license(s) involved.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 green-tea contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -39,6 +39,7 @@ matcha create controller Users # generate + auto-wire into @Module
|
||||
matcha add sse # add a capability to your controller
|
||||
matcha graph # draw the dependency graph
|
||||
matcha explain /users/:id # one route's chain, in execution order
|
||||
matcha openapi # structural OpenAPI 3.1 for the route table
|
||||
matcha doctor # check the project for confusing misconfigurations
|
||||
```
|
||||
|
||||
@@ -71,8 +72,13 @@ matcha graph --format dot # Graphviz
|
||||
matcha graph --format json # the raw GraphView
|
||||
matcha graph --out docs/graph.mmd # to a file instead of stdout
|
||||
matcha explain /users/:id # providers → steps → handler, with needs/provides
|
||||
matcha openapi --title "My API" --api-version 1.0.0 --out openapi.json
|
||||
```
|
||||
|
||||
`openapi` is *structural*: green-tea derives paths, methods and parameters from
|
||||
the decorators, which is everything the graph knows. It does not invent response
|
||||
schemas, so the document describes the surface rather than the payloads.
|
||||
|
||||
Both import `src/app.ts` (override with `--entry`) and call `app.ready()`, which
|
||||
resolves the graph and deliberately does **not** run provider factories — asking
|
||||
for a diagram will not open your database connections. Your dependencies have to
|
||||
|
||||
@@ -86,7 +86,8 @@ echo "▸ matcha graph"
|
||||
"$MATCHA" graph | grep -q '^flowchart LR' || { echo "graph produced no mermaid"; exit 1; }
|
||||
"$MATCHA" graph --format dot | grep -q '^digraph green_tea' || { echo "graph produced no DOT"; exit 1; }
|
||||
"$MATCHA" explain /zen | grep -q '\[sse\]' || { echo "explain did not report the sse route"; exit 1; }
|
||||
echo "✓ graph and explain resolve"
|
||||
"$MATCHA" openapi | grep -q '"openapi": "3.1.0"' || { echo "openapi produced no document"; exit 1; }
|
||||
echo "✓ graph, explain and openapi resolve"
|
||||
|
||||
# Every `matcha add` capability, spliced into one controller and type-checked
|
||||
# together. The stubs name core's real surface — `sse()` with an id, `@Ws` with
|
||||
|
||||
+18
-2
@@ -1,5 +1,8 @@
|
||||
use clap::builder::PossibleValuesParser;
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use crate::{cmd_add, cmd_create};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "matcha", version, about = "green-tea CLI")]
|
||||
pub struct Cli {
|
||||
@@ -21,7 +24,7 @@ pub enum Command {
|
||||
Run,
|
||||
/// Generate a piece and auto-wire it into the module
|
||||
Create {
|
||||
#[arg(value_parser = ["module", "controller", "step", "provider"])]
|
||||
#[arg(value_parser = PossibleValuesParser::new(cmd_create::kinds()))]
|
||||
kind: String,
|
||||
name: String,
|
||||
#[arg(long)]
|
||||
@@ -40,6 +43,19 @@ pub enum Command {
|
||||
#[arg(long)]
|
||||
out: Option<String>,
|
||||
},
|
||||
/// Print the structural OpenAPI 3.1 document for the route table
|
||||
Openapi {
|
||||
/// API title (default: core's own)
|
||||
#[arg(long)]
|
||||
title: Option<String>,
|
||||
/// API version (default: core's own)
|
||||
#[arg(long)]
|
||||
api_version: Option<String>,
|
||||
#[arg(long)]
|
||||
entry: Option<String>,
|
||||
#[arg(long)]
|
||||
out: Option<String>,
|
||||
},
|
||||
/// Explain one route's chain, in execution order
|
||||
Explain {
|
||||
/// The route pattern as declared, e.g. /users/:id
|
||||
@@ -51,7 +67,7 @@ pub enum Command {
|
||||
},
|
||||
/// Add a capability to a controller
|
||||
Add {
|
||||
#[arg(value_parser = ["sse", "stream", "buffer", "ws", "upload"])]
|
||||
#[arg(value_parser = PossibleValuesParser::new(cmd_add::names()))]
|
||||
capability: String,
|
||||
/// Which controller to edit (default: the only one in src/controllers)
|
||||
#[arg(long)]
|
||||
|
||||
+68
-43
@@ -7,61 +7,86 @@ use std::path::Path;
|
||||
|
||||
use crate::{entry, wire};
|
||||
|
||||
/// A piece that lives inside a module: a file under `src/<subdir>/` plus an
|
||||
/// entry in one of `@Module`'s arrays.
|
||||
///
|
||||
/// `module` is not one of these — it is registered in the `createApp` call
|
||||
/// rather than in a module array — so it stays a case of its own below.
|
||||
struct Piece {
|
||||
/// Name as typed on the command line.
|
||||
kind: &'static str,
|
||||
/// Directory under `src/`, and the `@Module` key, which are the same word
|
||||
/// for all three.
|
||||
subdir: &'static str,
|
||||
/// Filename infix: `users.controller.ts`.
|
||||
ext: &'static str,
|
||||
/// Appended to the given name to form the exported symbol.
|
||||
suffix: &'static str,
|
||||
stub: fn(&str) -> String,
|
||||
}
|
||||
|
||||
const PIECES: &[Piece] = &[
|
||||
Piece {
|
||||
kind: "controller",
|
||||
subdir: "controllers",
|
||||
ext: "controller",
|
||||
suffix: "Controller",
|
||||
stub: controller_stub,
|
||||
},
|
||||
Piece {
|
||||
kind: "step",
|
||||
subdir: "steps",
|
||||
ext: "step",
|
||||
suffix: "Step",
|
||||
stub: step_stub,
|
||||
},
|
||||
Piece {
|
||||
kind: "provider",
|
||||
subdir: "providers",
|
||||
ext: "provider",
|
||||
suffix: "Provider",
|
||||
stub: provider_stub,
|
||||
},
|
||||
];
|
||||
|
||||
/// Every `create` kind, for clap's `value_parser` and for error messages. One
|
||||
/// list, so a new kind cannot be accepted by the parser and rejected by `run`
|
||||
/// (or the reverse).
|
||||
pub fn kinds() -> Vec<&'static str> {
|
||||
std::iter::once("module")
|
||||
.chain(PIECES.iter().map(|p| p.kind))
|
||||
.collect()
|
||||
}
|
||||
|
||||
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(
|
||||
if kind == "module" {
|
||||
return create_module(name, check);
|
||||
}
|
||||
match PIECES.iter().find(|p| p.kind == kind) {
|
||||
Some(piece) => create_piece(name, check, piece),
|
||||
None => Err(Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("unknown kind {other}"),
|
||||
format!("unknown kind {kind} (try: {})", kinds().join(", ")),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
/// in `src/app.module.ts`. Emit-only + hint on failure.
|
||||
fn create_piece(name: &str, check: bool, piece: &Piece) -> std::io::Result<()> {
|
||||
let Piece {
|
||||
subdir,
|
||||
ext,
|
||||
suffix,
|
||||
..
|
||||
} = *piece;
|
||||
let module_key = subdir;
|
||||
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)?;
|
||||
std::fs::write(&file, (piece.stub)(name))?;
|
||||
println!("✓ {}", file.display());
|
||||
|
||||
let symbol = format!("{name}{suffix}");
|
||||
|
||||
@@ -81,6 +81,42 @@ console.log(lines.join('\n'));"#
|
||||
emit(dir, entry_override, out, &body)
|
||||
}
|
||||
|
||||
/// `matcha openapi` — the structural OpenAPI 3.1 document for the route table.
|
||||
///
|
||||
/// Structural is the honest word for it: green-tea derives paths, methods and
|
||||
/// parameters from the decorators, which is everything the graph knows. It does
|
||||
/// not invent response schemas, so what comes out describes the surface rather
|
||||
/// than the payloads.
|
||||
pub fn openapi(
|
||||
dir: &Path,
|
||||
title: Option<&str>,
|
||||
version: Option<&str>,
|
||||
entry_override: Option<&str>,
|
||||
out: Option<&str>,
|
||||
) -> std::io::Result<()> {
|
||||
// `app.openapi()` takes an optional info object; passing nothing lets core
|
||||
// apply its own defaults rather than having the CLI invent a title.
|
||||
let info = match (title, version) {
|
||||
(None, None) => String::new(),
|
||||
(t, v) => {
|
||||
let mut fields = Vec::new();
|
||||
if let Some(t) = t {
|
||||
fields.push(format!("title: {}", js_string(t)));
|
||||
}
|
||||
if let Some(v) = v {
|
||||
fields.push(format!("version: {}", js_string(v)));
|
||||
}
|
||||
format!("{{ {} }}", fields.join(", "))
|
||||
}
|
||||
};
|
||||
emit(
|
||||
dir,
|
||||
entry_override,
|
||||
out,
|
||||
&format!("console.log(JSON.stringify(app.openapi({info}), null, 2));"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves the entry, generates the script around `body`, runs it under the
|
||||
/// detected runtime, and routes its stdout to a file or to ours.
|
||||
fn emit(
|
||||
|
||||
+17
@@ -56,6 +56,23 @@ fn main() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Openapi {
|
||||
title,
|
||||
api_version,
|
||||
entry,
|
||||
out,
|
||||
} => {
|
||||
if let Err(e) = cmd_graph::openapi(
|
||||
std::path::Path::new("."),
|
||||
title.as_deref(),
|
||||
api_version.as_deref(),
|
||||
entry.as_deref(),
|
||||
out.as_deref(),
|
||||
) {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Explain { route, entry, out } => {
|
||||
if let Err(e) = cmd_graph::explain(
|
||||
std::path::Path::new("."),
|
||||
|
||||
+24
-1
@@ -13,7 +13,30 @@ fn help_lists_all_subcommands() {
|
||||
.stdout(contains("create"))
|
||||
.stdout(contains("add"))
|
||||
.stdout(contains("graph"))
|
||||
.stdout(contains("explain"));
|
||||
.stdout(contains("explain"))
|
||||
.stdout(contains("openapi"))
|
||||
.stdout(contains("doctor"));
|
||||
}
|
||||
|
||||
/// clap's accepted values and the values `run` dispatches on come from one list
|
||||
/// per command now. This is what proves the wiring reached clap — a regression
|
||||
/// would take the parser and the dispatcher out of step, which shows up as a
|
||||
/// value the CLI accepts and then refuses.
|
||||
#[test]
|
||||
fn create_and_add_advertise_every_value_they_accept() {
|
||||
for (command, values) in [
|
||||
("create", vec!["module", "controller", "step", "provider"]),
|
||||
("add", vec!["sse", "stream", "buffer", "ws", "upload"]),
|
||||
] {
|
||||
let mut assertion = Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.args([command, "--help"])
|
||||
.assert()
|
||||
.success();
|
||||
for value in values {
|
||||
assertion = assertion.stdout(contains(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -58,3 +58,18 @@ fn graph_rejects_an_unknown_format() {
|
||||
.assert()
|
||||
.failure();
|
||||
}
|
||||
|
||||
/// openapi shares graph's entry resolution, so it shares its failure modes —
|
||||
/// including the one that has to name the fix.
|
||||
#[test]
|
||||
fn openapi_without_an_entry_says_what_is_missing() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::write(d.path().join("package.json"), "{}").unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.arg("openapi")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("--entry"));
|
||||
}
|
||||
Reference in new issue
Block a user