fix(plugin): the review's smaller findings
CI / installer (macos-14) (pull_request) Successful in 4s
CI / check (pull_request) Failing after 29s
CI / starter (bun) (pull_request) Successful in 32s
CI / starter (deno) (pull_request) Successful in 33s
CI / starter (edge) (pull_request) Successful in 37s
CI / core-freshness (pull_request) Has been skipped
CI / installer (ubuntu-latest) (pull_request) Successful in 11s
CI / starter (node) (pull_request) Successful in 34s

- `--package` takes a directory only as `--package=DIR`, so
  `create plugin --package algo` names the plugin instead of writing
  into ./algo.
- A NAME passed on the command line is checked before any question.
- The package directory is named in its errors, a file there is
  reported as a file, and a failed write lists what was already written.
- An in-app plugin folder is removed again if the entry cannot be
  written, so the rerun does not stop on "already exists".
- `--folder .` and `./plugins/` give clean import paths.
- Flags for the other mode are named as ignored; plugin flags on
  another create kind are an error.
- Array elements are read from the parse tree, so `algo({ a, b })` is
  one element when checking for a duplicate.
- Scopes follow JSR's rule: 2 to 20 characters, no leading hyphen.
- Packages ship a LICENSE (MIT, which the README says to change), the
  license field in both manifests, and @types/node for the test file.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-24 13:26:29 -05:00
1 parent 4358091d07
commit ecdc46cac3
8 files changed
+460 -86

No files matched your search

