From 3c3b7aaf8e2e99574b3a4d088fdf21df25d8b7bc Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 12:54:51 -0500 Subject: [PATCH] feat(plugin): matcha create plugin scaffolds an in-app plugin and wires it In-app is the default. Each plugin gets its own folder under plugins/ (or --folder), so it can be exported as a package later, and the factory is registered in createApp({ plugins }). A plugins value that is not an array literal is left alone with a hint, as modules already is. Signed-off-by: Diego Resendez --- src/cli.rs | 18 +++++- src/cmd_create.rs | 6 +- src/cmd_plugin.rs | 130 +++++++++++++++++++++++++++++++++++++++ src/main.rs | 34 ++++++++++- src/plugin_files.rs | 38 ++++++++++++ src/wire.rs | 19 ++++-- tests/cli.rs | 5 +- tests/plugin.rs | 145 ++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 383 insertions(+), 12 deletions(-) create mode 100644 src/cmd_plugin.rs create mode 100644 src/plugin_files.rs create mode 100644 tests/plugin.rs diff --git a/src/cli.rs b/src/cli.rs index 83e9d80..e03153f 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -26,9 +26,25 @@ pub enum Command { Create { #[arg(value_parser = PossibleValuesParser::new(cmd_create::kinds()))] kind: String, - name: String, + /// Required for every kind but `plugin`, which asks for it + name: Option, #[arg(long)] check: bool, + /// plugin: a package of its own, in DIR (default: the current directory, which must be empty) + #[arg(long, num_args = 0..=1, value_name = "DIR")] + package: Option>, + /// plugin, in-app: folder relative to the project root (default: plugins) + #[arg(long)] + folder: Option, + /// plugin, package: the JSR scope + #[arg(long)] + scope: Option, + /// plugin, package: where it publishes (default: jsr) + #[arg(long, value_parser = ["jsr", "both"])] + registry: Option, + /// plugin, package, both: the npm name (default: @/green-tea-) + #[arg(long)] + npm_name: Option, }, /// Check the project for the misconfigurations that fail confusingly Doctor, diff --git a/src/cmd_create.rs b/src/cmd_create.rs index 0e1050f..d4a6bc1 100644 --- a/src/cmd_create.rs +++ b/src/cmd_create.rs @@ -53,8 +53,10 @@ const PIECES: &[Piece] = &[ /// 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") + ["module"] + .into_iter() .chain(PIECES.iter().map(|p| p.kind)) + .chain(["plugin"]) .collect() } @@ -143,7 +145,7 @@ fn create_module(name: &str, check: bool) -> std::io::Result<()> { maybe_check(check) } -fn maybe_check(check: bool) -> std::io::Result<()> { +pub(crate) fn maybe_check(check: bool) -> std::io::Result<()> { if check { match crate::check::run(Path::new(".")) { Ok(true) => println!("✓ type-check passed"), diff --git a/src/cmd_plugin.rs b/src/cmd_plugin.rs new file mode 100644 index 0000000..72da961 --- /dev/null +++ b/src/cmd_plugin.rs @@ -0,0 +1,130 @@ +//! `matcha create plugin`: an in-app plugin folder by default, or, with +//! `--package` or a yes, a package of its own. + +use std::io::{self, BufRead, Error, ErrorKind, Write}; +use std::path::{Component, Path}; + +use crate::ask::Ask; +use crate::{entry, naming, plugin_files, wire}; + +pub struct Opts { + pub name: Option, + /// `None`: not asked for. `Some(None)`: `--package` with no directory. + pub package: Option>, + pub folder: Option, + pub scope: Option, + pub registry: Option, + pub npm_name: Option, + pub check: bool, +} + +pub fn run(opts: Opts) -> io::Result<()> { + run_with(opts, &mut Ask::stdio(), Path::new(".")) +} + +pub fn run_with( + opts: Opts, + ask: &mut Ask, + root: &Path, +) -> io::Result<()> { + let package = match opts.package { + Some(_) => true, + None => ask.yes_no("Separate it as a package?", false)?, + }; + if package { + package_mode(opts, ask, root) + } else { + in_app(opts, ask, root) + } +} + +fn invalid(msg: String) -> Error { + Error::new(ErrorKind::InvalidInput, msg) +} + +fn resolve_slug( + name: Option, + ask: &mut Ask, +) -> io::Result { + let raw = match name { + Some(n) => n, + None => ask.text("Plugin name?", None, "the NAME argument")?, + }; + naming::slug(&raw).ok_or_else(|| { + invalid(format!( + "'{raw}' does not make a plugin name: start with a letter, and use letters, digits, spaces or hyphens" + )) + }) +} + +/// Relative, and never climbing out: `..` or an absolute path would put the +/// plugin outside the project it is being wired into. +fn inside_project(folder: &str) -> bool { + !folder.is_empty() + && Path::new(folder) + .components() + .all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) +} + +fn in_app(opts: Opts, ask: &mut Ask, root: &Path) -> io::Result<()> { + let Some(entry_path) = entry::find(root) else { + return Err(invalid(format!( + "an in-app plugin is wired into createApp, and there is no {} here; run this in a project, or pass --package for a package of its own", + entry::candidates() + ))); + }; + let folder = match opts.folder { + Some(f) => f, + None => ask.text("Folder?", Some("plugins"), "--folder")?, + }; + let folder = folder.trim_end_matches('/').to_string(); + if !inside_project(&folder) { + return Err(invalid(format!( + "the plugin folder has to be inside the project, got '{folder}'" + ))); + } + let slug = resolve_slug(opts.name, ask)?; + + let dir = root.join(&folder).join(&slug); + if dir.exists() { + return Err(Error::new( + ErrorKind::AlreadyExists, + format!( + "{} already exists", + Path::new(&folder).join(&slug).display() + ), + )); + } + std::fs::create_dir_all(&dir)?; + std::fs::write(dir.join("index.ts"), plugin_files::factory(&slug))?; + println!( + "✓ {}", + Path::new(&folder).join(&slug).join("index.ts").display() + ); + + let fun = naming::camel(&slug); + let call = format!("{fun}()"); + // Both entry candidates live in src/, so the plugin folder is one level up. + let from = format!("../{folder}/{slug}/index"); + let src = std::fs::read_to_string(&entry_path)?; + let imported = wire::add_import(&src, &fun, &from); + match wire::add_to_createapp(&imported, "plugins", &call) { + Some(wired) => { + std::fs::write(&entry_path, wired)?; + println!("✓ registered {call} in createApp"); + } + None => println!( + "→ could not auto-register; add {call} to createApp plugins[] in {}, and import {{ {fun} }} from '{from}'", + entry_path.strip_prefix(root).unwrap_or(&entry_path).display() + ), + } + crate::cmd_create::maybe_check(opts.check) +} + +fn package_mode( + _opts: Opts, + _ask: &mut Ask, + _root: &Path, +) -> io::Result<()> { + Err(invalid("package mode is not built yet".into())) +} diff --git a/src/main.rs b/src/main.rs index 3a30a50..2bb1686 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,9 +6,11 @@ mod cmd_create; mod cmd_doctor; mod cmd_graph; mod cmd_new; +mod cmd_plugin; mod cmd_run; mod entry; mod naming; +mod plugin_files; mod runtime; mod template; mod wire; @@ -35,8 +37,36 @@ fn main() { std::process::exit(1); } } - Command::Create { kind, name, check } => { - if let Err(e) = cmd_create::run(&kind, &name, check) { + Command::Create { + kind, + name, + check, + package, + folder, + scope, + registry, + npm_name, + } => { + let result = if kind == "plugin" { + cmd_plugin::run(cmd_plugin::Opts { + name, + package, + folder, + scope, + registry, + npm_name, + check, + }) + } else { + match name { + Some(name) => cmd_create::run(&kind, &name, check), + None => Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("create {kind} needs a name"), + )), + } + }; + if let Err(e) = result { eprintln!("error: {e}"); std::process::exit(1); } diff --git a/src/plugin_files.rs b/src/plugin_files.rs new file mode 100644 index 0000000..ba9df21 --- /dev/null +++ b/src/plugin_files.rs @@ -0,0 +1,38 @@ +//! The text of every file `matcha create plugin` writes. Pure: slug and +//! options in, file content out, so the shapes are tested without a disk. + +use crate::naming::{camel, pascal}; + +/// The plugin itself, the same in both modes. It follows the official +/// plugins' convention: one string is the plugin name, the node name and the +/// token, and `provides` renames it, so two instances can sit side by side. +pub fn factory(slug: &str) -> String { + let fun = camel(slug); + let opts = format!("{}Options", pascal(slug)); + format!( + "import type {{ Plugin }} from '@green-tea/core'; + +export interface {opts} {{ + /** The token this plugin provides. Change it to mount two instances side by side. */ + provides?: string; +}} + +export function {fun}(options: {opts} = {{}}): Plugin {{ + const provides = options.provides ?? '{slug}'; + + return {{ + name: provides, + mount({{ scope }}) {{ + scope.add({{ + kind: 'provider', + name: provides, + needs: [], + provides: [provides], + run: () => ({{ [provides]: null }}), + }}); + }}, + }}; +}} +" + ) +} diff --git a/src/wire.rs b/src/wire.rs index 21c2209..e44e012 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -215,15 +215,22 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option 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 { +/// Inserts `item` into the `key: [...]` array of the first `createApp(...)` +/// call's argument object, creating the key if absent. `item` is any array +/// element: a symbol for `modules`, a call like `algo()` for `plugins`. +/// Idempotent; returns `None` on parse breakage, when there is no +/// `createApp({...})`, or when `key` holds something other than an array +/// literal. +pub fn add_to_createapp(src: &str, key: &str, item: &str) -> Option { 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) + insert_into_object_array(src, object, key, item) +} + +/// `add_to_createapp` for `modules`, kept as the name `create module` reads. +pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option { + add_to_createapp(src, "modules", symbol) } /// Inserts `symbol` into the `key: [...]` array directly inside `object` diff --git a/tests/cli.rs b/tests/cli.rs index 620118c..b098072 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -25,7 +25,10 @@ fn help_lists_all_subcommands() { #[test] fn create_and_add_advertise_every_value_they_accept() { for (command, values) in [ - ("create", vec!["module", "controller", "step", "provider"]), + ( + "create", + vec!["module", "controller", "step", "provider", "plugin"], + ), ("add", vec!["sse", "stream", "buffer", "ws", "upload"]), ] { let mut assertion = Command::cargo_bin("matcha") diff --git a/tests/plugin.rs b/tests/plugin.rs new file mode 100644 index 0000000..02d73bf --- /dev/null +++ b/tests/plugin.rs @@ -0,0 +1,145 @@ +use assert_cmd::Command; +use predicates::str::contains; +use tempfile::tempdir; + +const APP: &str = "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nexport const app = createApp({ modules: [AppModule] });\n"; + +fn project(app_ts: &str) -> tempfile::TempDir { + let d = tempdir().unwrap(); + std::fs::create_dir_all(d.path().join("src")).unwrap(); + std::fs::write(d.path().join("src/app.ts"), app_ts).unwrap(); + d +} + +fn matcha(dir: &std::path::Path) -> Command { + let mut c = Command::cargo_bin("matcha").unwrap(); + c.current_dir(dir); + c +} + +#[test] +fn in_app_is_the_default_and_wires_into_create_app() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "Plugin Algo"]) + .assert() + .success(); + + let index = std::fs::read_to_string(d.path().join("plugins/plugin-algo/index.ts")).unwrap(); + assert!(index.contains("export function pluginAlgo(")); + assert!(index.contains("options.provides ?? 'plugin-algo'")); + let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(); + assert!( + app.contains("import { pluginAlgo } from '../plugins/plugin-algo/index';"), + "{app}" + ); + assert!(app.contains("plugins: [pluginAlgo()]"), "{app}"); +} + +#[test] +fn in_app_appends_to_an_existing_plugins_array() { + let d = project("import { createApp } from '@green-tea/core';\n\nexport const app = createApp({ modules: [], plugins: [other()] });\n"); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .success(); + let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(); + assert!(app.contains("plugins: [other(), algo()]"), "{app}"); +} + +#[test] +fn in_app_honours_folder() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "algo", "--folder", "lib/plugins"]) + .assert() + .success(); + assert!(d.path().join("lib/plugins/algo/index.ts").exists()); + let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(); + assert!(app.contains("'../lib/plugins/algo/index'"), "{app}"); +} + +#[test] +fn in_app_leaves_a_non_array_plugins_alone_and_says_what_to_add() { + let original = "import { createApp } from '@green-tea/core';\n\nexport const app = createApp({ modules: [], plugins: PLUGINS });\n"; + let d = project(original); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .success() + .stdout(contains("add algo() to createApp plugins[]")); + assert_eq!( + std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(), + original + ); + assert!(d.path().join("plugins/algo/index.ts").exists()); +} + +#[test] +fn in_app_refuses_an_existing_folder() { + let d = project(APP); + std::fs::create_dir_all(d.path().join("plugins/algo")).unwrap(); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .failure() + .stderr(contains("already exists")); + assert_eq!( + std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(), + APP + ); +} + +#[test] +fn in_app_refuses_a_folder_outside_the_project() { + let d = project(APP); + for folder in ["../outside", "/tmp/elsewhere"] { + matcha(d.path()) + .args(["create", "plugin", "algo", "--folder", folder]) + .assert() + .failure() + .stderr(contains("inside the project")); + } +} + +#[test] +fn in_app_needs_a_project() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .failure() + .stderr(contains("src/app.ts")); +} + +#[test] +fn a_bad_name_writes_nothing() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "🍵"]) + .assert() + .failure() + .stderr(contains("does not make a plugin name")); + assert!(!d.path().join("plugins").exists()); +} + +#[test] +fn off_a_tty_a_missing_name_is_an_error_not_a_hang() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin"]) + .timeout(std::time::Duration::from_secs(10)) + .assert() + .failure() + .stderr(contains("NAME")); +} + +#[test] +fn other_kinds_still_require_a_name() { + let d = project(APP); + matcha(d.path()) + .args(["create", "controller"]) + .assert() + .failure() + .stderr(contains("needs a name")); +}