Skip to content

Commit

Permalink
整理代码
Browse files Browse the repository at this point in the history
  • Loading branch information
sumneko committed Jul 12, 2024
1 parent 13c3f54 commit e670088
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions src/editorTable/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,30 @@ function makeSandbox() {

export async function runEditor(uri: vscode.Uri, funcName: string = 'main') {
const file = await y3.fs.readFile(uri);
let content = file!.string;
content = content + `\n\nmodule.exports = ${funcName}`;
let needExports: string[] = [];
let content = file!.string.replaceAll(/export\s+(async\s+)function\s+([\w_]+)/g, (_, async, name) => {
needExports.push(name);
return `${async}function ${name}`;
});
content = content + '\nmodule.exports = { ' + needExports.join(', ') + ' };\n';
let script = new vm.Script(content, {
filename: uri.path,
});
let func = script.runInNewContext(vm.createContext(makeSandbox()));
if (typeof func !== 'function') {
throw new Error('没有找到要执行的函数');
let exports = script.runInNewContext(vm.createContext(makeSandbox()));
if (typeof exports[funcName] !== 'function') {
throw new Error(`没有找到要执行的函数${funcName}`);
}
await func();
y3.log.info(`执行 "${uri.path.split('/').pop()}" 成功!`);
await exports[funcName]();
const name = uri.path.split('/').pop()!.replace(/\.js$/, '');
y3.log.info(`执行 "${name}/${funcName}" 成功!`);
}

class RunButtonProvider implements vscode.CodeLensProvider {
public provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] | undefined {
let codeLens: vscode.CodeLens[] = [];
for (let i = 0; i < document.lineCount; i++) {
const line = document.lineAt(i);
const name = line.text.match(/^async\s+function\s+([\w_]+)/)?.[1];
const name = line.text.match(/^export\s+(async\s+)function\s+([\w_]+)/)?.[2];
if (name) {
codeLens.push(new vscode.CodeLens(new vscode.Range(i, 0, i, 0), {
title: `$(debug-start)运行 ${name} 函数`,
Expand Down

0 comments on commit e670088

Please sign in to comment.