+2 -2
View File
@@ -30,8 +30,8 @@ pub enum Command {
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")]
/// plugin: a package of its own, in --package=DIR (default: the current directory, which must be empty)
#[arg(long, num_args = 0..=1, require_equals = true, value_name = "DIR")]
package: Option<Option<String>>,
/// plugin, in-app: folder relative to the project root (default: plugins)
#[arg(long)]
+161 -40
View File
@@ -27,13 +27,31 @@ pub fn run_with<R: BufRead, W: Write>(
ask: &mut Ask<R, W>,
root: &Path,
) -> io::Result<()> {
// A NAME given on the command line is checked before any question.
if let Some(name) = &opts.name {
check_name(name)?;
}
let package = match opts.package {
Some(_) => true,
None => ask.yes_no("Separate it as a package?", false)?,
};
if package {
for (flag, given) in [("--folder", opts.folder.is_some()), ("--check", opts.check)] {
if given {
println!("note: {flag} only applies to an in-app plugin; ignored");
}
}
package_mode(opts, ask, root)
} else {
for (flag, given) in [
("--scope", opts.scope.is_some()),
("--registry", opts.registry.is_some()),
("--npm-name", opts.npm_name.is_some()),
] {
if given {
println!("note: {flag} only applies to --package; ignored");
}
}
in_app(opts, ask, root)
}
}
@@ -42,15 +60,10 @@ 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")?,
};
let slug = naming::slug(&raw).ok_or_else(|| {
/// The slug for `raw`, or why it cannot be one: not a name, or a factory that
/// would be a reserved word.
fn check_name(raw: &str) -> io::Result<String> {
let slug = 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"
))
@@ -64,6 +77,17 @@ fn resolve_slug<R: BufRead, W: Write>(
Ok(slug)
}
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")?,
};
check_name(&raw)
}
/// 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 {
@@ -84,70 +108,121 @@ fn in_app<R: BufRead, W: Write>(opts: Opts, ask: &mut Ask<R, W>, root: &Path) ->
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}'"
)));
}
// `.`, `./plugins` and `plugins/` all mean what they say without leaving a
// `./` or a trailing slash in the import path.
let folder: Vec<String> = Path::new(&folder)
.components()
.filter_map(|c| match c {
Component::Normal(p) => Some(p.to_string_lossy().into_owned()),
_ => None,
})
.collect();
let folder = folder.join("/");
let slug = resolve_slug(opts.name, ask)?;
let fun = naming::camel(&slug);
let src = std::fs::read_to_string(&entry_path)?;
let entry_shown = entry_path
.strip_prefix(root)
.unwrap_or(&entry_path)
.display()
.to_string();
// A second binding of a name the entry already has is a SyntaxError, and it
// would break the app rather than only the new plugin.
if wire::binds(&src, &fun) {
return Err(invalid(format!(
"{} already uses `{fun}`, so the plugin's factory would collide with it; pick another name",
entry_path.strip_prefix(root).unwrap_or(&entry_path).display()
"{entry_shown} already uses `{fun}`, so the plugin's factory would collide with it; pick another name"
)));
}
let dir = root.join(&folder).join(&slug);
let shown = Path::new(&folder).join(&slug);
let dir = root.join(&shown);
if dir.exists() {
return Err(Error::new(
ErrorKind::AlreadyExists,
format!(
"{} already exists",
Path::new(&folder).join(&slug).display()
),
format!("{} already exists", shown.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 call = format!("{fun}()");
// Both entry candidates live in src/, so the plugin folder is one level up.
let from = format!("../{folder}/{slug}/index");
let imported = wire::add_import(&src, &fun, &from);
match wire::add_to_createapp(&imported, "plugins", &call) {
let from = if folder.is_empty() {
format!("../{slug}/index")
} else {
format!("../{folder}/{slug}/index")
};
let wired = wire::add_to_createapp(&wire::add_import(&src, &fun, &from), "plugins", &call);
std::fs::create_dir_all(&dir)?;
std::fs::write(dir.join("index.ts"), plugin_files::factory(&slug))?;
println!("✓ {}", shown.join("index.ts").display());
match wired {
Some(wired) => {
std::fs::write(&entry_path, wired)?;
// The plugin folder and its registration land together or not at
// all: a folder left behind would make the rerun say "already exists".
if let Err(e) = std::fs::write(&entry_path, wired) {
let _ = std::fs::remove_dir_all(&dir);
return Err(Error::new(
e.kind(),
format!(
"could not write {entry_shown} ({e}); removed {} again",
shown.display()
),
));
}
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()
"→ could not auto-register; add {call} to createApp plugins[] in {entry_shown}, and import {{ {fun} }} from '{from}'"
),
}
crate::cmd_create::maybe_check(opts.check)
}
const EMPTY_DIR: &str = "a plugin package needs an empty directory, so the package stays self-contained — pass --package <dir> or run it in an empty folder";
const EMPTY_DIR: &str = "a plugin package needs an empty directory, so the package stays self-contained — pass --package=<dir> or run it in an empty folder";
const NPM_CONVENTION: &str =
"green-tea-<x> is the naming convention; the plugin listing uses it to find green-tea plugins.";
/// JSR's scope rule: lowercase letters, digits and hyphens.
/// JSR's scope rule: 2 to 20 characters, lowercase letters, digits and
/// hyphens, and not starting with a hyphen.
fn valid_scope(s: &str) -> bool {
!s.is_empty()
(2..=20).contains(&s.len())
&& !s.starts_with('-')
&& s.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// Writes every file, reporting each; on a failure, the error names the files
/// already written, so a half-filled directory is not a mystery on the rerun.
fn write_all(dir: &Path, root: &Path, files: &[(String, String)]) -> io::Result<()> {
let mut written: Vec<&str> = Vec::new();
for (rel, content) in files {
let path = dir.join(rel);
let result = std::fs::create_dir_all(path.parent().unwrap())
.and_then(|()| std::fs::write(&path, content));
if let Err(e) = result {
let so_far = if written.is_empty() {
"none".to_string()
} else {
written.join(", ")
};
return Err(Error::new(
e.kind(),
format!("could not write {rel} ({e}); already written: {so_far}"),
));
}
println!("✓ {}", path.strip_prefix(root).unwrap_or(&path).display());
written.push(rel);
}
Ok(())
}
/// npm's package name rule, closely enough to catch a typo: optional `@scope/`, lowercase.
fn valid_npm_name(s: &str) -> bool {
let part = |p: &str| {
@@ -173,8 +248,17 @@ fn package_mode<R: BufRead, W: Write>(
Some(Some(d)) => root.join(d),
_ => root.to_path_buf(),
};
let dir_shown = dir.strip_prefix(root).unwrap_or(&dir).display().to_string();
let dir_shown = if dir_shown.is_empty() {
".".to_string()
} else {
dir_shown
};
if dir.is_file() {
return Err(invalid(format!("{dir_shown} is a file; {EMPTY_DIR}")));
}
if dir.exists() && std::fs::read_dir(&dir)?.next().is_some() {
return Err(invalid(EMPTY_DIR.into()));
return Err(invalid(format!("{dir_shown}: {EMPTY_DIR}")));
}
let slug = resolve_slug(opts.name, ask)?;
@@ -185,7 +269,7 @@ fn package_mode<R: BufRead, W: Write>(
let scope = scope.trim_start_matches('@').to_string();
if !valid_scope(&scope) {
return Err(invalid(format!(
"'{scope}' is not a JSR scope: use lowercase letters, digits and hyphens"
"'{scope}' is not a JSR scope: 2 to 20 lowercase letters, digits or hyphens, not starting with a hyphen"
)));
}
@@ -223,14 +307,51 @@ fn package_mode<R: BufRead, W: Write>(
};
let package = plugin_files::Package { slug, scope, npm };
for (rel, content) in plugin_files::package(&package) {
let path = dir.join(&rel);
std::fs::create_dir_all(path.parent().unwrap())?;
std::fs::write(&path, content)?;
println!("✓ {}", path.strip_prefix(root).unwrap_or(&path).display());
}
write_all(&dir, root, &plugin_files::package(&package))?;
println!(
"→ next: fill in the Runtimes table in README.md, then `deno test` and `deno publish`"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
fn opts(name: Option<&str>) -> Opts {
Opts {
name: name.map(str::to_string),
package: None,
folder: None,
scope: None,
registry: None,
npm_name: None,
check: false,
}
}
/// A NAME passed on the command line is checked before any question: nobody should answer
/// "package?" and "folder?" to learn the name was never going to work. With no answers
/// scripted, asking anything would end in an end-of-input error instead.
#[test]
fn a_bad_name_fails_before_any_question() {
let mut ask = Ask::new(true, Cursor::new(Vec::new()), Vec::new());
let err = run_with(opts(Some("🍵")), &mut ask, Path::new("/nonexistent")).unwrap_err();
assert!(
err.to_string().contains("does not make a plugin name"),
"{err}"
);
}
#[test]
fn write_all_reports_what_it_wrote_before_failing() {
let d = tempfile::tempdir().unwrap();
let files = vec![
("a".to_string(), "x".to_string()),
("a/b".to_string(), "y".to_string()),
];
let err = write_all(d.path(), d.path(), &files).unwrap_err();
assert!(err.to_string().contains("already written: a"), "{err}");
}
}
+17 -1
View File
@@ -47,7 +47,23 @@ fn main() {
registry,
npm_name,
} => {
let result = if kind == "plugin" {
let stray: Vec<&str> = [
("--package", package.is_some()),
("--folder", folder.is_some()),
("--scope", scope.is_some()),
("--registry", registry.is_some()),
("--npm-name", npm_name.is_some()),
]
.into_iter()
.filter(|(_, on)| *on)
.map(|(flag, _)| flag)
.collect();
let result = if kind != "plugin" && !stray.is_empty() {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{} only apply to create plugin", stray.join(", ")),
))
} else if kind == "plugin" {
cmd_plugin::run(cmd_plugin::Opts {
name,
package,
+48 -2
View File
@@ -65,6 +65,7 @@ pub fn package(p: &Package) -> Vec<(String, String)> {
"CHANGELOG.md".to_string(),
"# Changelog\n\n## [Unreleased]\n\n- First version.\n".to_string(),
),
("LICENSE".to_string(), license(p)),
(
".gitignore".to_string(),
"node_modules\ndist\n.DS_Store\n".to_string(),
@@ -91,7 +92,7 @@ fn deno_json(p: &Package) -> String {
"test": "deno test --allow-env --allow-read"
}},
"publish": {{
"include": ["src", "README.md", "CHANGELOG.md", "deno.json"]
"include": ["src", "README.md", "CHANGELOG.md", "LICENSE", "deno.json"]
}}
}}
"#,
@@ -112,13 +113,15 @@ fn package_json(p: &Package) -> String {
"name": "{name}",
"version": "0.1.0",
"private": true,
"license": "MIT",
"type": "module",
{ENGINES}
"scripts": {{
"test": "node --test test/*.test.ts"
}},
"devDependencies": {{
"@green-tea/core": "{CORE_VERSION}"
"@green-tea/core": "{CORE_VERSION}",
"@types/node": "^22"
}}
}}
"#,
@@ -145,6 +148,7 @@ fn package_json(p: &Package) -> String {
}},
"devDependencies": {{
"@green-tea/core": "{CORE_VERSION}",
"@types/node": "^22",
"typescript": "^5"
}}
}}
@@ -197,6 +201,43 @@ test('two instances under one name are refused', () => {{
)
}
/// MIT as a starting point, which the README tells the author to change. The
/// holder is the scope, the closest thing to an author matcha knows.
fn license(p: &Package) -> String {
// Whole years since the epoch, averaged over leap years: a copyright line
// needs the year, not the date, and this needs no dependency.
let year = 1970
+ std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() / 31_556_952)
.unwrap_or(0);
let scope = &p.scope;
format!(
"MIT License
Copyright (c) {year} {scope}
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.
"
)
}
fn readme(p: &Package) -> String {
let jsr = p.jsr_name();
let fun = camel(&p.slug);
@@ -239,6 +280,11 @@ import {{ {fun} }} from '{jsr}';
const app = createApp({{ modules: [AppModule], plugins: [{fun}()] }});
```
## License
MIT, as generated. Change `LICENSE` and the `license` fields in `deno.json` and `package.json`
if you publish under another.
## List it
Once it is published, add it to the green-tea plugin listing: https://green-tea.expressive-tea.io/plugins/#contribute
+36 -1
View File
@@ -261,7 +261,7 @@ pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option<String> {
fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> Option<String> {
if let Some((open, close)) = find_key_array_span(object, src, key) {
let inner = &src[open + 1..close];
if inner.split(',').map(str::trim).any(|s| s == symbol) {
if array_elements(object, src, key).iter().any(|e| e == symbol) {
return Some(src.to_string()); // idempotent
}
let joined = if inner.trim().is_empty() {
@@ -305,6 +305,32 @@ fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) ->
}
}
/// The text of each element of `object`'s `key: [...]` array, read from the
/// parse tree: `algo({ a: 1, b: 2 })` is one element, which a split on `,` is not.
fn array_elements(object: Node, src: &str, key: &str) -> Vec<String> {
let mut c = object.walk();
for pair in object.named_children(&mut c) {
let is_key = pair.kind() == "pair"
&& pair
.child_by_field_name("key")
.and_then(|k| k.utf8_text(src.as_bytes()).ok())
== Some(key);
let Some(array) = pair
.child_by_field_name("value")
.filter(|v| is_key && v.kind() == "array")
else {
continue;
};
let mut ac = array.walk();
return array
.named_children(&mut ac)
.filter_map(|e| e.utf8_text(src.as_bytes()).ok())
.map(|t| t.split_whitespace().collect::<Vec<_>>().join(" "))
.collect();
}
Vec::new()
}
/// True when `object` has any direct `pair` child whose key text equals `key`,
/// regardless of the value's kind. Used to avoid creating a duplicate key when
/// an existing pair's value isn't an array literal.
@@ -473,6 +499,15 @@ fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option<Node<'a>> {
#[cfg(test)]
mod tests {
#[test]
fn an_element_with_commas_inside_is_still_one_element() {
let src = "const app = createApp({ plugins: [algo({ a: 1, b: 2 })] });\n";
assert_eq!(
add_to_createapp(src, "plugins", "algo({ a: 1, b: 2 })").as_deref(),
Some(src)
);
}
#[test]
fn binds_sees_identifiers_not_strings_or_comments() {
let src = "import { createApp } from '@green-tea/core';\n// green tea\nexport const app = createApp({});\n";