rob-revisited/ide/ui/js/gutter-run.js

196 lines
11 KiB
JavaScript

// Run / Debug icons on the line (the editor's gutter, left of the line numbers): a scene's class line (run THAT scene, not the whole project: the
// game starts on it, JUMPHP_SCENE; also for the samples of an extension, run through its example game), and a CLI app's command
// (#[AsCommand(name: 'add')]) gets a ▶ that runs the program with that command, from the line, and Debug (Xdebug)
// with the same arguments. The arguments (the command's options and values) are typed once and remembered per
// command (prefs), like the run configurations.
import { monaco, pathOf } from './editor.js';
import { menu, prompt, prefs, debounce, t } from './ui.js';
import { castorMenuItems } from './command-wizard.js';
const COMMAND = /#\[AsCommand\(\s*(?:name:\s*)?(['"])([^'"]+)\1/;
const NAMESPACE = /^namespace\s+([^;\s]+)\s*;/;
const TEST_METHOD = /^\s*(?:public\s+)?function\s+(test\w+)\s*\(/;
const STATUS_TEXT = { passed: 'passed', failed: 'failed', error: 'failed', skipped: 'skipped', running: 'running', queued: 'running' };
const AS_TASK = /#\[AsTask\b(?:\((.*)\))?/;
const TASK_FUNCTION = /^\s*function\s+(\w+)\s*\(/;
const isCastorFile = (path) => /(^|\/)castor\.php$|(^|\/)\.castor\/.+\.php$/.test(path);
/** The name castor gives a task: #[AsTask(name: 'x', namespace: 'db')] -> 'db:x', else the function in kebab case. */
export function castorTaskName(attrArgs, fn) {
const arg = (key) => new RegExp(`\\b${key}\\s*:\\s*(['"])([^'"]*)\\1`).exec(attrArgs || '')?.[2];
const name = arg('name') || fn.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/_/g, '-').toLowerCase();
const ns = arg('namespace');
return ns ? `${ns}:${name}` : name;
}
const SCENE_CLASS = /^(?:final\s+)?class\s+(\w+)\s+extends\s+\\?(?:[\w\\]*\\)?(\w*Scene)\b/;
/** "add 'two words' --done" -> ['add', 'two words', '--done'] (quotes group, no shell). */
export function splitArgs(text) {
const out = [];
const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
let m;
while ((m = re.exec(String(text || '')))) out.push(m[1] ?? m[2] ?? m[3]);
return out;
}
export class GutterRun {
constructor(app) {
this.app = app;
this.marks = new Map(); // model uri => [{ line, name }]
this.decorations = new Map(); // model uri => decoration ids
for (const group of app.editors.groups) this.attach(group.editor);
monaco.editor.onDidCreateEditor((editor) => this.attach(editor));
}
attach(editor) {
if (editor.__gutterRun) return;
editor.__gutterRun = true;
const refresh = debounce(() => this.scan(editor.getModel()), 300);
editor.onDidChangeModel(() => this.scan(editor.getModel()));
editor.onDidChangeModelContent(refresh);
this.scan(editor.getModel());
editor.__gutterRunAt = (line) => !!this.markAt(editor.getModel(), line);
editor.onMouseDown((e) => {
if (e.target.type !== monaco.editor.MouseTargetType.GUTTER_LINE_DECORATIONS) return;
const model = editor.getModel();
const mark = model && e.target.position ? this.markAt(model, e.target.position.lineNumber) : null;
if (mark) this.open(model, mark, { x: e.event.posx, y: e.event.posy });
});
}
markAt(model, line) { return model ? (this.marks.get(model.uri.toString()) || []).find((m) => m.line === line) || null : null; }
/** The module (apps/<id>/ or games/<id>/) a file is in, when it has a Run configuration. */
moduleOf(path) {
const m = /^(?:games|apps)\/([^/]+)\//.exec(path);
return m && this.app.runner?.config('run:' + m[1]) ? m[1] : null;
}
/** The game that runs the scenes of a file: its own module, or (a sample of an extension project) the extension's example game <id>-demo. */
gameOf(path) {
const own = this.moduleOf(path);
if (own) return own;
const e = /^extensions\/([^/]+)\//.exec(path);
return e && this.app.runner?.config('run:' + e[1] + '-demo') ? e[1] + '-demo' : null;
}
/** the marks of every open editor again (the Tests window found tests, or a run ended: the icons' colours) */
rescan() {
for (const group of this.app.editors.groups) this.scan(group.editor.getModel());
}
scan(model) {
if (!model || model.isDisposed()) return;
const path = pathOf(model.uri);
const tested = this.app.tests?.scopeOf(path);
if (model.getLanguageId() !== 'php' && !tested) return;
const key = model.uri.toString();
const marks = [];
if (tested) {
// a test file of the Tests window: its classes and test methods, coloured by their last result
for (const m of this.app.tests.marksFor(path, model.getValue())) marks.push({ line: m.line, name: m.name, unit: m });
}
if (this.moduleOf(path)) {
model.getLinesContent().forEach((text, i) => { const m = COMMAND.exec(text); if (m) marks.push({ line: i + 1, name: m[2] }); });
}
const tm = /^(?:games|apps)\/([^/]+)\/(tests\/.+Test\.php)$/.exec(path);
if (tm && this.app.runner && !tested) {
model.getLinesContent().forEach((text, i) => { const m = TEST_METHOD.exec(text); if (m) marks.push({ line: i + 1, name: m[1], test: { module: tm[1], file: tm[2] } }); });
}
if (isCastorFile(path)) {
// a Castor task (#[AsTask] above a function): ▶ runs it like the Scripts window does
const lines = model.getLinesContent();
lines.forEach((text, i) => {
const a = AS_TASK.exec(text);
if (!a) return;
for (let j = i; j < Math.min(lines.length, i + 6); j++) {
const f = TASK_FUNCTION.exec(lines[j]);
if (f) { marks.push({ line: i + 1, name: castorTaskName(a[1], f[1]), castor: true }); break; }
}
});
}
if (this.gameOf(path)) {
const lines = model.getLinesContent();
const ns = lines.map((l) => NAMESPACE.exec(l)).find(Boolean)?.[1];
lines.forEach((text, i) => {
const m = SCENE_CLASS.exec(text);
if (m && ns) marks.push({ line: i + 1, name: m[1], scene: `${ns}\\${m[1]}` });
});
}
this.marks.set(key, marks);
this.decorations.set(key, model.deltaDecorations(this.decorations.get(key) || [], marks.map((m) => ({
range: new monaco.Range(m.line, 1, m.line, 1),
options: { linesDecorationsClassName: m.unit ? `run-gutter test-${m.unit.status || 'none'}` : 'run-gutter', linesDecorationsTooltip: m.unit ? t('Run the test {name}', { name: m.name }) + (m.unit.status ? ` (${t(STATUS_TEXT[m.unit.status] || 'not run')})` : '') : m.test ? t('Run the test {name} (only this one)', { name: m.name }) : m.scene ? t('Run the scene {name} (only this scene)', { name: m.name }) : t('Run or debug the command {name}', { name: m.name }) },
}))));
}
key(path, name) { return `runargs:${this.app.projectKey}:${path}:${name}`; }
/** The run configuration of the module with the command and its remembered arguments added to it. */
config(model, mark) {
const path = pathOf(model.uri);
const base = this.app.runner.config('run:' + this.moduleOf(path));
const args = splitArgs(prefs.get(this.key(path, mark.name), ''));
return { ...base, id: base.id + ':' + mark.name, label: `${base.group} ${mark.name}${args.length ? ' ' + args.join(' ') : ''}`, command: [...base.command, mark.name, ...args] };
}
/** The scene's run configuration: its game, started on that scene. */
sceneConfig(model, mark) {
const game = this.gameOf(pathOf(model.uri));
const base = this.app.runner.config('run:' + game);
// ad hoc: the backend runs the command given, for ids it does not know (run:<game>:<Scene> is not one of the project's configurations)
return { config: { id: 'adhoc', kind: base.kind || 'run', label: `${game}: ${mark.name}`, command: base.command }, env: { JUMPHP_SCENE: mark.scene } };
}
open(model, mark, at) {
const path = pathOf(model.uri);
if (mark.unit) {
const tests = this.app.tests;
const scope = tests.scopeOf(path);
menu([
{ label: t("Run '{name}'", { name: mark.name }), icon: 'play', action: () => { this.app.showTool('tests'); tests.runMark(path, mark.unit); } },
tests.coverable(scope) ? { label: t("Run '{name}' with coverage", { name: mark.name }), icon: 'check', action: () => { this.app.showTool('tests'); tests.runMark(path, mark.unit, true); } } : null,
{ label: t('Show in the Tests window'), icon: 'test', action: () => { tests.selected = (mark.unit.kind === 'class' ? 'class:' : 'test:') + mark.unit.id; this.app.showTool('tests'); tests.render(); } },
].filter(Boolean), at);
return;
}
if (mark.test) {
const config = { id: 'adhoc', kind: 'test', label: mark.name, command: ['bin/jumphp', 'test', mark.test.module, mark.test.file, mark.name] };
menu([{ label: t("Run '{name}'", { name: mark.name }), icon: 'play', action: () => this.app.runner.start(config) }], at);
return;
}
if (mark.castor) {
const scripts = this.app.scripts;
const run = async (withArgs) => {
await scripts?.load?.(true);
const item = scripts?.items?.().find((i) => i.runner === 'castor' && i.name === mark.name);
if (!item) { scripts?.data?.castor && !scripts.data.castor.installed && scripts.data.castor.installable ? await scripts.installCastor() : this.app.showTool?.('scripts'); return; }
if (withArgs) return castorMenuItems(this.app, mark.name)[1].action();
scripts.run(item.ref);
};
menu([
{ label: t("Run '{name}'", { name: mark.name }), icon: 'play', action: () => run(false) },
{ label: t('Run with Arguments…'), icon: 'play', action: () => run(true) },
castorMenuItems(this.app, mark.name)[0],
], at);
return;
}
if (mark.scene) {
const { config, env } = this.sceneConfig(model, mark);
menu([
{ label: t("Run '{name}'", { name: mark.name }), icon: 'play', action: () => this.app.runner.start(config, env) },
this.app.debugger ? { label: t("Debug '{name}'", { name: mark.name }), icon: 'debug', action: () => this.app.debugger.debug(config, env) } : null,
].filter(Boolean), at);
return;
}
const shown = () => this.config(model, mark).label;
menu([
{ label: t("Run '{name}'", { name: shown() }), icon: 'play', action: () => this.app.runner.start(this.config(model, mark)) },
this.app.debugger ? { label: t("Debug '{name}'", { name: shown() }), icon: 'debug', action: () => this.app.debugger.debug(this.config(model, mark)) } : null,
{ label: t('Arguments…'), action: async () => {
const value = await prompt(t('Arguments of {name}', { name: mark.name }), { value: prefs.get(this.key(path, mark.name), ''), label: t('Options and values after the command name (quotes group words)'), placeholder: "'Buy milk' --verbose", ok: t('Save') });
if (value !== null && value !== undefined) prefs.set(this.key(path, mark.name), String(value).trim());
} },
].filter(Boolean), at);
}
}