fix(add): merge imports into existing brace + capability idempotency; fmt
- wire::add_import now merges a new symbol into an already-present
`import { ... } from '<from>';` brace instead of appending a second,
colliding import line for the same module (a duplicate ESM binding
is a hard SyntaxError/TS2300, not a harmless dupe as previously
assumed). Falls back to appending a new line when the module isn't
imported yet, or if the brace-merge edit fails the parses_clean
guard.
- cmd_add::run gains a capability-level idempotency guard, keyed on
each capability's unique route-path literal, so `matcha add <cap>`
run twice no longer appends a duplicate handler + route.
- cargo fmt --all across the crate; drop the stale #[allow(dead_code)]
on wire::parses_clean now that it's demonstrably live.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
1 parent
65ecba05d1
commit
2f9b656692
10 files changed
+329
-79
No files matched your search
+21
-7
@@ -1,18 +1,23 @@
|
|||||||
use std::path::Path;
|
|
||||||
use crate::runtime::{self, Runtime};
|
use crate::runtime::{self, Runtime};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
fn check_command(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
fn check_command(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
||||||
match rt {
|
match rt {
|
||||||
Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]),
|
Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]),
|
||||||
Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]),
|
Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]),
|
||||||
Runtime::Node => ("npx", vec!["tsc", "--noEmit"]),
|
Runtime::Node => ("npx", vec!["tsc", "--noEmit"]),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(dir: &Path) -> std::io::Result<bool> {
|
pub fn run(dir: &Path) -> std::io::Result<bool> {
|
||||||
let Some(rt) = runtime::detect(dir) else { return Ok(true) }; // nothing to check against
|
let Some(rt) = runtime::detect(dir) else {
|
||||||
|
return Ok(true);
|
||||||
|
}; // nothing to check against
|
||||||
let (prog, args) = check_command(rt);
|
let (prog, args) = check_command(rt);
|
||||||
let status = std::process::Command::new(prog).args(&args).current_dir(dir).status()?;
|
let status = std::process::Command::new(prog)
|
||||||
|
.args(&args)
|
||||||
|
.current_dir(dir)
|
||||||
|
.status()?;
|
||||||
Ok(status.success())
|
Ok(status.success())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,16 +28,25 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn deno_check_cmd() {
|
fn deno_check_cmd() {
|
||||||
assert_eq!(check_command(Runtime::Deno), ("deno", vec!["check", "src/app.module.ts"]));
|
assert_eq!(
|
||||||
|
check_command(Runtime::Deno),
|
||||||
|
("deno", vec!["check", "src/app.module.ts"])
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn node_uses_tsc_noemit() {
|
fn node_uses_tsc_noemit() {
|
||||||
assert_eq!(check_command(Runtime::Node), ("npx", vec!["tsc", "--noEmit"]));
|
assert_eq!(
|
||||||
|
check_command(Runtime::Node),
|
||||||
|
("npx", vec!["tsc", "--noEmit"])
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bun_uses_bunx_tsc_noemit() {
|
fn bun_uses_bunx_tsc_noemit() {
|
||||||
assert_eq!(check_command(Runtime::Bun), ("bunx", vec!["tsc", "--noEmit"]));
|
assert_eq!(
|
||||||
|
check_command(Runtime::Bun),
|
||||||
|
("bunx", vec!["tsc", "--noEmit"])
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+34
-12
@@ -8,21 +8,31 @@ use std::path::PathBuf;
|
|||||||
|
|
||||||
use crate::wire;
|
use crate::wire;
|
||||||
|
|
||||||
/// Returns `(decorator symbol, method source)` for a known capability, or
|
/// Returns `(decorator symbol, method source, dedup marker)` for a known
|
||||||
/// `None` for an unrecognized one.
|
/// capability, or `None` for an unrecognized one.
|
||||||
fn handler(cap: &str) -> Option<(&'static str, String)> {
|
///
|
||||||
|
/// 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 {
|
match cap {
|
||||||
"sse" => Some((
|
"sse" => Some((
|
||||||
"Sse",
|
"Sse",
|
||||||
"\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(),
|
"\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(),
|
||||||
|
"'/events'",
|
||||||
)),
|
)),
|
||||||
"stream" => Some((
|
"stream" => Some((
|
||||||
"Stream",
|
"Stream",
|
||||||
"\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(),
|
"\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(),
|
||||||
|
"'/stream'",
|
||||||
)),
|
)),
|
||||||
"buffer" => Some((
|
"buffer" => Some((
|
||||||
"Get",
|
"Get",
|
||||||
"\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(),
|
"\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(),
|
||||||
|
"'/data'",
|
||||||
)),
|
)),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
@@ -38,8 +48,13 @@ fn only_controller() -> std::io::Result<PathBuf> {
|
|||||||
.collect();
|
.collect();
|
||||||
match hits.len() {
|
match hits.len() {
|
||||||
1 => Ok(hits.pop().unwrap()),
|
1 => Ok(hits.pop().unwrap()),
|
||||||
0 => Err(Error::new(ErrorKind::NotFound, "no *.controller.ts in src/controllers")),
|
0 => Err(Error::new(
|
||||||
_ => Err(Error::other("multiple controllers; specify which (not yet supported)")),
|
ErrorKind::NotFound,
|
||||||
|
"no *.controller.ts in src/controllers",
|
||||||
|
)),
|
||||||
|
_ => Err(Error::other(
|
||||||
|
"multiple controllers; specify which (not yet supported)",
|
||||||
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,23 +69,30 @@ fn class_name(src: &str) -> Option<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(cap: &str) -> std::io::Result<()> {
|
pub fn run(cap: &str) -> std::io::Result<()> {
|
||||||
let (decorator, method) = handler(cap)
|
let (decorator, method, marker) = handler(cap)
|
||||||
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("unknown capability {cap}")))?;
|
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("unknown capability {cap}")))?;
|
||||||
let path = only_controller()?;
|
let path = only_controller()?;
|
||||||
let src = std::fs::read_to_string(&path)?;
|
let src = std::fs::read_to_string(&path)?;
|
||||||
let class = class_name(&src).ok_or_else(|| Error::other("no exported class found"))?;
|
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");
|
let with_import = wire::add_import(&src, decorator, "@green-tea/core");
|
||||||
// add_import above assumes a fresh import line; if '@green-tea/core' is
|
|
||||||
// already imported under a shared brace, we still append a second import
|
|
||||||
// line for the new symbol — a duplicate named import is legal TS and tsc
|
|
||||||
// dedups at type level. Merging into the existing brace is deferred past
|
|
||||||
// v1; not worth tree-sitter surgery now.
|
|
||||||
match wire::insert_method(&with_import, &class, &method) {
|
match wire::insert_method(&with_import, &class, &method) {
|
||||||
Some(out) => {
|
Some(out) => {
|
||||||
std::fs::write(&path, out)?;
|
std::fs::write(&path, out)?;
|
||||||
println!("✓ added @{decorator} to {class}");
|
println!("✓ added @{decorator} to {class}");
|
||||||
}
|
}
|
||||||
None => println!("→ could not edit {}; add @{decorator} handler manually", path.display()),
|
None => println!(
|
||||||
|
"→ could not edit {}; add @{decorator} handler manually",
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
+13
-7
@@ -13,24 +13,30 @@ use crate::wire;
|
|||||||
|
|
||||||
fn controller_stub(name: &str) -> String {
|
fn controller_stub(name: &str) -> String {
|
||||||
format!(
|
format!(
|
||||||
"import {{ Route, Get }} from '@green-tea/core';\n\n\
|
"import {{ Route, Get }} from '@green-tea/core';\n\n\
|
||||||
@Route('/{lower}')\nexport class {name}Controller {{\n \
|
@Route('/{lower}')\nexport class {name}Controller {{\n \
|
||||||
@Get('/')\n list() {{\n return [];\n }}\n}}\n",
|
@Get('/')\n list() {{\n return [];\n }}\n}}\n",
|
||||||
lower = name.to_lowercase(), name = name)
|
lower = name.to_lowercase(),
|
||||||
|
name = name
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
|
pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
|
||||||
match kind {
|
match kind {
|
||||||
"controller" => create_controller(name, check),
|
"controller" => create_controller(name, check),
|
||||||
"module" | "step" => Err(Error::new(ErrorKind::Unsupported,
|
"module" | "step" => Err(Error::new(
|
||||||
format!("create {kind} not implemented yet"))),
|
ErrorKind::Unsupported,
|
||||||
other => Err(Error::new(ErrorKind::InvalidInput, format!("unknown kind {other}"))),
|
format!("create {kind} not implemented yet"),
|
||||||
|
)),
|
||||||
|
other => Err(Error::new(
|
||||||
|
ErrorKind::InvalidInput,
|
||||||
|
format!("unknown kind {other}"),
|
||||||
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_controller(name: &str, check: bool) -> std::io::Result<()> {
|
fn create_controller(name: &str, check: bool) -> std::io::Result<()> {
|
||||||
let file = Path::new("src/controllers")
|
let file = Path::new("src/controllers").join(format!("{}.controller.ts", name.to_lowercase()));
|
||||||
.join(format!("{}.controller.ts", name.to_lowercase()));
|
|
||||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
std::fs::create_dir_all(file.parent().unwrap())?;
|
||||||
std::fs::write(&file, controller_stub(name))?;
|
std::fs::write(&file, controller_stub(name))?;
|
||||||
println!("✓ {}", file.display());
|
println!("✓ {}", file.display());
|
||||||
|
|||||||
+12
-6
@@ -6,8 +6,10 @@ use crate::template;
|
|||||||
pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> {
|
pub fn run(name: &str, template_url: Option<&str>) -> std::io::Result<()> {
|
||||||
let dest = Path::new(name);
|
let dest = Path::new(name);
|
||||||
if dest.exists() {
|
if dest.exists() {
|
||||||
return Err(Error::new(ErrorKind::AlreadyExists,
|
return Err(Error::new(
|
||||||
format!("'{name}' already exists")));
|
ErrorKind::AlreadyExists,
|
||||||
|
format!("'{name}' already exists"),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
match template_url {
|
match template_url {
|
||||||
@@ -46,12 +48,16 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
#[test]
|
#[test]
|
||||||
fn gh_shorthand_expands() {
|
fn gh_shorthand_expands() {
|
||||||
assert_eq!(resolve_url("gh:green-tea/tmpl"),
|
assert_eq!(
|
||||||
"https://github.com/green-tea/tmpl");
|
resolve_url("gh:green-tea/tmpl"),
|
||||||
|
"https://github.com/green-tea/tmpl"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn full_url_passes_through() {
|
fn full_url_passes_through() {
|
||||||
assert_eq!(resolve_url("https://example.com/x.git"),
|
assert_eq!(
|
||||||
"https://example.com/x.git");
|
resolve_url("https://example.com/x.git"),
|
||||||
|
"https://example.com/x.git"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+14
-6
@@ -12,13 +12,18 @@ fn command_for(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(dir: &Path) -> std::io::Result<()> {
|
pub fn run(dir: &Path) -> std::io::Result<()> {
|
||||||
let rt = runtime::detect(dir).ok_or_else(|| Error::new(
|
let rt = runtime::detect(dir).ok_or_else(|| {
|
||||||
ErrorKind::NotFound,
|
Error::new(
|
||||||
"no runtime detected (need deno.json, bun.lock, or package.json)",
|
ErrorKind::NotFound,
|
||||||
))?;
|
"no runtime detected (need deno.json, bun.lock, or package.json)",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
let (prog, args) = command_for(rt);
|
let (prog, args) = command_for(rt);
|
||||||
println!("→ {prog} {}", args.join(" "));
|
println!("→ {prog} {}", args.join(" "));
|
||||||
let status = std::process::Command::new(prog).args(&args).current_dir(dir).status()?;
|
let status = std::process::Command::new(prog)
|
||||||
|
.args(&args)
|
||||||
|
.current_dir(dir)
|
||||||
|
.status()?;
|
||||||
std::process::exit(status.code().unwrap_or(1));
|
std::process::exit(status.code().unwrap_or(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +38,10 @@ mod tests {
|
|||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn bun_watch() {
|
fn bun_watch() {
|
||||||
assert_eq!(command_for(Runtime::Bun), ("bun", vec!["--watch", "run", "dev"]));
|
assert_eq!(
|
||||||
|
command_for(Runtime::Bun),
|
||||||
|
("bun", vec!["--watch", "run", "dev"])
|
||||||
|
);
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn node_watch() {
|
fn node_watch() {
|
||||||
|
|||||||
+117
-8
@@ -30,7 +30,6 @@ fn parser() -> Parser {
|
|||||||
/// True when tree-sitter parses `src` with no `ERROR`/missing node anywhere
|
/// 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
|
/// in the tree. Used as the revert-on-breakage guarantee: if an edit fails
|
||||||
/// this check, the caller must discard it.
|
/// this check, the caller must discard it.
|
||||||
#[allow(dead_code)]
|
|
||||||
fn parses_clean(src: &str) -> bool {
|
fn parses_clean(src: &str) -> bool {
|
||||||
let tree = parser().parse(src, None).unwrap();
|
let tree = parser().parse(src, None).unwrap();
|
||||||
!has_error(tree.root_node())
|
!has_error(tree.root_node())
|
||||||
@@ -49,16 +48,60 @@ fn has_error(node: Node) -> bool {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inserts `import { <symbol> } from '<from>';` after the last top-level
|
/// Wires `symbol` into `src`'s imports from module `from`:
|
||||||
/// import statement. No-op (returns `src` unchanged) if the exact import
|
///
|
||||||
/// line is already present, making repeated calls idempotent.
|
/// 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 {
|
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}';");
|
let line = format!("import {{ {symbol} }} from '{from}';");
|
||||||
if src.contains(&line) {
|
if src.contains(&line) {
|
||||||
return src.to_string();
|
return src.to_string();
|
||||||
}
|
}
|
||||||
let tree = parser().parse(src, None).unwrap();
|
|
||||||
let root = tree.root_node();
|
|
||||||
let mut last_end = 0usize;
|
let mut last_end = 0usize;
|
||||||
let mut c = root.walk();
|
let mut c = root.walk();
|
||||||
for child in root.children(&mut c) {
|
for child in root.children(&mut c) {
|
||||||
@@ -77,6 +120,47 @@ pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
|||||||
out
|
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
|
/// Finds the `key: [ ... ]` array inside the first `@Module({...})` and
|
||||||
/// inserts `symbol` into it. Idempotent: a repeat call that would insert an
|
/// inserts `symbol` into it. Idempotent: a repeat call that would insert an
|
||||||
/// already-present symbol is a no-op. Returns `None` — leaving the caller's
|
/// already-present symbol is a no-op. Returns `None` — leaving the caller's
|
||||||
@@ -226,7 +310,9 @@ fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option<Node<'a>> {
|
|||||||
let call = find_decorator_call(*root, src)?;
|
let call = find_decorator_call(*root, src)?;
|
||||||
let args = call.child_by_field_name("arguments")?;
|
let args = call.child_by_field_name("arguments")?;
|
||||||
let mut ac = args.walk();
|
let mut ac = args.walk();
|
||||||
let object = args.named_children(&mut ac).find(|&child| child.kind() == "object");
|
let object = args
|
||||||
|
.named_children(&mut ac)
|
||||||
|
.find(|&child| child.kind() == "object");
|
||||||
object
|
object
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,7 +350,9 @@ export class AppModule {}
|
|||||||
// key missing entirely → our splice can't find it → None, file untouched upstream
|
// key missing entirely → our splice can't find it → None, file untouched upstream
|
||||||
assert!(
|
assert!(
|
||||||
add_to_module_array(MOD, "providers", "X").is_none()
|
add_to_module_array(MOD, "providers", "X").is_none()
|
||||||
|| add_to_module_array(MOD, "providers", "X").unwrap().contains("providers")
|
|| add_to_module_array(MOD, "providers", "X")
|
||||||
|
.unwrap()
|
||||||
|
.contains("providers")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -317,4 +405,25 @@ export class AppModule {}
|
|||||||
let src = "export class HomeController {\n home() {}\n}\n";
|
let src = "export class HomeController {\n home() {}\n}\n";
|
||||||
assert!(insert_method(src, "NotHere", " zen() {}\n").is_none());
|
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';"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+51
-11
@@ -5,13 +5,19 @@ use tempfile::tempdir;
|
|||||||
fn add_sse_appends_handler() {
|
fn add_sse_appends_handler() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
||||||
std::fs::write(d.path().join("src/controllers/home.controller.ts"),
|
std::fs::write(
|
||||||
"import { Route, Get } from '@green-tea/core';\n\n\
|
d.path().join("src/controllers/home.controller.ts"),
|
||||||
@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n").unwrap();
|
"import { Route, Get } from '@green-tea/core';\n\n\
|
||||||
|
@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["add", "sse"]).assert().success();
|
.args(["add", "sse"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
|
||||||
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||||
assert!(out.contains("@Sse("));
|
assert!(out.contains("@Sse("));
|
||||||
@@ -22,9 +28,34 @@ fn add_sse_appends_handler() {
|
|||||||
fn add_errors_when_no_controller() {
|
fn add_errors_when_no_controller() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["add", "sse"]).assert().failure();
|
.args(["add", "sse"])
|
||||||
|
.assert()
|
||||||
|
.failure();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_sse_twice_is_idempotent() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
||||||
|
std::fs::write(d.path().join("src/controllers/home.controller.ts"),
|
||||||
|
"import { Route, Get } from '@green-tea/core';\n\n@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n").unwrap();
|
||||||
|
let run = || {
|
||||||
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
|
.current_dir(d.path())
|
||||||
|
.args(["add", "sse"])
|
||||||
|
.assert()
|
||||||
|
.success()
|
||||||
|
};
|
||||||
|
run();
|
||||||
|
run();
|
||||||
|
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||||
|
// exactly one Sse handler, exactly one @green-tea/core import line
|
||||||
|
assert_eq!(out.matches("@Sse(").count(), 1);
|
||||||
|
assert_eq!(out.matches("from '@green-tea/core'").count(), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -36,10 +67,19 @@ fn add_errors_when_multiple_controllers_and_writes_nothing() {
|
|||||||
for n in ["a", "b"] {
|
for n in ["a", "b"] {
|
||||||
std::fs::write(cdir.join(format!("{n}.controller.ts")), original).unwrap();
|
std::fs::write(cdir.join(format!("{n}.controller.ts")), original).unwrap();
|
||||||
}
|
}
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["add", "sse"]).assert().failure();
|
.args(["add", "sse"])
|
||||||
|
.assert()
|
||||||
|
.failure();
|
||||||
// no file was modified
|
// no file was modified
|
||||||
assert_eq!(std::fs::read_to_string(cdir.join("a.controller.ts")).unwrap(), original);
|
assert_eq!(
|
||||||
assert_eq!(std::fs::read_to_string(cdir.join("b.controller.ts")).unwrap(), original);
|
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>
|
||||||
}
|
}
|
||||||
+15
-6
@@ -3,20 +3,29 @@ use tempfile::tempdir;
|
|||||||
|
|
||||||
fn seed_module(dir: &std::path::Path) {
|
fn seed_module(dir: &std::path::Path) {
|
||||||
std::fs::create_dir_all(dir.join("src/controllers")).unwrap();
|
std::fs::create_dir_all(dir.join("src/controllers")).unwrap();
|
||||||
std::fs::write(dir.join("src/app.module.ts"),
|
std::fs::write(
|
||||||
"import { Module } from '@green-tea/core';\n\n\
|
dir.join("src/app.module.ts"),
|
||||||
@Module({ controllers: [] })\nexport class AppModule {}\n").unwrap();
|
"import { Module } from '@green-tea/core';\n\n\
|
||||||
|
@Module({ controllers: [] })\nexport class AppModule {}\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn create_controller_writes_and_wires() {
|
fn create_controller_writes_and_wires() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
seed_module(d.path());
|
seed_module(d.path());
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["create", "controller", "Users"]).assert().success();
|
.args(["create", "controller", "Users"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
|
||||||
assert!(d.path().join("src/controllers/users.controller.ts").exists());
|
assert!(d
|
||||||
|
.path()
|
||||||
|
.join("src/controllers/users.controller.ts")
|
||||||
|
.exists());
|
||||||
let module = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap();
|
let module = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap();
|
||||||
assert!(module.contains("UsersController"));
|
assert!(module.contains("UsersController"));
|
||||||
assert!(module.contains("import { UsersController }"));
|
assert!(module.contains("import { UsersController }"));
|
||||||
|
|||||||
+38
-10
@@ -5,9 +5,12 @@ 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());
|
||||||
@@ -17,9 +20,12 @@ fn new_scaffolds_into_named_dir() {
|
|||||||
fn new_refuses_existing_dir() {
|
fn new_refuses_existing_dir() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
std::fs::create_dir(d.path().join("taken")).unwrap();
|
std::fs::create_dir(d.path().join("taken")).unwrap();
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["new", "taken"]).assert().failure();
|
.args(["new", "taken"])
|
||||||
|
.assert()
|
||||||
|
.failure();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -29,15 +35,37 @@ fn new_clones_local_template() {
|
|||||||
let src = d.path().join("src-tmpl");
|
let src = d.path().join("src-tmpl");
|
||||||
std::fs::create_dir_all(src.join("public")).unwrap();
|
std::fs::create_dir_all(src.join("public")).unwrap();
|
||||||
std::fs::write(src.join("public/marker.txt"), "hi").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")
|
||||||
Proc::new("git").args(["add", "."]).current_dir(&src).status().unwrap();
|
.args(["init", "-q"])
|
||||||
Proc::new("git").args(["-c","user.email=t@t","-c","user.name=t",
|
.current_dir(&src)
|
||||||
"commit","-qm","init"]).current_dir(&src).status().unwrap();
|
.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());
|
let url = format!("file://{}", src.display());
|
||||||
Command::cargo_bin("matcha").unwrap()
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
.current_dir(d.path())
|
.current_dir(d.path())
|
||||||
.args(["new", "cloned", "--template-url", &url]).assert().success();
|
.args(["new", "cloned", "--template-url", &url])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
assert!(d.path().join("cloned/public/marker.txt").exists());
|
assert!(d.path().join("cloned/public/marker.txt").exists());
|
||||||
assert!(!d.path().join("cloned/.git").exists()); // .git stripped
|
assert!(!d.path().join("cloned/.git").exists()); // .git stripped
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user