diff --git a/crates/ide-host/src/ops/bdd.rs b/crates/ide-host/src/ops/bdd.rs index 7413f1a2f..e8043abd0 100644 --- a/crates/ide-host/src/ops/bdd.rs +++ b/crates/ide-host/src/ops/bdd.rs @@ -1,5 +1,6 @@ //! Cucumber sources: the project's `.feature` files and the JavaScript / TypeScript files -//! that could define steps (`@cucumber/cucumber`, `playwright-bdd`), with their text. The UI +//! (`@cucumber/cucumber`, `playwright-bdd`) and Java / Kotlin files (cucumber-jvm's +//! `@Given("…")` annotations and Java 8 lambdas) that could define steps, with their text. The UI //! owns the Gherkin and step-expression parsing and the index it feeds (as for `routes`), //! so this side stays a cheap scan. @@ -37,7 +38,7 @@ fn is_feature(path: &Path) -> bool { fn is_script(path: &Path) -> bool { matches!( path.extension().and_then(|e| e.to_str()), - Some("js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts") + Some("js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts" | "java" | "kt") ) } @@ -100,13 +101,15 @@ mod tests { std::fs::write(root.join("steps/bdd.mjs"), "const { When } = createBdd();\nWhen(/^I add (\\d+)$/, f);") .unwrap(); std::fs::write(root.join("src/app.ts"), "export const app = 1;").unwrap(); + std::fs::write(root.join("src/CartSteps.java"), "@Given(\"an empty cart\")\npublic void empty() {}").unwrap(); + std::fs::write(root.join("src/App.java"), "class App {}").unwrap(); std::fs::write(root.join("src/notes.md"), "Given('x')").unwrap(); std::fs::write(root.join("node_modules/@cucumber/cucumber/lib/index.js"), "Given('x')").unwrap(); let files = sources_in(root, &["node_modules".to_owned()]); let names: Vec = files.iter().map(|f| f.path.0.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/")).collect(); - assert_eq!(names, ["features/cart.feature", "steps/bdd.mjs", "steps/cart.steps.ts"]); + assert_eq!(names, ["features/cart.feature", "src/CartSteps.java", "steps/bdd.mjs", "steps/cart.steps.ts"]); assert!(files[0].feature && !files[1].feature); - assert!(files[2].text.contains("an empty cart")); + assert!(files[3].text.contains("an empty cart")); } } diff --git a/src/features/cucumber/index.ts b/src/features/cucumber/index.ts index 7b9b8e0e7..23be341be 100644 --- a/src/features/cucumber/index.ts +++ b/src/features/cucumber/index.ts @@ -1,9 +1,10 @@ /** - * Cucumber steps: Go to Declaration (⌘-click, ⌘B) on a `.feature` step opens its JavaScript / - * TypeScript step definitions, and on a definition's pattern lists the feature steps it + * Cucumber steps: Go to Declaration (⌘-click, ⌘B) on a `.feature` step opens its step + * definitions (JavaScript / TypeScript, and cucumber-jvm's Java / Kotlin), and on a definition's pattern lists the feature steps it * matches. Steps no definition matches are reported (Undefined step), with a quick fix that * writes a pending definition into the project's step file. */ +import { Text } from "@codemirror/state"; import { ViewPlugin, type EditorView } from "@codemirror/view"; import { intentionProviders, @@ -22,7 +23,15 @@ import { tx } from "@/platform/i18n"; import { CUCUMBER_UNDEFINED_STEP_PRODUCER } from "@/platform/inspections"; import { call, commands, onIdeEvent } from "@/platform/ipc"; import { editorService, notifications } from "@/workbench/contributions"; -import { definingKeyword, featureSteps, stepDefinitions, stepSnippet, type FeatureStep } from "./steps"; +import { + definingKeyword, + definitionInsertions, + featureSteps, + snippetStyle, + stepDefinitions, + stepSnippet, + type FeatureStep, +} from "./steps"; import { clearStepIndex, definitionFileFor, @@ -32,7 +41,7 @@ import { usagesOf, } from "./stepIndex"; -const SCRIPT = /\.[cm]?[jt]sx?$/i; +const SCRIPT = /\.(?:[cm]?[jt]sx?|java|kt)$/i; const FEATURE = /\.feature$/i; const DELAY_MS = 300; @@ -62,21 +71,27 @@ async function createDefinition(featurePath: string, all: readonly FeatureStep[] cursor?.path === target ? (await call(commands.docSnapshot(cursor.doc))).text : await call(commands.fsReadText(target)); - const lines = text.split("\n"); - const end = { line: lines.length - 1, col: lines[lines.length - 1]!.length }; - const lead = text.length === 0 ? "" : text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n"; - const style = /\bcreateBdd\s*\(/.test(text) ? "playwright-bdd" : "cucumber"; - const snippet = stepSnippet(definingKeyword(all, step), step.matchText, style); + const style = snippetStyle(target, text); + const keyword = definingKeyword(all, step); + const snippet = stepSnippet(keyword, step.matchText, style); + const { insertions, select } = definitionInsertions(text, keyword, snippet, style); + const lines = Text.of(text.split("\n")); await whenAllSynced(); await call( commands.applyWorkspaceEdit({ - files: [{ kind: "edit", path: target, edits: [{ range: { start: end, end }, new_text: lead + snippet.text }] }], + files: [ + { + kind: "edit", + path: target, + edits: insertions.map((i) => ({ range: offsetsToRange(lines, i.at, i.at), new_text: i.text })), + }, + ], }), ); - // The body line (the pending return, or the comment) is selected. - const line = end.line + lead.split("\n").length - 1 + snippet.body; - const body = snippet.text.split("\n")[snippet.body]!; - await editorService().openFile(target, { selection: { line, col: 2, endLine: line, endCol: body.length } }); + // The body line (the pending return or exception, or the comment) is selected. + await editorService().openFile(target, { + selection: { line: select.line, col: select.from, endLine: select.line, endCol: select.to }, + }); } catch (e) { notifications().notify({ group: "cucumber", diff --git a/src/features/cucumber/stepIndex.ts b/src/features/cucumber/stepIndex.ts index b9b168b00..16f9236c8 100644 --- a/src/features/cucumber/stepIndex.ts +++ b/src/features/cucumber/stepIndex.ts @@ -18,7 +18,7 @@ let cached: Promise | null = null; /** Whether a change to `path` can change the index: a feature or script file. */ export function isCucumberSource(path: string): boolean { - return /\.(feature|[cm]?[jt]sx?)$/i.test(path); + return /\.(feature|[cm]?[jt]sx?|java|kt)$/i.test(path); } /** Forgets the index, so the next lookup rescans the project. */ @@ -93,7 +93,13 @@ export async function undefinedSteps(steps: readonly FeatureStep[]): Promise { const { definitions } = await stepIndex(); - const stem = (path: string) => (path.split("/").pop() ?? "").split(".")[0]!.toLowerCase(); + // `cart.steps.ts`, `CartSteps.java` and `cart_stepdefs.kt` all name the `cart` feature's steps. + const stem = (path: string) => + (path.split("/").pop() ?? "") + .split(".")[0]! + .toLowerCase() + .replace(/[^a-z0-9]/g, "") + .replace(/(?:stepdefinitions|stepdefs|steps)$/, ""); const feature = stem(featurePath); const named = definitions.find((file) => stem(file.path) === feature); if (named) return named.path; diff --git a/src/features/cucumber/steps.test.ts b/src/features/cucumber/steps.test.ts index 0a34bd568..d34054c90 100644 --- a/src/features/cucumber/steps.test.ts +++ b/src/features/cucumber/steps.test.ts @@ -1,5 +1,14 @@ import { describe, expect, it } from "vitest"; -import { definingKeyword, expressionRegExp, featureSteps, matchesStep, stepDefinitions, stepSnippet } from "./steps"; +import { + definingKeyword, + definitionInsertions, + expressionRegExp, + featureSteps, + matchesStep, + snippetStyle, + stepDefinitions, + stepSnippet, +} from "./steps"; const STEPS = `import { Given, When, Then } from "@cucumber/cucumber"; import { createBdd } from "playwright-bdd"; @@ -135,3 +144,63 @@ describe("definingKeyword", () => { expect(steps.map((s) => definingKeyword(steps, s))).toEqual(["Given", "Given", "When", "When", "Then", "Then"]); }); }); + +describe("cucumber-jvm", () => { + const step = (text: string) => featureSteps(`Feature: f\n Scenario: s\n Given ${text}\n`)[0]!; + const JAVA = `package shop; + +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; + +public class CartSteps { + @Given("an empty cart") + public void emptyCart() {} + + @Then("^the total is (\\\\d+\\\\.\\\\d+) EUR$") + public void total(String amount) {} +} +`; + + it("reads annotation patterns, anchored strings as regular expressions", () => { + const definitions = stepDefinitions(JAVA); + expect(definitions.map((d) => d.source)).toEqual(["an empty cart", "^the total is (\\d+\\.\\d+) EUR$"]); + expect(matchesStep(definitions[1]!, step("the total is 3.50 EUR"))).toBe(true); + expect(matchesStep(definitions[0]!, step("an empty cart"))).toBe(true); + }); + + it("writes a Java method into the class with the keyword's import", () => { + const snippet = stepSnippet("When", `I pay 12 "EUR" for 2.5 kg (net)`, "java"); + expect(snippet.text).toBe( + [ + ' @When("I pay {int} {string} for {double} kg \\\\(net\\\\)")', + " public void i_pay_for_kg_net(Integer int1, String string, Double double1) {", + " // Write code here that turns the phrase above into concrete actions", + " throw new io.cucumber.java.PendingException();", + " }", + "", + ].join("\n"), + ); + const { insertions, select } = definitionInsertions(JAVA, "When", snippet, "java"); + let out = JAVA; + for (const i of [...insertions].sort((a, b) => b.at - a.at)) out = out.slice(0, i.at) + i.text + out.slice(i.at); + expect(out).toContain("import io.cucumber.java.en.Then;\nimport io.cucumber.java.en.When;\n"); + expect( + out.endsWith(" public void total(String amount) {}\n\n" + snippet.text.replace(/\n$/, "") + "\n}\n"), + ).toBe(true); + expect(out.split("\n")[select.line]!.slice(select.from, select.to)).toBe( + "throw new io.cucumber.java.PendingException();", + ); + const created = stepDefinitions(out).find((d) => d.source.startsWith("I pay"))!; + expect(matchesStep(created, step(`I pay 12 "EUR" for 2.5 kg (net)`))).toBe(true); + }); + + it("writes Kotlin in camel case and escapes $", () => { + const snippet = stepSnippet("Given", "a $5 coupon", "kotlin"); + expect(snippet.text.split("\n").slice(0, 2)).toEqual([ + ' @Given("a \\${int} coupon")', + " fun aCoupon(int1: Int) {", + ]); + expect(snippetStyle("src/test/kotlin/CartSteps.kt", "")).toBe("kotlin"); + expect(snippetStyle("steps/cart.steps.ts", "createBdd()")).toBe("playwright-bdd"); + }); +}); diff --git a/src/features/cucumber/steps.ts b/src/features/cucumber/steps.ts index 2094575cf..985c8a83a 100644 --- a/src/features/cucumber/steps.ts +++ b/src/features/cucumber/steps.ts @@ -5,7 +5,10 @@ * expression matching between them. */ -/** A step definition: the pattern literal of a `Given` / `When` / `Then` / `Step` call. */ +/** + * A step definition: the pattern literal of a `Given` / `When` / `Then` / `Step` call, or of a + * cucumber-jvm `@Given("…")` annotation. + */ export interface StepDefinition { /** Offsets of the literal (quotes or slashes included) in its file. */ from: number; @@ -36,12 +39,26 @@ export function stepDefinitions(text: string): StepDefinition[] { const at = m.index + m[0].length; const literal = readLiteral(text, at); if (!literal) continue; - const regexp = literal.regexp ?? expressionRegExp(literal.value); + const regexp = literal.regexp ?? stringPattern(literal.value); if (regexp) out.push({ from: at, to: literal.end, source: literal.value, regexp }); } return out; } +/** + * The pattern of a string: a regular expression when it is anchored with `^` or `$` (how + * Cucumber's expression factory tells them apart, and how cucumber-jvm annotations write them), + * else a Cucumber expression. + */ +function stringPattern(value: string): RegExp | null { + if (!value.startsWith("^") && !value.endsWith("$")) return expressionRegExp(value); + try { + return new RegExp(value); + } catch { + return null; + } +} + /** A string, template (without substitutions) or regular expression literal at `at`. */ function readLiteral(text: string, at: number): { value: string; end: number; regexp?: RegExp } | null { const quote = text[at]; @@ -218,47 +235,118 @@ export function definingKeyword(steps: readonly FeatureStep[], step: FeatureStep /** Strings and numbers of a step's text, as Cucumber's snippets turn them into parameters. */ const SNIPPET_PARAMETER = /(^|[^\w.-])("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|-?\d+\.\d+|-?\d+)(?![\w.])/g; -/** `text` as a Cucumber expression inside a single-quoted JavaScript string. */ -const expressionText = (text: string) => text.replace(/[\\(){}/]/g, "\\\\$&").replace(/'/g, "\\'"); +export type SnippetStyle = "cucumber" | "playwright-bdd" | "java" | "kotlin"; + +/** The snippet style of a step definition file. */ +export function snippetStyle(path: string, text: string): SnippetStyle { + if (/\.java$/i.test(path)) return "java"; + if (/\.kts?$/i.test(path)) return "kotlin"; + return /\bcreateBdd\s*\(/.test(text) ? "playwright-bdd" : "cucumber"; +} + +/** `text` as a Cucumber expression inside a string literal of the snippet's language. */ +function expressionText(text: string, style: SnippetStyle): string { + const escaped = text.replace(/[\\(){}/]/g, "\\\\$&"); + if (style === "java") return escaped.replace(/"/g, '\\"'); + if (style === "kotlin") return escaped.replace(/"/g, '\\"').replace(/\$/g, "\\$"); + return escaped.replace(/'/g, "\\'"); +} + +/** cucumber-jvm's method name for a step: its words without the parameters, in snake case (camel case in Kotlin). */ +function methodName(words: string, style: "java" | "kotlin"): string { + const parts = words + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter(Boolean); + if (!parts.length) return "step"; + const name = + style === "java" + ? parts.join("_") + : parts[0]! + + parts + .slice(1) + .map((p) => p[0]!.toUpperCase() + p.slice(1)) + .join(""); + return /^\d/.test(name) ? `_${name}` : name; +} + +const COMMENT = "// Write code here that turns the phrase above into concrete actions"; /** * The step definition Cucumber suggests for an undefined step: its strings and numbers become - * `{string}`, `{float}` and `{int}` parameters of a pending step. `playwright-bdd` steps take - * the fixtures first. `body` is the line (0-based) of the snippet the caret goes to. + * `{string}`, `{float}` (`{double}` on the JVM) and `{int}` parameters of a pending step. + * `playwright-bdd` steps take the fixtures first; Java and Kotlin ones are annotated methods, + * indented for a class body. `body` is the line (0-based) of the snippet the caret goes to. */ export function stepSnippet( keyword: string, text: string, - style: "cucumber" | "playwright-bdd" = "cucumber", + style: SnippetStyle = "cucumber", ): { text: string; body: number } { + const jvm = style === "java" || style === "kotlin"; const types: string[] = []; let expression = ""; + let words = ""; let last = 0; for (const m of text.matchAll(SNIPPET_PARAMETER)) { const start = m.index + m[1]!.length; const value = m[2]!; - const type = /^["']/.test(value) ? "string" : value.includes(".") ? "float" : "int"; - expression += `${expressionText(text.slice(last, start))}{${type}}`; + const type = /^["']/.test(value) ? "string" : value.includes(".") ? (jvm ? "double" : "float") : "int"; + expression += `${expressionText(text.slice(last, start), style)}{${type}}`; + words += ` ${text.slice(last, start)}`; types.push(type); last = start + value.length; } - expression += expressionText(text.slice(last)); + expression += expressionText(text.slice(last), style); + words += ` ${text.slice(last)}`; const seen = new Map(); const names = types.map((type) => { const n = (seen.get(type) ?? 0) + 1; seen.set(type, n); - return n === 1 ? type : `${type}${n}`; + // cucumber-jvm numbers its int and double parameters from 1. + return type === "string" ? (n === 1 ? type : `${type}${n}`) : jvm ? `${type}${n}` : n === 1 ? type : `${type}${n}`; }); - const comment = " // Write code here that turns the phrase above into concrete actions"; + if (style === "java") { + const javaType: Record = { int: "Integer", double: "Double", string: "String" }; + const params = types.map((t, i) => `${javaType[t]} ${names[i]}`).join(", "); + return { + text: [ + ` @${keyword}("${expression}")`, + ` public void ${methodName(words, "java")}(${params}) {`, + ` ${COMMENT}`, + " throw new io.cucumber.java.PendingException();", + " }", + "", + ].join("\n"), + body: 3, + }; + } + if (style === "kotlin") { + const kotlinType: Record = { int: "Int", double: "Double", string: "String" }; + const params = types.map((t, i) => `${names[i]}: ${kotlinType[t]}`).join(", "); + return { + text: [ + ` @${keyword}("${expression}")`, + ` fun ${methodName(words, "kotlin")}(${params}) {`, + ` ${COMMENT}`, + " throw io.cucumber.java.PendingException()", + " }", + "", + ].join("\n"), + body: 3, + }; + } if (style === "playwright-bdd") return { - text: [`${keyword}('${expression}', async (${["{}", ...names].join(", ")}) => {`, comment, "});", ""].join("\n"), + text: [`${keyword}('${expression}', async (${["{}", ...names].join(", ")}) => {`, ` ${COMMENT}`, "});", ""].join( + "\n", + ), body: 1, }; return { text: [ `${keyword}('${expression}', async function (${names.join(", ")}) {`, - comment, + ` ${COMMENT}`, " return 'pending';", "});", "", @@ -266,3 +354,54 @@ export function stepSnippet( body: 2, }; } + +/** A text insertion at an offset of the file. */ +export interface Insertion { + at: number; + text: string; +} + +/** + * Where a definition goes in a step file: at its end, or before the closing brace of its class + * for Java and Kotlin, which also get the keyword's `io.cucumber.java.en` import when the file + * imports others from there. `select` is the body line's range in the file after the insertions. + */ +export function definitionInsertions( + fileText: string, + keyword: string, + snippet: { text: string; body: number }, + style: SnippetStyle, +): { insertions: Insertion[]; select: { line: number; from: number; to: number } } { + const insertions: Insertion[] = []; + let at: number; + let insert: string; + if (style === "java" || style === "kotlin") { + const close = fileText.lastIndexOf("}"); + at = close < 0 ? fileText.length : fileText.slice(0, close).trimEnd().length; + insert = `\n\n${snippet.text.replace(/\n$/, "")}`; + if (close >= 0 && !fileText.slice(at, close).includes("\n")) insert += "\n"; + const imports = [...fileText.matchAll(/^import\s+io\.cucumber\.java\.en\.(\w+);?[ \t]*$/gm)]; + if (imports.length && !imports.some((m) => m[1] === keyword || m[1] === "*")) { + const lastImport = imports[imports.length - 1]!; + const end = lastImport.index + lastImport[0].length; + const statement = ["import io.cucumber.java.en.", keyword, style === "java" ? ";" : ""].join(""); + insertions.push({ at: end, text: `\n${statement}` }); + } + } else { + at = fileText.length; + const lead = !fileText ? "" : fileText.endsWith("\n\n") ? "" : fileText.endsWith("\n") ? "\n" : "\n\n"; + insert = lead + snippet.text; + } + insertions.push({ at, text: insert }); + // The snippet's first line, counted in the file after every insertion before it. + const before = insertions.filter((i) => i.at < at).reduce((n, i) => n + (i.text.split("\n").length - 1), 0); + const snippetStart = insert.length - insert.trimStart().length; + const firstLine = + fileText.slice(0, at).split("\n").length - 1 + before + (insert.slice(0, snippetStart).split("\n").length - 1); + const bodyText = snippet.text.split("\n")[snippet.body]!; + const indent = bodyText.length - bodyText.trimStart().length; + return { + insertions, + select: { line: firstLine + snippet.body, from: indent, to: bodyText.length }, + }; +} diff --git a/src/platform/inspections.ts b/src/platform/inspections.ts index 4b203d95c..3c62aec01 100644 --- a/src/platform/inspections.ts +++ b/src/platform/inspections.ts @@ -330,7 +330,7 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [ name: "Undefined step", group: "Gherkin", description: - "Reports steps of a .feature file that no step definition of the project's JavaScript or TypeScript files matches (Cucumber expressions and regular expressions). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.", + "Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.", defaultLevel: "warning", }, { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 1d4e2ebd7..306e588e6 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2031,6 +2031,6 @@ "Undefined step reference: {text}": "Undefined step reference: {text}", "Create Step Definition": "Create Step Definition", "Create step definition '{text}'": "Create step definition '{text}'", - "Reports steps of a .feature file that no step definition of the project's JavaScript or TypeScript files matches (Cucumber expressions and regular expressions). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "Reports steps of a .feature file that no step definition of the project's JavaScript or TypeScript files matches (Cucumber expressions and regular expressions). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.", - "Undefined step": "Undefined step" + "Undefined step": "Undefined step", + "Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 410009a1a..8b16a5290 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8418,6 +8418,6 @@ "Undefined step reference: {text}": "未定义的步骤引用:{text}", "Create Step Definition": "创建步骤定义", "Create step definition '{text}'": "创建步骤定义“{text}”", - "Reports steps of a .feature file that no step definition of the project's JavaScript or TypeScript files matches (Cucumber expressions and regular expressions). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "报告 .feature 文件中没有任何步骤定义匹配的步骤(按项目 JavaScript 或 TypeScript 文件中的 Cucumber 表达式和正则表达式匹配)。这些文件里没有步骤定义的项目不做检查。按 Alt+Enter 可创建定义。", - "Undefined step": "未定义的步骤" + "Undefined step": "未定义的步骤", + "Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "报告 .feature 文件中项目里没有任何步骤定义匹配的步骤(按 JavaScript、TypeScript、Java 和 Kotlin 文件中的 Cucumber 表达式和正则表达式匹配)。这些文件里没有步骤定义的项目不做检查。按 Alt+Enter 可创建定义。" }