mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-18 16:08:55 +00:00
feat(cucumber): navigate between feature steps and step definitions (#3668)
Go to Declaration on a .feature step opens the matching JavaScript / TypeScript step definitions (@cucumber/cucumber, playwright-bdd); on a definition's pattern it lists the feature steps using it. Cucumber expressions and regular expressions match; Scenario Outline steps use their first example's values. A cheap backend scan (cucumber_sources) feeds a UI index kept until a feature or script file changes. Refs #797
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
//! 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
|
||||
//! owns the Gherkin and step-expression parsing and the index it feeds (as for `routes`),
|
||||
//! so this side stays a cheap scan.
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::IdeResult;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// Files handed out at most, and bytes in total: a test suite's features and step
|
||||
/// files fit well inside these, and the UI indexes them once.
|
||||
const MAX_FILES: usize = 4096;
|
||||
const MAX_BYTES: usize = 64 << 20;
|
||||
/// A single source bigger than this is a bundle, not a step file.
|
||||
const MAX_FILE_BYTES: u64 = 2 << 20;
|
||||
|
||||
/// What a step definition call starts with (`Given('…'`, `defineStep(/…/`).
|
||||
const STEP_CALLS: [&str; 5] = ["Given(", "When(", "Then(", "Step(", "defineStep("];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StepSource {
|
||||
pub path: ide_core::IpcPath,
|
||||
pub text: String,
|
||||
/// A Gherkin `.feature` file; otherwise a script defining steps.
|
||||
pub feature: bool,
|
||||
}
|
||||
|
||||
fn is_feature(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("feature"))
|
||||
}
|
||||
|
||||
fn is_script(path: &Path) -> bool {
|
||||
matches!(
|
||||
path.extension().and_then(|e| e.to_str()),
|
||||
Some("js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts")
|
||||
)
|
||||
}
|
||||
|
||||
/// The feature files and step definition files under `root`.
|
||||
pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec<StepSource> {
|
||||
let found: Mutex<Vec<StepSource>> = Mutex::new(Vec::new());
|
||||
let bytes = AtomicUsize::new(0);
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
let feature = is_feature(path);
|
||||
if !(feature || is_script(path)) || bytes.load(Ordering::Relaxed) >= MAX_BYTES {
|
||||
return;
|
||||
}
|
||||
if std::fs::metadata(path).map_or(true, |m| m.len() > MAX_FILE_BYTES) {
|
||||
return;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else { return };
|
||||
if !feature && !STEP_CALLS.iter().any(|call| text.contains(call)) {
|
||||
return;
|
||||
}
|
||||
let Ok(mut found) = found.lock() else { return };
|
||||
if found.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
bytes.fetch_add(text.len(), Ordering::Relaxed);
|
||||
found.push(StepSource { path: path.to_path_buf().into(), text, feature });
|
||||
});
|
||||
let mut files = found.into_inner().unwrap_or_default();
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
files
|
||||
}
|
||||
|
||||
/// Every Cucumber source of the project (its folder and the content roots outside it).
|
||||
pub fn cucumber_sources(host: &Host, window: &str) -> IdeResult<Vec<StepSource>> {
|
||||
let project = host.project(window)?;
|
||||
let mut excludes = project.search_excludes();
|
||||
// Cucumber's own sources (and every other package's) are not the project's steps.
|
||||
excludes.push("node_modules".to_owned());
|
||||
let mut out = Vec::new();
|
||||
for root in std::iter::once(project.root.clone()).chain(project.content_roots()) {
|
||||
out.extend(sources_in(&root, &excludes));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn features_and_step_files_are_read_and_nothing_else() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["features", "steps", "src", "node_modules/@cucumber/cucumber/lib"] {
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("features/cart.feature"), "Feature: Cart\n").unwrap();
|
||||
std::fs::write(root.join("steps/cart.steps.ts"), "Given('an empty cart', () => {});").unwrap();
|
||||
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/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<String> =
|
||||
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!(files[0].feature && !files[1].feature);
|
||||
assert!(files[2].text.contains("an empty cart"));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
pub mod agent;
|
||||
pub mod analysis;
|
||||
pub mod bdd;
|
||||
pub mod build;
|
||||
pub mod bytes;
|
||||
pub mod coverage;
|
||||
|
||||
@@ -248,6 +248,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
nav::index_status,
|
||||
nav::index_file_extensions,
|
||||
nav::spring_route_sources,
|
||||
nav::cucumber_sources,
|
||||
nav::find_files,
|
||||
nav::find_files_named,
|
||||
nav::find_dirs,
|
||||
|
||||
@@ -61,6 +61,20 @@ pub fn spring_route_sources(
|
||||
ide_host::ops::routes::spring_route_sources(&state.host, window.label())
|
||||
}
|
||||
|
||||
/// Cucumber feature files and step definition files, for step navigation.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn cucumber_sources(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
) -> IdeResult<Vec<ide_host::ops::bdd::StepSource>> {
|
||||
let host = state.host.clone();
|
||||
let label = window.label().to_owned();
|
||||
tauri::async_runtime::spawn_blocking(move || ide_host::ops::bdd::cucumber_sources(&host, &label))
|
||||
.await
|
||||
.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn find_symbols(
|
||||
|
||||
@@ -81,6 +81,7 @@ close_project always project_host bin
|
||||
coverage_collect trusted project_host bindings async
|
||||
coverage_import always project_host bindings async
|
||||
coverage_prepare trusted project_host bindings async
|
||||
cucumber_sources trusted desktop bindings async
|
||||
db_apply_edits trusted project_host bindings async
|
||||
db_completion trusted project_host bindings async
|
||||
db_connect trusted project_host bindings async
|
||||
|
||||
@@ -488,6 +488,8 @@ export const commands = {
|
||||
indexFileExtensions: () => typedError<ExtensionCount[], IdeError>(__TAURI_INVOKE("index_file_extensions")),
|
||||
/** Spring Web mapping sources for the request-path index of Search Everywhere. */
|
||||
springRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("spring_route_sources")),
|
||||
/** Cucumber feature files and step definition files, for step navigation. */
|
||||
cucumberSources: () => typedError<StepSource[], IdeError>(__TAURI_INVOKE("cucumber_sources")),
|
||||
findFiles: (query: string, limit: number) => typedError<FileMatch[], IdeError>(__TAURI_INVOKE("find_files", { query, limit })),
|
||||
findFilesNamed: (name: string) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("find_files_named", { name })),
|
||||
/** Folders holding indexed files, for `@` references. */
|
||||
@@ -10299,6 +10301,13 @@ export type StepInTarget = {
|
||||
|
||||
export type StepKind = "over" | "into" | "out";
|
||||
|
||||
export type StepSource = {
|
||||
path: IpcPath,
|
||||
text: string,
|
||||
/** A Gherkin `.feature` file; otherwise a script defining steps. */
|
||||
feature: boolean,
|
||||
};
|
||||
|
||||
export type StructuralEvent = { type: "file"; file: StructuralFile } | { type: "done"; summary: StructuralSummary };
|
||||
|
||||
/** All matches in one file; streamed as files complete. */
|
||||
|
||||
@@ -209,7 +209,7 @@ export async function locationItems(locs: readonly DeclarationTarget[]): Promise
|
||||
};
|
||||
return {
|
||||
id: `${i}`,
|
||||
label: names[i] ?? basename(l.path),
|
||||
label: l.name ?? names[i] ?? basename(l.path),
|
||||
detail: [indexed.get(i) ?? enclosingType(files.get(l.path), l), where].filter(Boolean).join(" · "),
|
||||
icon: fileIconName(basename(l.path), l.path),
|
||||
location: { path: l.path, line: l.range.start.line },
|
||||
|
||||
@@ -6,7 +6,8 @@ import type { Location } from "@/platform/ipc";
|
||||
export interface NavigationMatch {
|
||||
from: number;
|
||||
to: number;
|
||||
targets: Location[];
|
||||
/** `name`: what the chooser shows for a target (else the word at it). */
|
||||
targets: Array<Location & { name?: string }>;
|
||||
}
|
||||
type Provider = (view: EditorView, offset: number) => Promise<NavigationMatch | null>;
|
||||
const providers = new Set<Provider>();
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Cucumber step navigation: 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 matches.
|
||||
*/
|
||||
import { docOf } from "@/editor/lsp/lsp";
|
||||
import { registerNavigationProvider } from "@/editor/navigationProviders";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { featureSteps, stepDefinitions } from "./steps";
|
||||
import { clearStepIndex, definitionsOf, isCucumberSource, usagesOf } from "./stepIndex";
|
||||
|
||||
const SCRIPT = /\.[cm]?[jt]sx?$/i;
|
||||
|
||||
export function activate(): () => void {
|
||||
const unregister = registerNavigationProvider(async (view, offset) => {
|
||||
const doc = docOf(view);
|
||||
if (!doc || doc.virtual) return null;
|
||||
const text = view.state.doc.toString();
|
||||
if (/\.feature$/i.test(doc.path)) {
|
||||
const step = featureSteps(text).find((s) => s.from <= offset && offset < s.to);
|
||||
if (!step) return null;
|
||||
const targets = await definitionsOf(step);
|
||||
return targets.length ? { from: step.from, to: step.to, targets } : null;
|
||||
}
|
||||
if (!SCRIPT.test(doc.path)) return null;
|
||||
const definition = stepDefinitions(text).find((d) => d.from <= offset && offset < d.to);
|
||||
if (!definition) return null;
|
||||
const targets = await usagesOf(definition);
|
||||
return targets.length ? { from: definition.from, to: definition.to, targets } : null;
|
||||
});
|
||||
const unsubscribe = onIdeEvent("fsChanged", (e) => {
|
||||
if ([...e.created, ...e.modified, ...e.removed].some((p) => isCucumberSource(String(p)))) clearStepIndex();
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
unregister();
|
||||
clearStepIndex();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/** The project's Cucumber steps and step definitions, scanned once and kept until a source changes. */
|
||||
import { call, commands, type Location } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { featureSteps, matchesStep, stepDefinitions, type FeatureStep, type StepDefinition } from "./steps";
|
||||
|
||||
interface Indexed<T> {
|
||||
path: string;
|
||||
text: string;
|
||||
items: T[];
|
||||
}
|
||||
|
||||
interface StepIndex {
|
||||
definitions: Indexed<StepDefinition>[];
|
||||
steps: Indexed<FeatureStep>[];
|
||||
}
|
||||
|
||||
let cached: Promise<StepIndex> | 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);
|
||||
}
|
||||
|
||||
/** Forgets the index, so the next lookup rescans the project. */
|
||||
export function clearStepIndex() {
|
||||
cached = null;
|
||||
}
|
||||
|
||||
function stepIndex(): Promise<StepIndex> {
|
||||
cached ??= call(commands.cucumberSources()).then(
|
||||
(sources) => {
|
||||
const index: StepIndex = { definitions: [], steps: [] };
|
||||
for (const s of sources) {
|
||||
const path = ipcPath(s.path);
|
||||
if (s.feature) index.steps.push({ path, text: s.text, items: featureSteps(s.text) });
|
||||
else {
|
||||
const items = stepDefinitions(s.text);
|
||||
if (items.length) index.definitions.push({ path, text: s.text, items });
|
||||
}
|
||||
}
|
||||
return index;
|
||||
},
|
||||
(e: unknown) => {
|
||||
cached = null;
|
||||
throw e;
|
||||
},
|
||||
);
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** The 0-based line and UTF-16 column of `offset` in `text`. */
|
||||
function position(text: string, offset: number): { line: number; col: number } {
|
||||
let line = 0;
|
||||
let start = 0;
|
||||
for (let i = text.indexOf("\n"); i >= 0 && i < offset; i = text.indexOf("\n", i + 1)) {
|
||||
line++;
|
||||
start = i + 1;
|
||||
}
|
||||
return { line, col: offset - start };
|
||||
}
|
||||
|
||||
const location = (path: string, text: string, from: number, to: number, name: string) => ({
|
||||
path,
|
||||
range: { start: position(text, from), end: position(text, to) },
|
||||
name,
|
||||
});
|
||||
|
||||
/** The definitions matching a feature step. */
|
||||
export async function definitionsOf(step: FeatureStep): Promise<Array<Location & { name: string }>> {
|
||||
const { definitions } = await stepIndex();
|
||||
return definitions.flatMap((file) =>
|
||||
file.items.filter((d) => matchesStep(d, step)).map((d) => location(file.path, file.text, d.from, d.to, d.source)),
|
||||
);
|
||||
}
|
||||
|
||||
/** The feature steps a definition matches. */
|
||||
export async function usagesOf(definition: StepDefinition): Promise<Array<Location & { name: string }>> {
|
||||
const { steps } = await stepIndex();
|
||||
return steps.flatMap((file) =>
|
||||
file.items
|
||||
.filter((s) => matchesStep(definition, s))
|
||||
.map((s) => location(file.path, file.text, s.from, s.to, `${s.keyword} ${s.text}`)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { expressionRegExp, featureSteps, matchesStep, stepDefinitions } from "./steps";
|
||||
|
||||
const STEPS = `import { Given, When, Then } from "@cucumber/cucumber";
|
||||
import { createBdd } from "playwright-bdd";
|
||||
const bdd = createBdd();
|
||||
|
||||
Given('an empty cart', async function () {});
|
||||
When("I add {int} {string} to the cart", async (n: number, name: string) => {});
|
||||
bdd.Then(/^the total is (\\d+(?:\\.\\d+)?) EUR$/, async () => {});
|
||||
Then<World>(\`I see {word} item(s) in my basket/bag\`, () => {});
|
||||
When(\`dynamic \${name}\`, () => {});
|
||||
const isGiven = (x) => x; isGiven('not a step');
|
||||
`;
|
||||
|
||||
const FEATURE = `# language: en
|
||||
@cart
|
||||
Feature: Cart
|
||||
|
||||
Background:
|
||||
Given an empty cart
|
||||
|
||||
Scenario: Add one
|
||||
When I add 2 "apples" to the cart
|
||||
Then the total is 3.50 EUR
|
||||
And I see 1 item in my bag
|
||||
"""
|
||||
Given not a step
|
||||
"""
|
||||
|
||||
Scenario Outline: Add several
|
||||
When I add <count> "<fruit>" to the cart
|
||||
* I see <count> items in my basket
|
||||
|
||||
Examples:
|
||||
| count | fruit |
|
||||
| 3 | pears |
|
||||
| 4 | plums |
|
||||
`;
|
||||
|
||||
describe("Cucumber steps", () => {
|
||||
it("reads step definitions of @cucumber/cucumber and playwright-bdd", () => {
|
||||
const defs = stepDefinitions(STEPS);
|
||||
expect(defs.map((d) => d.source)).toEqual([
|
||||
"an empty cart",
|
||||
"I add {int} {string} to the cart",
|
||||
"^the total is (\\d+(?:\\.\\d+)?) EUR$",
|
||||
"I see {word} item(s) in my basket/bag",
|
||||
]);
|
||||
// The range covers the literal, quotes included.
|
||||
expect(STEPS.slice(defs[0]!.from, defs[0]!.to)).toBe("'an empty cart'");
|
||||
});
|
||||
|
||||
it("turns Cucumber expressions into anchored regular expressions", () => {
|
||||
const re = (e: string) => expressionRegExp(e)!;
|
||||
expect(re("I add {int} {string} to the cart").test('I add 12 "big apples" to the cart')).toBe(true);
|
||||
expect(re("I add {int} {string} to the cart").test('I add many "apples" to the cart')).toBe(false);
|
||||
expect(re("I have {float} cucumber(s)").test("I have 1.5 cucumbers")).toBe(true);
|
||||
expect(re("I have {float} cucumber(s)").test("I have 1 cucumber")).toBe(true);
|
||||
expect(re("my belly/stomach hurts").test("my stomach hurts")).toBe(true);
|
||||
expect(re("my belly/stomach hurts").test("my belly/stomach hurts")).toBe(false);
|
||||
expect(re("a {color} ball").test("a red ball")).toBe(true);
|
||||
expect(re("it costs \\(about\\) {int}$").test("it costs (about) 5$")).toBe(true);
|
||||
expect(re("a {} thing").test("a very odd thing")).toBe(true);
|
||||
expect(re("an empty cart").test("an empty cart today")).toBe(false);
|
||||
expect(expressionRegExp("broken {int")).toBeNull();
|
||||
});
|
||||
|
||||
it("reads feature steps, skipping doc strings and filling outline placeholders", () => {
|
||||
const steps = featureSteps(FEATURE);
|
||||
expect(steps.map((s) => [s.keyword, s.matchText])).toEqual([
|
||||
["Given", "an empty cart"],
|
||||
["When", 'I add 2 "apples" to the cart'],
|
||||
["Then", "the total is 3.50 EUR"],
|
||||
["And", "I see 1 item in my bag"],
|
||||
["When", 'I add 3 "pears" to the cart'],
|
||||
["*", "I see 3 items in my basket"],
|
||||
]);
|
||||
expect(FEATURE.slice(steps[4]!.from, steps[4]!.to)).toBe('I add <count> "<fruit>" to the cart');
|
||||
});
|
||||
|
||||
it("matches every step to its definition", () => {
|
||||
const defs = stepDefinitions(STEPS);
|
||||
const matched = featureSteps(FEATURE).map((s) => defs.findIndex((d) => matchesStep(d, s)));
|
||||
expect(matched).toEqual([0, 1, 2, 3, 1, 3]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* Cucumber steps, both sides: the step definitions of JavaScript / TypeScript files
|
||||
* (`Given('a {int} item cart', …)` of `@cucumber/cucumber`, `playwright-bdd`'s `createBdd()`
|
||||
* functions) and the steps of Gherkin `.feature` files, with Cucumber expression and regular
|
||||
* expression matching between them.
|
||||
*/
|
||||
|
||||
/** A step definition: the pattern literal of a `Given` / `When` / `Then` / `Step` call. */
|
||||
export interface StepDefinition {
|
||||
/** Offsets of the literal (quotes or slashes included) in its file. */
|
||||
from: number;
|
||||
to: number;
|
||||
/** The pattern as written, without quotes. */
|
||||
source: string;
|
||||
regexp: RegExp;
|
||||
}
|
||||
|
||||
/** A step of a feature file, with the text it is matched by. */
|
||||
export interface FeatureStep {
|
||||
/** Offsets of the step text (after the keyword) in its file. */
|
||||
from: number;
|
||||
to: number;
|
||||
keyword: string;
|
||||
/** The text as written. */
|
||||
text: string;
|
||||
/** The text matched against definitions: Scenario Outline placeholders take the first example's values. */
|
||||
matchText: string;
|
||||
}
|
||||
|
||||
const DEFINE = /\b(?:Given|When|Then|And|But|Step|defineStep)\s*(?:<[^<>()]*>\s*)?\(\s*/g;
|
||||
|
||||
/** The step definitions of a script. */
|
||||
export function stepDefinitions(text: string): StepDefinition[] {
|
||||
const out: StepDefinition[] = [];
|
||||
for (const m of text.matchAll(DEFINE)) {
|
||||
const at = m.index + m[0].length;
|
||||
const literal = readLiteral(text, at);
|
||||
if (!literal) continue;
|
||||
const regexp = literal.regexp ?? expressionRegExp(literal.value);
|
||||
if (regexp) out.push({ from: at, to: literal.end, source: literal.value, regexp });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 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];
|
||||
if (quote === "'" || quote === '"' || quote === "`") {
|
||||
let value = "";
|
||||
for (let i = at + 1; i < text.length; i++) {
|
||||
const c = text[i]!;
|
||||
if (c === "\\") {
|
||||
const next = text[i + 1] ?? "";
|
||||
// An escaped quote is the quote; other escapes stay (a Cucumber expression's `\(`).
|
||||
value += next === quote ? next : c + next;
|
||||
i++;
|
||||
} else if (c === quote) return { value, end: i + 1 };
|
||||
else if ((c === "\n" && quote !== "`") || (quote === "`" && c === "$" && text[i + 1] === "{")) return null;
|
||||
else value += c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (quote === "/") {
|
||||
let inClass = false;
|
||||
for (let i = at + 1; i < text.length; i++) {
|
||||
const c = text[i]!;
|
||||
if (c === "\\") i++;
|
||||
else if (c === "[") inClass = true;
|
||||
else if (c === "]") inClass = false;
|
||||
else if (c === "\n") return null;
|
||||
else if (c === "/" && !inClass) {
|
||||
const flags = /^[a-z]*/.exec(text.slice(i + 1))![0];
|
||||
const value = text.slice(at + 1, i);
|
||||
try {
|
||||
return { value, end: i + 1 + flags.length, regexp: new RegExp(value, flags.replace(/[gy]/g, "")) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Built-in parameter types; a custom one (`defineParameterType`) matches anything. */
|
||||
const PARAMETERS: Record<string, string> = {
|
||||
int: "-?\\d+",
|
||||
byte: "-?\\d+",
|
||||
short: "-?\\d+",
|
||||
long: "-?\\d+",
|
||||
biginteger: "-?\\d+",
|
||||
float: "-?(?:\\d+(?:[.,]\\d*)?|[.,]\\d+)(?:[eE][-+]?\\d+)?",
|
||||
double: "-?(?:\\d+(?:[.,]\\d*)?|[.,]\\d+)(?:[eE][-+]?\\d+)?",
|
||||
bigdecimal: "-?(?:\\d+(?:[.,]\\d*)?|[.,]\\d+)(?:[eE][-+]?\\d+)?",
|
||||
word: "[^\\s]+",
|
||||
string: "\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'",
|
||||
"": ".*",
|
||||
};
|
||||
|
||||
const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
|
||||
|
||||
/**
|
||||
* A Cucumber expression as an anchored regular expression: `{type}` parameters, `(optional)`
|
||||
* text, `a/b` alternatives within a word, `\` escapes. Null when it is malformed.
|
||||
*/
|
||||
export function expressionRegExp(expression: string): RegExp | null {
|
||||
let out = "";
|
||||
// Alternatives apply within a run of text without whitespace, parameters or optionals.
|
||||
let word: string[] = [""];
|
||||
const flush = () => {
|
||||
out += word.length > 1 ? `(?:${word.join("|")})` : word[0]!;
|
||||
word = [""];
|
||||
};
|
||||
const add = (re: string) => (word[word.length - 1] += re);
|
||||
for (let i = 0; i < expression.length; i++) {
|
||||
const c = expression[i]!;
|
||||
if (c === "\\" && i + 1 < expression.length) {
|
||||
add(escapeRe(expression[++i]!));
|
||||
} else if (c === "{") {
|
||||
const end = expression.indexOf("}", i);
|
||||
if (end < 0) return null;
|
||||
const name = expression.slice(i + 1, end).trim();
|
||||
flush();
|
||||
out += `(${PARAMETERS[name] ?? ".*?"})`;
|
||||
i = end;
|
||||
} else if (c === "(") {
|
||||
const end = expression.indexOf(")", i);
|
||||
if (end < 0) return null;
|
||||
add(`(?:${escapeRe(expression.slice(i + 1, end))})?`);
|
||||
i = end;
|
||||
} else if (c === "/") {
|
||||
word.push("");
|
||||
} else if (/\s/.test(c)) {
|
||||
flush();
|
||||
out += escapeRe(c);
|
||||
} else {
|
||||
add(escapeRe(c));
|
||||
}
|
||||
}
|
||||
flush();
|
||||
try {
|
||||
return new RegExp(`^${out}$`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const STEP = /^(\s*)(Given|When|Then|And|But|\*)(\s+)(\S.*?)\s*$/;
|
||||
const BLOCK = /^\s*(Feature|Rule|Background|Scenario|Scenario Outline|Scenario Template|Example|Examples|Scenarios):/;
|
||||
|
||||
/** The steps of a feature file (English keywords), placeholders filled from each outline's first example. */
|
||||
export function featureSteps(text: string): FeatureStep[] {
|
||||
const out: FeatureStep[] = [];
|
||||
let outline: FeatureStep[] = [];
|
||||
let header: string[] | null = null;
|
||||
let examples = false;
|
||||
let docString: string | null = null;
|
||||
let offset = 0;
|
||||
for (const line of text.split("\n")) {
|
||||
const start = offset;
|
||||
offset += line.length + 1;
|
||||
const trimmed = line.trim();
|
||||
if (docString) {
|
||||
if (trimmed.startsWith(docString)) docString = null;
|
||||
continue;
|
||||
}
|
||||
if (trimmed.startsWith('"""') || trimmed.startsWith("```")) {
|
||||
docString = trimmed.slice(0, 3);
|
||||
continue;
|
||||
}
|
||||
if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith("@")) continue;
|
||||
const block = BLOCK.exec(line);
|
||||
if (block) {
|
||||
examples = block[1] === "Examples" || block[1] === "Scenarios";
|
||||
if (!examples) outline = [];
|
||||
header = null;
|
||||
continue;
|
||||
}
|
||||
if (trimmed.startsWith("|")) {
|
||||
if (!examples) continue;
|
||||
const cells = trimmed
|
||||
.replace(/^\||\|$/g, "")
|
||||
.split("|")
|
||||
.map((c) => c.trim());
|
||||
if (!header) header = cells;
|
||||
else if (header.length) {
|
||||
const values = new Map(header.map((h, i) => [h, cells[i] ?? ""]));
|
||||
for (const step of outline)
|
||||
step.matchText = step.text.replace(/<([^<>]+)>/g, (all, name: string) => values.get(name) ?? all);
|
||||
// Later examples rows give the same steps: the first one stands for them.
|
||||
header = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const m = STEP.exec(line);
|
||||
if (!m) continue;
|
||||
const from = start + m[1]!.length + m[2]!.length + m[3]!.length;
|
||||
const step = { from, to: from + m[4]!.length, keyword: m[2]!, text: m[4]!, matchText: m[4]! };
|
||||
out.push(step);
|
||||
if (step.text.includes("<")) outline.push(step);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const matchesStep = (definition: StepDefinition, step: FeatureStep) => definition.regexp.test(step.matchText);
|
||||
@@ -48,6 +48,7 @@ import { activate as analysis } from "./analysis";
|
||||
import { activate as services } from "./services";
|
||||
import { activate as github, activateSettingsPages as githubPages } from "./github";
|
||||
import { activate as httpClient } from "./http-client";
|
||||
import { activate as cucumber } from "./cucumber";
|
||||
import { activate as database, activateSettingsPages as databasePages } from "./database";
|
||||
import { activate as graphql } from "./graphql";
|
||||
import { activate as deployment, activateDeploymentWindow } from "./deployment";
|
||||
@@ -99,6 +100,7 @@ const features: Array<[string, Activate]> = [
|
||||
["services", services],
|
||||
["github", github],
|
||||
["http-client", httpClient],
|
||||
["cucumber", cucumber],
|
||||
["database", database],
|
||||
["graphql", graphql],
|
||||
["deployment", deployment],
|
||||
|
||||
Reference in New Issue
Block a user