release: 26.9.0-beta.1 — create plugin, core 26.9.0-beta.2 #15
No files matched your search
+17
-1
@@ -26,9 +26,25 @@ pub enum Command {
|
|||||||
Create {
|
Create {
|
||||||
#[arg(value_parser = PossibleValuesParser::new(cmd_create::kinds()))]
|
#[arg(value_parser = PossibleValuesParser::new(cmd_create::kinds()))]
|
||||||
kind: String,
|
kind: String,
|
||||||
name: String,
|
/// Required for every kind but `plugin`, which asks for it
|
||||||
|
name: Option<String>,
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
check: bool,
|
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<Option<String>>,
|
||||||
|
/// plugin, in-app: folder relative to the project root (default: plugins)
|
||||||
|
#[arg(long)]
|
||||||
|
folder: Option<String>,
|
||||||
|
/// plugin, package: the JSR scope
|
||||||
|
#[arg(long)]
|
||||||
|
scope: Option<String>,
|
||||||
|
/// plugin, package: where it publishes (default: jsr)
|
||||||
|
#[arg(long, value_parser = ["jsr", "both"])]
|
||||||
|
registry: Option<String>,
|
||||||
|
/// plugin, package, both: the npm name (default: @<scope>/green-tea-<slug>)
|
||||||
|
#[arg(long)]
|
||||||
|
npm_name: Option<String>,
|
||||||
},
|
},
|
||||||
/// Check the project for the misconfigurations that fail confusingly
|
/// Check the project for the misconfigurations that fail confusingly
|
||||||
Doctor,
|
Doctor,
|
||||||
|
|||||||
+4
-2
@@ -53,8 +53,10 @@ const PIECES: &[Piece] = &[
|
|||||||
/// list, so a new kind cannot be accepted by the parser and rejected by `run`
|
/// list, so a new kind cannot be accepted by the parser and rejected by `run`
|
||||||
/// (or the reverse).
|
/// (or the reverse).
|
||||||
pub fn kinds() -> Vec<&'static str> {
|
pub fn kinds() -> Vec<&'static str> {
|
||||||
std::iter::once("module")
|
["module"]
|
||||||
|
.into_iter()
|
||||||
.chain(PIECES.iter().map(|p| p.kind))
|
.chain(PIECES.iter().map(|p| p.kind))
|
||||||
|
.chain(["plugin"])
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +145,7 @@ fn create_module(name: &str, check: bool) -> std::io::Result<()> {
|
|||||||
maybe_check(check)
|
maybe_check(check)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn maybe_check(check: bool) -> std::io::Result<()> {
|
pub(crate) fn maybe_check(check: bool) -> std::io::Result<()> {
|
||||||
if check {
|
if check {
|
||||||
match crate::check::run(Path::new(".")) {
|
match crate::check::run(Path::new(".")) {
|
||||||
Ok(true) => println!("✓ type-check passed"),
|
Ok(true) => println!("✓ type-check passed"),
|
||||||
|
|||||||
@@ -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<String>,
|
||||||
|
/// `None`: not asked for. `Some(None)`: `--package` with no directory.
|
||||||
|
pub package: Option<Option<String>>,
|
||||||
|
pub folder: Option<String>,
|
||||||
|
pub scope: Option<String>,
|
||||||
|
pub registry: Option<String>,
|
||||||
|
pub npm_name: Option<String>,
|
||||||
|
pub check: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(opts: Opts) -> io::Result<()> {
|
||||||
|
run_with(opts, &mut Ask::stdio(), Path::new("."))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run_with<R: BufRead, W: Write>(
|
||||||
|
opts: Opts,
|
||||||
|
ask: &mut Ask<R, W>,
|
||||||
|
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<R: BufRead, W: Write>(
|
||||||
|
name: Option<String>,
|
||||||
|
ask: &mut Ask<R, W>,
|
||||||
|
) -> io::Result<String> {
|
||||||
|
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<R: BufRead, W: Write>(opts: Opts, ask: &mut Ask<R, W>, 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<R: BufRead, W: Write>(
|
||||||
|
_opts: Opts,
|
||||||
|
_ask: &mut Ask<R, W>,
|
||||||
|
_root: &Path,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
Err(invalid("package mode is not built yet".into()))
|
||||||
|
}
|
||||||
+32
-2
@@ -6,9 +6,11 @@ mod cmd_create;
|
|||||||
mod cmd_doctor;
|
mod cmd_doctor;
|
||||||
mod cmd_graph;
|
mod cmd_graph;
|
||||||
mod cmd_new;
|
mod cmd_new;
|
||||||
|
mod cmd_plugin;
|
||||||
mod cmd_run;
|
mod cmd_run;
|
||||||
mod entry;
|
mod entry;
|
||||||
mod naming;
|
mod naming;
|
||||||
|
mod plugin_files;
|
||||||
mod runtime;
|
mod runtime;
|
||||||
mod template;
|
mod template;
|
||||||
mod wire;
|
mod wire;
|
||||||
@@ -35,8 +37,36 @@ fn main() {
|
|||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Command::Create { kind, name, check } => {
|
Command::Create {
|
||||||
if let Err(e) = cmd_create::run(&kind, &name, check) {
|
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}");
|
eprintln!("error: {e}");
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 }}),
|
||||||
|
}});
|
||||||
|
}},
|
||||||
|
}};
|
||||||
|
}}
|
||||||
|
"
|
||||||
|
)
|
||||||
|
}
|
||||||
+13
-6
@@ -215,15 +215,22 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option<String>
|
|||||||
insert_into_object_array(src, object, key, symbol)
|
insert_into_object_array(src, object, key, symbol)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inserts `symbol` into the `modules` array of the first `createApp(...)`
|
/// Inserts `item` into the `key: [...]` array of the first `createApp(...)`
|
||||||
/// call's argument object (creating the `modules` key if absent). Idempotent;
|
/// call's argument object, creating the key if absent. `item` is any array
|
||||||
/// reverts (returns `None`) on parse breakage or when no `createApp(...)` call
|
/// element: a symbol for `modules`, a call like `algo()` for `plugins`.
|
||||||
/// with an object argument is found.
|
/// Idempotent; returns `None` on parse breakage, when there is no
|
||||||
pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option<String> {
|
/// `createApp({...})`, or when `key` holds something other than an array
|
||||||
|
/// literal.
|
||||||
|
pub fn add_to_createapp(src: &str, key: &str, item: &str) -> Option<String> {
|
||||||
let tree = parser().parse(src, None).unwrap();
|
let tree = parser().parse(src, None).unwrap();
|
||||||
let root = tree.root_node();
|
let root = tree.root_node();
|
||||||
let object = find_createapp_object(&root, src)?;
|
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<String> {
|
||||||
|
add_to_createapp(src, "modules", symbol)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inserts `symbol` into the `key: [...]` array directly inside `object`
|
/// Inserts `symbol` into the `key: [...]` array directly inside `object`
|
||||||
|
|||||||
+4
-1
@@ -25,7 +25,10 @@ fn help_lists_all_subcommands() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn create_and_add_advertise_every_value_they_accept() {
|
fn create_and_add_advertise_every_value_they_accept() {
|
||||||
for (command, values) in [
|
for (command, values) in [
|
||||||
("create", vec!["module", "controller", "step", "provider"]),
|
(
|
||||||
|
"create",
|
||||||
|
vec!["module", "controller", "step", "provider", "plugin"],
|
||||||
|
),
|
||||||
("add", vec!["sse", "stream", "buffer", "ws", "upload"]),
|
("add", vec!["sse", "stream", "buffer", "ws", "upload"]),
|
||||||
] {
|
] {
|
||||||
let mut assertion = Command::cargo_bin("matcha")
|
let mut assertion = Command::cargo_bin("matcha")
|
||||||
|
|||||||
+145
@@ -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"));
|
||||||
|
}
|
||||||
Reference in new issue
Block a user