fix(plugin): close the review's gaps in names, prompts and the generated test
The collision check scanned the whole file as text, so every scaffolded app refused `core`, `tea` or `module` because they appear inside import strings. It now reads identifiers from the parse tree. Typing `npm` at the registry question silently produced a JSR-only package. An answer that is not offered is now asked again. The generated test only awaited boot(); it now checks the plugin's token is in app.graph(), and fails if it is not. engines.node moves to >=22.18, the first Node that runs `node --test` on .ts unflagged. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+163
-29
No files matched your search
+63
@@ -63,6 +63,32 @@ impl<R: BufRead, W: Write> Ask<R, W> {
|
||||
})
|
||||
}
|
||||
|
||||
/// One of `choices`, each `(key, value)`: the answer may be the key or the
|
||||
/// value, and Enter takes `default`. Anything else is asked again. Quietly
|
||||
/// taking the default would turn a typed `npm` into a JSR-only package.
|
||||
pub fn choice(
|
||||
&mut self,
|
||||
question: &str,
|
||||
choices: &[(&str, &'static str)],
|
||||
default: &'static str,
|
||||
flag: &str,
|
||||
) -> io::Result<&'static str> {
|
||||
if !self.interactive {
|
||||
return Ok(default);
|
||||
}
|
||||
let keys: Vec<&str> = choices.iter().map(|(k, _)| *k).collect();
|
||||
loop {
|
||||
let answer = self.line(question)?.to_lowercase();
|
||||
if answer.is_empty() {
|
||||
return Ok(default);
|
||||
}
|
||||
if let Some((_, v)) = choices.iter().find(|(k, v)| answer == *k || answer == *v) {
|
||||
return Ok(v);
|
||||
}
|
||||
writeln!(self.output, "answer {} (or pass {flag})", keys.join(" or "))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// `flag` names what to pass instead, for the error off a TTY.
|
||||
pub fn text(
|
||||
&mut self,
|
||||
@@ -145,6 +171,43 @@ mod tests {
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_asks_again_on_an_answer_that_is_not_offered() {
|
||||
let mut ask = scripted("npm\n3\n2\n");
|
||||
let picked = ask
|
||||
.choice(
|
||||
"Publish to:",
|
||||
&[("1", "jsr"), ("2", "both")],
|
||||
"jsr",
|
||||
"--registry",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(picked, "both");
|
||||
let shown = String::from_utf8(ask.output.clone()).unwrap();
|
||||
assert!(shown.contains("answer 1 or 2"), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_takes_the_default_on_enter_and_off_a_tty() {
|
||||
let choices = [("1", "jsr"), ("2", "both")];
|
||||
assert_eq!(
|
||||
scripted("\n")
|
||||
.choice("P?", &choices, "jsr", "--registry")
|
||||
.unwrap(),
|
||||
"jsr"
|
||||
);
|
||||
assert_eq!(
|
||||
scripted("both\n")
|
||||
.choice("P?", &choices, "jsr", "--registry")
|
||||
.unwrap(),
|
||||
"both"
|
||||
);
|
||||
assert_eq!(
|
||||
piped().choice("P?", &choices, "jsr", "--registry").unwrap(),
|
||||
"jsr"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_a_tty_nothing_is_asked() {
|
||||
let mut ask = piped();
|
||||
|
||||
+8
-12
@@ -96,7 +96,7 @@ fn in_app<R: BufRead, W: Write>(opts: Opts, ask: &mut Ask<R, W>, root: &Path) ->
|
||||
let src = std::fs::read_to_string(&entry_path)?;
|
||||
// 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 naming::used_in(&src, &fun) {
|
||||
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()
|
||||
@@ -193,17 +193,13 @@ fn package_mode<R: BufRead, W: Write>(
|
||||
Some(r) => r,
|
||||
None => {
|
||||
ask.say(&format!("\n{}\n", plugin_files::JSR_BANNER))?;
|
||||
match ask
|
||||
.text(
|
||||
"Publish to: (1) JSR only (2) JSR + npm",
|
||||
Some("1"),
|
||||
"--registry",
|
||||
)?
|
||||
.as_str()
|
||||
{
|
||||
"2" | "both" => "both".to_string(),
|
||||
_ => "jsr".to_string(),
|
||||
}
|
||||
ask.choice(
|
||||
"Publish to: (1) JSR only [default] (2) JSR + npm",
|
||||
&[("1", "jsr"), ("2", "both")],
|
||||
"jsr",
|
||||
"--registry",
|
||||
)?
|
||||
.to_string()
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -110,16 +110,6 @@ pub fn is_reserved(ident: &str) -> bool {
|
||||
RESERVED.contains(&ident)
|
||||
}
|
||||
|
||||
/// True when `ident` appears as a whole identifier anywhere in `src`.
|
||||
///
|
||||
/// ponytail: a token scan, not a parse, so a match inside a comment or a string
|
||||
/// also counts. That refuses a name that would have been fine, never the other
|
||||
/// way round; a scope-aware check is the upgrade if it ever gets in the way.
|
||||
pub fn used_in(src: &str, ident: &str) -> bool {
|
||||
src.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
|
||||
.any(|token| token == ident)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -149,11 +139,6 @@ mod tests {
|
||||
assert!(is_reserved("delete"));
|
||||
assert!(is_reserved("class"));
|
||||
assert!(!is_reserved("pluginAlgo"));
|
||||
let src = "import { createApp } from 'x';\nexport const app = createApp({});\n";
|
||||
assert!(used_in(src, "createApp"));
|
||||
assert!(used_in(src, "app"));
|
||||
assert!(!used_in(src, "appModule"));
|
||||
assert!(!used_in(src, "create"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+3
-2
@@ -100,7 +100,7 @@ fn deno_json(p: &Package) -> String {
|
||||
}
|
||||
|
||||
const ENGINES: &str = r#" "engines": {
|
||||
"node": ">=22",
|
||||
"node": ">=22.18",
|
||||
"deno": ">=2",
|
||||
"bun": ">=1.3"
|
||||
},"#;
|
||||
@@ -179,9 +179,10 @@ import {{ createApp }} from '@green-tea/core';
|
||||
|
||||
import {{ {fun} }} from '../src/index.ts';
|
||||
|
||||
test('mounts into an app, and the app boots', async () => {{
|
||||
test('mounts, boots, and puts its token in the graph', async () => {{
|
||||
const app = createApp({{ modules: [], plugins: [{fun}()] }});
|
||||
await app.boot();
|
||||
assert.ok(app.graph().nodes.some((node) => node.provides.includes('{slug}')));
|
||||
}});
|
||||
|
||||
test('two instances mount side by side under different tokens', async () => {{
|
||||
|
||||
+31
@@ -215,6 +215,27 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option<String>
|
||||
insert_into_object_array(src, object, key, symbol)
|
||||
}
|
||||
|
||||
/// True when `ident` is an identifier anywhere in `src`: an import, a
|
||||
/// declaration or a use. Read from the parse tree, so a word inside a string
|
||||
/// (`'@green-tea/core'`) or a comment does not count; those are not bindings
|
||||
/// and cannot collide.
|
||||
pub fn binds(src: &str, ident: &str) -> bool {
|
||||
fn visit(node: Node, src: &str, ident: &str) -> bool {
|
||||
if matches!(
|
||||
node.kind(),
|
||||
"identifier" | "type_identifier" | "shorthand_property_identifier_pattern"
|
||||
) && node.utf8_text(src.as_bytes()).ok() == Some(ident)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let mut c = node.walk();
|
||||
let found = node.children(&mut c).any(|child| visit(child, src, ident));
|
||||
found
|
||||
}
|
||||
let tree = parser().parse(src, None).unwrap();
|
||||
visit(tree.root_node(), src, ident)
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
@@ -452,6 +473,16 @@ fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option<Node<'a>> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[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";
|
||||
assert!(binds(src, "createApp"));
|
||||
assert!(binds(src, "app"));
|
||||
assert!(!binds(src, "core"));
|
||||
assert!(!binds(src, "green"));
|
||||
assert!(!binds(src, "appModule"));
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
const MOD: &str = r#"import { Module } from '@green-tea/core';
|
||||
|
||||
@@ -409,3 +409,61 @@ fn in_app_refuses_a_factory_name_the_entry_already_uses() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The scaffolded app.ts imports from '@green-tea/core' and './app.module'. Words inside those
|
||||
/// strings are not bindings, so `core`, `tea` and `module` are free names for a plugin.
|
||||
#[test]
|
||||
fn words_inside_strings_and_comments_are_not_collisions() {
|
||||
let app = "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\n// the green tea app\nexport const app = createApp({ modules: [AppModule] });\n";
|
||||
for name in ["core", "tea", "module", "green"] {
|
||||
let d = project(app);
|
||||
matcha(d.path())
|
||||
.args(["create", "plugin", name])
|
||||
.assert()
|
||||
.success();
|
||||
assert!(
|
||||
d.path().join(format!("plugins/{name}/index.ts")).exists(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_engines_need_the_node_that_strips_types() {
|
||||
let d = tempdir().unwrap();
|
||||
matcha(d.path())
|
||||
.args([
|
||||
"create",
|
||||
"plugin",
|
||||
"algo",
|
||||
"--package",
|
||||
"p",
|
||||
"--scope",
|
||||
"acme",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap();
|
||||
// `node --test test/*.test.ts` needs unflagged type stripping, which is 22.18+.
|
||||
assert!(pj.contains("\"node\": \">=22.18\""), "{pj}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
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",
|
||||
])
|
||||
.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}");
|
||||
}
|
||||
Reference in new issue
Block a user