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 <diego.resendez@zero-oneit.com>
This commit is contained in:
8 files changed
+383
-12
No files matched your search
+17
-1
@@ -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<String>,
|
||||
#[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<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
|
||||
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`
|
||||
/// (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"),
|
||||
|
||||
@@ -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_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);
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
/// Inserts `symbol` into the `modules` array of the first `createApp(...)`
|
||||
/// call's argument object (creating the `modules` key if absent). Idempotent;
|
||||
/// reverts (returns `None`) on parse breakage or when no `createApp(...)` call
|
||||
/// with an object argument is found.
|
||||
pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option<String> {
|
||||
/// 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<String> {
|
||||
let tree = parser().parse(src, None).unwrap();
|
||||
let root = tree.root_node();
|
||||
let object = find_createapp_object(&root, src)?;
|
||||
insert_into_object_array(src, object, "modules", symbol)
|
||||
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`
|
||||
|
||||
Reference in new issue
Block a user