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

+1 -1
View File
@@ -14,7 +14,7 @@ is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says w
### Added
- **`matcha create plugin`.** By default it scaffolds an in-app plugin in a folder of its own,
`plugins/<name>/`, and registers it in `createApp({ plugins })`. With `--package [DIR]` it writes
`plugins/<name>/`, and registers it in `createApp({ plugins })`. With `--package` (or `--package=DIR`) it writes
a package instead. JSR is the default, and `--registry both` adds an ESM-only npm build. The
package passes `deno test`, `node --test`, `bun test` and `deno publish --dry-run` as generated.
At a terminal it asks for what the flags leave out. Without one it takes the defaults, and fails
+7 -6
View File
@@ -119,18 +119,19 @@ An in-app plugin by default, or a package of its own.
```sh
matcha create plugin "Plugin Algo" # plugins/plugin-algo/, registered in createApp
matcha create plugin algo --folder lib/plugins
matcha create plugin algo --package ./algo --scope acme # a JSR package
matcha create plugin algo --package ./algo --scope acme --registry both # JSR + npm, ESM only
matcha create plugin algo --package=./algo --scope acme # a JSR package
matcha create plugin algo --package=./algo --scope acme --registry both # JSR + npm, ESM only
```
In-app, each plugin gets a folder of its own under `plugins/` (or `--folder`, relative to the
project root) and is registered in `createApp({ plugins })`. It lives in a folder so it can become
a package later without being pulled out of the app.
`--package [DIR]` writes a package into `DIR`, or into the current directory, and either one has to
be empty. JSR is the default, because it records which runtimes a package supports.
`--registry both` adds npm with a `tsc` build to ESM only, and suggests the
`@scope/green-tea-<name>` name without requiring it. The package passes `deno test`, `node --test`,
`--package` writes a package into the current directory, or `--package=DIR` into `DIR`, and either
one has to be empty. The `=` is required, so a word after a bare `--package` is the plugin's
name. JSR is the default, because it records which runtimes a package supports. `--registry both`
adds npm with a `tsc` build to ESM only, and suggests the `@scope/green-tea-<name>` name without
requiring it. The package passes `deno test`, `node --test`,
`bun test` and `deno publish --dry-run` as generated.
At a terminal it asks for whatever the flags leave out. Without a terminal (CI, a pipe) it takes the
+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";
+188 -33
View File
@@ -169,8 +169,7 @@ fn package_jsr_writes_the_tree_into_dir() {
"create",
"plugin",
"Plugin Algo",
"--package",
"algo-pkg",
"--package=algo-pkg",
"--scope",
"@acme",
])
@@ -182,6 +181,7 @@ fn package_jsr_writes_the_tree_into_dir() {
[
".gitignore",
"CHANGELOG.md",
"LICENSE",
"README.md",
"deno.json",
"package.json",
@@ -217,8 +217,7 @@ fn package_both_adds_the_npm_build() {
"create",
"plugin",
"algo",
"--package",
"p",
"--package=p",
"--scope",
"acme",
"--registry",
@@ -247,8 +246,7 @@ fn both_package_json_is_esm_only() {
"create",
"plugin",
"algo",
"--package",
"p",
"--package=p",
"--scope",
"acme",
"--registry",
@@ -270,8 +268,7 @@ fn package_accepts_any_npm_name_and_notes_the_convention() {
"create",
"plugin",
"algo",
"--package",
"p",
"--package=p",
"--scope",
"acme",
"--registry",
@@ -312,7 +309,7 @@ fn package_in_an_empty_current_directory() {
fn package_off_a_tty_needs_a_scope() {
let d = tempdir().unwrap();
matcha(d.path())
.args(["create", "plugin", "algo", "--package", "p"])
.args(["create", "plugin", "algo", "--package=p"])
.assert()
.failure()
.stderr(contains("--scope"));
@@ -327,8 +324,7 @@ fn package_rejects_a_bad_scope_or_npm_name() {
"create",
"plugin",
"algo",
"--package",
"p",
"--package=p",
"--scope",
"Ac Me",
])
@@ -340,8 +336,7 @@ fn package_rejects_a_bad_scope_or_npm_name() {
"create",
"plugin",
"algo",
"--package",
"q",
"--package=q",
"--scope",
"acme",
"--registry",
@@ -379,8 +374,7 @@ fn a_package_whose_factory_would_be_a_reserved_word_writes_nothing() {
"create",
"plugin",
"delete",
"--package",
"p",
"--package=p",
"--scope",
"acme",
])
@@ -432,15 +426,7 @@ fn words_inside_strings_and_comments_are_not_collisions() {
fn package_engines_need_the_node_that_strips_types() {
let d = tempdir().unwrap();
matcha(d.path())
.args([
"create",
"plugin",
"algo",
"--package",
"p",
"--scope",
"acme",
])
.args(["create", "plugin", "algo", "--package=p", "--scope", "acme"])
.assert()
.success();
let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap();
@@ -452,18 +438,187 @@ fn package_engines_need_the_node_that_strips_types() {
fn the_generated_test_asserts_the_token_is_in_the_graph() {
let d = tempdir().unwrap();
matcha(d.path())
.args([
"create",
"plugin",
"algo",
"--package",
"p",
"--scope",
"acme",
])
.args(["create", "plugin", "algo", "--package=p", "--scope", "acme"])
.assert()
.success();
let t = std::fs::read_to_string(d.path().join("p/test/algo.test.ts")).unwrap();
assert!(t.contains("app.graph()"), "{t}");
assert!(t.contains("provides.includes('algo')"), "{t}");
}
#[test]
fn package_into_a_path_that_is_a_file_names_it() {
let d = tempdir().unwrap();
std::fs::write(d.path().join("taken"), "x").unwrap();
matcha(d.path())
.args([
"create",
"plugin",
"algo",
"--package=taken",
"--scope",
"acme",
])
.assert()
.failure()
.stderr(contains("taken is a file"));
}
#[test]
fn the_empty_directory_error_names_the_directory() {
let d = tempdir().unwrap();
std::fs::create_dir_all(d.path().join("busy")).unwrap();
std::fs::write(d.path().join("busy/keep.txt"), "x").unwrap();
matcha(d.path())
.args([
"create",
"plugin",
"algo",
"--package=busy",
"--scope",
"acme",
])
.assert()
.failure()
.stderr(contains("busy: a plugin package needs an empty directory"));
}
#[cfg(unix)]
#[test]
fn in_app_leaves_nothing_behind_when_the_entry_cannot_be_written() {
use std::os::unix::fs::PermissionsExt;
let d = project(APP);
let entry = d.path().join("src/app.ts");
std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o444)).unwrap();
matcha(d.path())
.args(["create", "plugin", "algo"])
.assert()
.failure();
std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o644)).unwrap();
assert!(
!d.path().join("plugins/algo").exists(),
"the plugin folder is rolled back"
);
assert_eq!(std::fs::read_to_string(&entry).unwrap(), APP);
}
#[test]
fn folder_dot_and_leading_dot_slash_give_clean_imports() {
let d = project(APP);
matcha(d.path())
.args(["create", "plugin", "algo", "--folder", "."])
.assert()
.success();
assert!(d.path().join("algo/index.ts").exists());
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
assert!(app.contains("from '../algo/index'"), "{app}");
let d = project(APP);
matcha(d.path())
.args(["create", "plugin", "algo", "--folder", "./plugins/"])
.assert()
.success();
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
assert!(app.contains("from '../plugins/algo/index'"), "{app}");
}
#[test]
fn plugin_flags_on_another_kind_are_an_error() {
let d = project(APP);
matcha(d.path())
.args(["create", "controller", "Users", "--scope", "acme"])
.assert()
.failure()
.stderr(contains("only apply to create plugin"));
assert!(!d.path().join("src/controllers").exists());
}
#[test]
fn flags_for_the_other_mode_are_named_as_ignored() {
let d = project(APP);
matcha(d.path())
.args(["create", "plugin", "algo", "--scope", "acme"])
.assert()
.success()
.stdout(contains("--scope only applies to --package; ignored"));
let d = tempdir().unwrap();
matcha(d.path())
.args([
"create",
"plugin",
"algo",
"--package",
"--scope",
"acme",
"--folder",
"x",
"--check",
])
.assert()
.success()
.stdout(contains(
"--folder only applies to an in-app plugin; ignored",
))
.stdout(contains(
"--check only applies to an in-app plugin; ignored",
));
}
/// `--package algo` used to take `algo` as the directory. It now needs `--package=DIR`, so a
/// bare word after `--package` is the plugin's name.
#[test]
fn a_word_after_package_is_the_name_not_the_directory() {
let d = tempdir().unwrap();
matcha(d.path())
.args(["create", "plugin", "--package", "algo", "--scope", "acme"])
.assert()
.success();
let deno = std::fs::read_to_string(d.path().join("deno.json")).unwrap();
assert!(deno.contains("\"name\": \"@acme/algo\""), "{deno}");
}
#[test]
fn scopes_jsr_would_refuse_are_refused() {
for scope in ["-", "-acme", "a", "abcdefghijklmnopqrstu"] {
let d = tempdir().unwrap();
matcha(d.path())
// `=` so a leading hyphen is a value, not another flag.
.args([
"create",
"plugin",
"algo",
"--package",
&format!("--scope={scope}"),
])
.assert()
.failure()
.stderr(contains("is not a JSR scope"));
assert!(!d.path().join("deno.json").exists(), "{scope}");
}
}
#[test]
fn packages_ship_a_license_and_node_types() {
for registry in ["jsr", "both"] {
let d = tempdir().unwrap();
matcha(d.path())
.args([
"create",
"plugin",
"algo",
"--package",
"--scope",
"acme",
"--registry",
registry,
])
.assert()
.success();
let license = std::fs::read_to_string(d.path().join("LICENSE")).unwrap();
assert!(license.starts_with("MIT License"), "{registry}");
let pj = std::fs::read_to_string(d.path().join("package.json")).unwrap();
assert!(pj.contains("\"license\": \"MIT\""), "{registry}: {pj}");
assert!(pj.contains("\"@types/node\""), "{registry}: {pj}");
}
}