Perfect the codebase for wamr-ide (#1817)

Fix errors and warnings reported by eslint
Add CONTRIBUTING document for vscode-extension
This commit is contained in:
Wang Ning 2022-12-27 15:04:36 +08:00 committed by GitHub
parent 676c3c7b04
commit 679a8ab3cb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 316 additions and 299 deletions

View File

@ -1,13 +1,12 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"extends": ["plugin:@typescript-eslint/recommended"],
"parserOptions": {
"ecmaVersion": 6,
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",
@ -16,9 +15,5 @@
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": [
"out",
"dist",
"**/*.d.ts"
]
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}

View File

@ -0,0 +1,34 @@
# CONTRIBUTING
## Pull requests
To submit your change:
- Make sure your code is in line with our
[coding conventions](##Coding-conventions).
- Create an [issue] describing the bug the PR fixes or the feature you intend
to implement.
- Submit a [pull request] into the main branch.
## Coding conventions
#### Format
The codebase is formatted by `Prettier` and the `.prettierrc.json` has been
configured.
- VSCode along with `Format on Save` configuration could easily format your
code during development.
- You can run `prettier-format-check` and `prettier-format-apply` to check and
format your codebase with `prettier` in terminal.
#### Lint
`ESlint` is used as linter for the codebase and the `.eslintrc.json` has been
configured.
- It's suggested to run `npm run lint` then fix errors and warnings before
committing.
[issue]: https://github.com/bytecodealliance/wasm-micro-runtime/issues
[pull request]: https://github.com/bytecodealliance/wasm-micro-runtime/pulls

View File

@ -229,6 +229,7 @@
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts",
"lint-fix": "eslint --fix src --ext ts",
"test": "node ./out/test/runTest.js",
"prettier-format-check": "prettier --config .prettierrc.json 'src/**/*.ts' --check",
"prettier-format-apply": "prettier --config .prettierrc.json 'src/**/*.ts' --write"

View File

@ -3,7 +3,6 @@
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
const vscode = acquireVsCodeApi();
document.getElementById('btn_submit').onclick = () => {
@ -12,16 +11,16 @@ document.getElementById('btn_submit').onclick = () => {
function submitFunc() {
let outputFileName = document.getElementById('output_file_name').value;
let initmemSize = document.getElementById('initial_mem_size').value;
let maxmemSize = document.getElementById('max_mem_size').value;
let initMemSize = document.getElementById('initial_mem_size').value;
let maxMemSize = document.getElementById('max_mem_size').value;
let stackSize = document.getElementById('stack_size').value;
let exportedSymbols = document.getElementById('exported_symbols').value;
vscode.postMessage({
command: 'config_build_target',
outputFileName: outputFileName,
initmemSize: initmemSize,
maxmemSize: maxmemSize,
initMemSize: initMemSize,
maxMemSize: maxMemSize,
stackSize: stackSize,
exportedSymbols: exportedSymbols,
});

View File

@ -9,8 +9,6 @@ import * as os from 'os';
export class WasmDebugConfigurationProvider
implements vscode.DebugConfigurationProvider
{
constructor() {}
/* default port set as 1234 */
private port = 1234;
private hostPath!: string;
@ -29,7 +27,7 @@ export class WasmDebugConfigurationProvider
return this.providerPromise;
}
public setDebugConfig(hostPath: string, port: number) {
public setDebugConfig(hostPath: string, port: number): void {
this.port = port;
this.hostPath = hostPath;
/* linux and windows has different debug configuration */
@ -57,7 +55,7 @@ export class WasmDebugConfigurationProvider
}
}
public getDebugConfig() {
public getDebugConfig(): vscode.DebugConfiguration {
return this.wasmDebugConfig;
}
}

View File

@ -26,11 +26,11 @@ export class DecorationProvider implements vscode.FileDecorationProvider {
public onDidChangeFileDecorations: vscode.Event<
vscode.Uri | vscode.Uri[] | undefined
>;
private _eventEmiter: vscode.EventEmitter<vscode.Uri | vscode.Uri[]>;
private eventEmitter: vscode.EventEmitter<vscode.Uri | vscode.Uri[]>;
constructor() {
this._eventEmiter = new vscode.EventEmitter();
this.onDidChangeFileDecorations = this._eventEmiter.event;
this.eventEmitter = new vscode.EventEmitter();
this.onDidChangeFileDecorations = this.eventEmitter.event;
this.disposables.push(
vscode.window.registerFileDecorationProvider(this)
);
@ -39,34 +39,27 @@ export class DecorationProvider implements vscode.FileDecorationProvider {
public provideFileDecoration(
uri: vscode.Uri
): vscode.ProviderResult<vscode.FileDecoration> {
let currentPrjDir,
prjConfigDir,
configFilePath,
configData,
includePathArr = new Array(),
excludeFileArr = new Array(),
pathRelative;
/* Read include_paths and exclude_fils from the config file */
currentPrjDir =
const currentPrjDir =
os.platform() === 'win32'
? (vscode.workspace.workspaceFolders?.[0].uri.fsPath as string)
: os.platform() === 'linux' || os.platform() === 'darwin'
? (currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri
.path as string)
? (vscode.workspace.workspaceFolders?.[0].uri.path as string)
: '';
pathRelative = (uri.fsPath ? uri.fsPath : uri.toString()).replace(
const pathRelative = (uri.fsPath ? uri.fsPath : uri.toString()).replace(
currentPrjDir,
'..'
);
prjConfigDir = path.join(currentPrjDir, '.wamr');
configFilePath = path.join(prjConfigDir, 'compilation_config.json');
const prjConfigDir = path.join(currentPrjDir, '.wamr');
const configFilePath = path.join(
prjConfigDir,
'compilation_config.json'
);
if (readFromFile(configFilePath) !== '') {
configData = JSON.parse(readFromFile(configFilePath));
includePathArr = configData['include_paths'];
excludeFileArr = configData['exclude_files'];
const configData = JSON.parse(readFromFile(configFilePath));
const includePathArr = configData['includePaths'];
const excludeFileArr = configData['excludeFiles'];
if (includePathArr.indexOf(pathRelative) > -1) {
return DECORATION_INCLUDE_PATHS;
@ -81,7 +74,7 @@ export class DecorationProvider implements vscode.FileDecorationProvider {
}
public updateDecorationsForSource(uri: vscode.Uri): void {
this._eventEmiter.fire(uri);
this.eventEmitter.fire(uri);
}
}

View File

@ -26,13 +26,20 @@ import {
let wasmTaskProvider: WasmTaskProvider;
let wasmDebugConfigProvider: WasmDebugConfigurationProvider;
var currentPrjDir = '';
var extensionPath = '';
var isWasmProject = false;
let currentPrjDir = '';
let isWasmProject = false;
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export async function activate(context: vscode.ExtensionContext) {
var OS_PLATFORM = '',
buildScript = '',
const extensionPath = context.extensionPath;
const osPlatform = os.platform();
const wamrVersion = getWAMRExtensionVersion(context);
const typeMap = new Map<string, string>();
const scriptMap = new Map<string, string>();
/* set relative path of build.bat|sh script */
const scriptPrefix = 'resource/scripts/';
let buildScript = '',
runScript = '',
debugScript = '',
destroyScript = '',
@ -40,40 +47,27 @@ export async function activate(context: vscode.ExtensionContext) {
runScriptFullPath = '',
debugScriptFullPath = '',
destroyScriptFullPath = '',
typeMap = new Map(),
/* include paths array used for written into config file */
includePathArr = new Array(),
includePathArr = new Array<string>(),
/* exclude files array used for written into config file */
excludeFileArr = new Array(),
scriptMap = new Map();
const wamrVersion = getWAMRExtensionVersion(context);
/**
* Get OS platform information for differ windows and linux execution script
*/
OS_PLATFORM = os.platform();
excludeFileArr = new Array<string>();
/**
* Provide Build & Run Task with Task Provider instead of "tasks.json"
*/
/* set relative path of build.bat|sh script */
let scriptPrefix = 'resource/scripts/';
if (OS_PLATFORM === 'win32') {
if (osPlatform === 'win32') {
buildScript = scriptPrefix.concat('build.bat');
runScript = scriptPrefix.concat('run.bat');
debugScript = scriptPrefix.concat('boot_debugger_server.bat');
destroyScript = scriptPrefix.concat('destroy.bat');
} else if (OS_PLATFORM === 'linux' || OS_PLATFORM === 'darwin') {
} else if (osPlatform === 'linux' || osPlatform === 'darwin') {
buildScript = scriptPrefix.concat('build.sh');
runScript = scriptPrefix.concat('run.sh');
debugScript = scriptPrefix.concat('boot_debugger_server.sh');
destroyScript = scriptPrefix.concat('destroy.sh');
}
extensionPath = context.extensionPath;
buildScriptFullPath = path.join(extensionPath, buildScript);
runScriptFullPath = path.join(extensionPath, runScript);
debugScriptFullPath = path.join(extensionPath, debugScript);
@ -94,10 +88,10 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.tasks.registerTaskProvider('wasm', wasmTaskProvider);
if (vscode.workspace.workspaceFolders?.[0]) {
if (OS_PLATFORM === 'win32') {
if (osPlatform === 'win32') {
currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri
.fsPath as string;
} else if (OS_PLATFORM === 'linux' || OS_PLATFORM === 'darwin') {
} else if (osPlatform === 'linux' || osPlatform === 'darwin') {
currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri
.path as string;
}
@ -107,7 +101,7 @@ export async function activate(context: vscode.ExtensionContext) {
* it not, `build`, `run` and `debug` will be disabled
*/
if (currentPrjDir !== '') {
let wamrFolder = fileSystem
const wamrFolder = fileSystem
.readdirSync(currentPrjDir, {
withFileTypes: true,
})
@ -133,7 +127,7 @@ export async function activate(context: vscode.ExtensionContext) {
.getConfiguration()
.get('C_Cpp.default.systemIncludePath');
let LibcBuiltinHeaderPath = path.join(
const libcBuiltinHeaderPath = path.join(
extensionPath,
'resource/wamr-sdk/libc-builtin-sysroot/include'
);
@ -141,17 +135,17 @@ export async function activate(context: vscode.ExtensionContext) {
if (newIncludeInCppArr !== undefined) {
/* in case the configuration has not been set up, push directly */
if (newIncludeInCppArr === null) {
newIncludeInCppArr = new Array();
newIncludeInCppArr.push(LibcBuiltinHeaderPath);
newIncludeInCppArr = [];
newIncludeInCppArr.push(libcBuiltinHeaderPath);
} else {
/* if the configuration has been set up, check the condition */
if (
/* include libc-builtin-sysroot */
newIncludeInCppArr.indexOf(
LibcBuiltinHeaderPath
libcBuiltinHeaderPath
) < 0
) {
newIncludeInCppArr.push(LibcBuiltinHeaderPath);
newIncludeInCppArr.push(libcBuiltinHeaderPath);
}
}
@ -185,21 +179,21 @@ export async function activate(context: vscode.ExtensionContext) {
]);
if (readFromConfigFile() !== '') {
let configData = JSON.parse(readFromConfigFile());
includePathArr = configData['include_paths'];
excludeFileArr = configData['exclude_files'];
const configData = JSON.parse(readFromConfigFile());
includePathArr = configData['includePaths'];
excludeFileArr = configData['excludeFiles'];
if (Object.keys(configData['build_args']).length !== 0) {
TargetConfigPanel.BUILD_ARGS = configData['build_args'];
if (Object.keys(configData['buildArgs']).length !== 0) {
TargetConfigPanel.buildArgs = configData['buildArgs'];
}
}
let disposableNewProj = vscode.commands.registerCommand(
const disposableNewProj = vscode.commands.registerCommand(
'wamride.newProject',
() => {
let _ok = 'Set up now';
let _cancle = 'Maybe later';
let curWorkspace = vscode.workspace
const okStr = 'Set up now';
const cancelStr = 'Maybe later';
const curWorkspace = vscode.workspace
.getConfiguration()
.get('WAMR-IDE.configWorkspace');
@ -208,11 +202,11 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.window
.showWarningMessage(
'Please setup your workspace firstly.',
_ok,
_cancle
okStr,
cancelStr
)
.then(item => {
if (item === _ok) {
if (item === okStr) {
vscode.commands.executeCommand(
'wamride.changeWorkspace'
);
@ -233,10 +227,10 @@ export async function activate(context: vscode.ExtensionContext) {
.get('WAMR-IDE.configWorkspace') +
'',
},
_ok
okStr
)
.then(item => {
if (item === _ok) {
if (item === okStr) {
vscode.commands.executeCommand(
'wamride.changeWorkspace'
);
@ -250,7 +244,7 @@ export async function activate(context: vscode.ExtensionContext) {
}
);
let disposableTargetConfig = vscode.commands.registerCommand(
const disposableTargetConfig = vscode.commands.registerCommand(
'wamride.targetConfig',
() => {
if (currentPrjDir !== '') {
@ -264,16 +258,16 @@ export async function activate(context: vscode.ExtensionContext) {
}
);
let disposableChangeWorkspace = vscode.commands.registerCommand(
const disposableChangeWorkspace = vscode.commands.registerCommand(
'wamride.changeWorkspace',
async () => {
let options: vscode.OpenDialogOptions = {
const options: vscode.OpenDialogOptions = {
canSelectFiles: false,
canSelectFolders: true,
openLabel: 'Select Workspace',
};
let Workspace = await vscode.window
const workSpace = await vscode.window
.showOpenDialog(options)
.then(res => {
if (res) {
@ -284,21 +278,21 @@ export async function activate(context: vscode.ExtensionContext) {
});
/* update workspace value to vscode global settings */
if (Workspace !== '' && Workspace !== undefined) {
if (workSpace !== '' && workSpace !== undefined) {
await vscode.workspace
.getConfiguration()
.update(
'WAMR-IDE.configWorkspace',
Workspace.trim(),
workSpace.trim(),
vscode.ConfigurationTarget.Global
)
.then(
success => {
() => {
vscode.window.showInformationMessage(
'Workspace has been set up successfully!'
);
},
error => {
() => {
vscode.window.showErrorMessage(
'Set up Workspace failed!'
);
@ -308,7 +302,7 @@ export async function activate(context: vscode.ExtensionContext) {
}
);
let disposableBuild = vscode.commands.registerCommand(
const disposableBuild = vscode.commands.registerCommand(
'wamride.build',
() => {
if (!isWasmProject) {
@ -327,7 +321,7 @@ export async function activate(context: vscode.ExtensionContext) {
'Destroy: Wasm-Container-Before-Build'
)
.then(() => {
let disposable = vscode.tasks.onDidEndTaskProcess(t => {
const disposable = vscode.tasks.onDidEndTaskProcess(t => {
if (
t.execution.task.name ===
'Wasm-Container-Before-Build'
@ -345,7 +339,7 @@ export async function activate(context: vscode.ExtensionContext) {
)
.then(() => {
/* destroy the wasm-toolchain-ctr after building */
let disposable_aft =
const disposableAft =
vscode.tasks.onDidEndTask(a => {
if (
a.execution.task.name ===
@ -361,7 +355,7 @@ export async function activate(context: vscode.ExtensionContext) {
.then(() => {
/* dispose the event after this building process
*/
disposable_aft.dispose();
disposableAft.dispose();
});
}
});
@ -374,7 +368,7 @@ export async function activate(context: vscode.ExtensionContext) {
}
);
let disposableDebug = vscode.commands.registerCommand(
const disposableDebug = vscode.commands.registerCommand(
'wamride.debug',
async () => {
if (!isWasmProject) {
@ -414,7 +408,7 @@ export async function activate(context: vscode.ExtensionContext) {
)
.then(() => {
/* execute the debug task when destroy task finish */
let disposable_bfr = vscode.tasks.onDidEndTask(t => {
const disposableBfr = vscode.tasks.onDidEndTask(t => {
if (
t.execution.task.name ===
'Wasm-Container-Before-Debug'
@ -432,7 +426,7 @@ export async function activate(context: vscode.ExtensionContext) {
)
.then(() => {
/* register to listen debug session finish event */
let dispose_aft =
const disposableAft =
vscode.debug.onDidTerminateDebugSession(
s => {
if (
@ -455,18 +449,19 @@ export async function activate(context: vscode.ExtensionContext) {
'Debug: Wasm'
);
dispose_aft.dispose();
disposableAft.dispose();
}
);
});
});
}
disposable_bfr.dispose();
disposableBfr.dispose();
});
});
}
);
let disposableRun = vscode.commands.registerCommand('wamride.run', () => {
const disposableRun = vscode.commands.registerCommand('wamride.run', () => {
if (!isWasmProject) {
vscode.window.showErrorMessage('run failed', {
modal: true,
@ -489,7 +484,7 @@ export async function activate(context: vscode.ExtensionContext) {
'Destroy: Wasm-Container-Before-Run'
)
.then(() => {
let dispose_bfr = vscode.tasks.onDidEndTaskProcess(e => {
const disposableAft = vscode.tasks.onDidEndTaskProcess(e => {
if (e.execution.task.name === 'Wasm-Container-Before-Run') {
/* make sure that run wasm task will be executed after destroy task finish */
vscode.commands
@ -499,25 +494,24 @@ export async function activate(context: vscode.ExtensionContext) {
)
.then(() => {
if (e.exitCode !== 0) {
dispose_bfr.dispose();
disposableAft.dispose();
return;
}
});
dispose_bfr.dispose();
disposableAft.dispose();
}
});
});
});
let disposableToggleIncludePath = vscode.commands.registerCommand(
const disposableToggleIncludePath = vscode.commands.registerCommand(
'wamride.build.toggleStateIncludePath',
fileUri => {
let pathRelative: string;
let path =
const path =
fileUri._fsPath !== null && fileUri._fsPath !== undefined
? fileUri._fsPath
: vscode.Uri.parse(fileUri.path as string).fsPath;
pathRelative = path.replace(currentPrjDir, '..');
const pathRelative = path.replace(currentPrjDir, '..');
if (includePathArr.indexOf(pathRelative) > -1) {
/* this folder has been added to include path, remove it */
@ -531,25 +525,23 @@ export async function activate(context: vscode.ExtensionContext) {
writeIntoConfigFile(
includePathArr,
excludeFileArr,
TargetConfigPanel.BUILD_ARGS
TargetConfigPanel.buildArgs
);
decorationProvider.updateDecorationsForSource(fileUri);
}
);
let disposableToggleExcludeFile = vscode.commands.registerCommand(
const disposableToggleExcludeFile = vscode.commands.registerCommand(
'wamride.build.toggleStateExclude',
fileUri => {
let pathRelative: string;
let path =
const path =
fileUri._fsPath !== null && fileUri._fsPath !== undefined
? fileUri._fsPath
: vscode.Uri.parse(fileUri.path as string).fsPath;
/* replace the current project absolute path with .. to change to relative path */
pathRelative = path.replace(currentPrjDir, '..');
const pathRelative = path.replace(currentPrjDir, '..');
if (excludeFileArr.indexOf(pathRelative) > -1) {
excludeFileArr = excludeFileArr.filter(val => {
@ -562,7 +554,7 @@ export async function activate(context: vscode.ExtensionContext) {
writeIntoConfigFile(
includePathArr,
excludeFileArr,
TargetConfigPanel.BUILD_ARGS
TargetConfigPanel.buildArgs
);
/* update decoration for this source file */
@ -570,14 +562,14 @@ export async function activate(context: vscode.ExtensionContext) {
}
);
let disposableOpenFolder = vscode.commands.registerCommand(
const disposableOpenFolder = vscode.commands.registerCommand(
'wamride.openFolder',
() => {
/* get projects list under current workspace */
let _ok = 'Set up now';
let _cancle = 'Maybe later';
let _create = 'Create now';
let curWorkspace = vscode.workspace
const okStr = 'Set up now';
const cancelStr = 'Maybe later';
const createStr = 'Create now';
const curWorkspace = vscode.workspace
.getConfiguration()
.get('WAMR-IDE.configWorkspace') as string;
@ -586,11 +578,11 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.window
.showWarningMessage(
'Please setup your workspace firstly.',
_ok,
_cancle
okStr,
cancelStr
)
.then(item => {
if (item === _ok) {
if (item === okStr) {
vscode.commands.executeCommand(
'wamride.changeWorkspace'
);
@ -611,10 +603,10 @@ export async function activate(context: vscode.ExtensionContext) {
.get('WAMR-IDE.configWorkspace') +
'',
},
_ok
okStr
)
.then(item => {
if (item === _ok) {
if (item === okStr) {
vscode.commands.executeCommand(
'wamride.changeWorkspace'
);
@ -640,7 +632,7 @@ export async function activate(context: vscode.ExtensionContext) {
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);
let projFilesArr = directoryArr.filter(obj => {
const projFilesArr = directoryArr.filter(obj => {
if (checkIfWasmProj(path.join(curWorkspace, obj))) {
return true;
}
@ -650,11 +642,11 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.window
.showWarningMessage(
'Current workspace is empty, please create your project firstly.',
_create,
_cancle
createStr,
cancelStr
)
.then(item => {
if (item === _create) {
if (item === createStr) {
vscode.commands.executeCommand(
'wamride.newProject'
);
@ -673,18 +665,18 @@ export async function activate(context: vscode.ExtensionContext) {
return;
}
let _path = curWorkspace.concat(
OS_PLATFORM === 'win32'
const path = curWorkspace.concat(
osPlatform === 'win32'
? '\\'
: OS_PLATFORM === 'linux' ||
OS_PLATFORM === 'darwin'
: osPlatform === 'linux' ||
osPlatform === 'darwin'
? '/'
: '',
option
);
/* open the selected wasm project */
openWindoWithSituation(vscode.Uri.file(_path));
openWindowWithSituation(vscode.Uri.file(path));
});
}
}
@ -713,13 +705,14 @@ export async function activate(context: vscode.ExtensionContext) {
}
}
function openWindoWithSituation(uri: vscode.Uri) {
function openWindowWithSituation(uri: vscode.Uri) {
/**
* check if the workspace folder is empty,
* if yes, open new window, else open in current window
*/
let isWorkspaceEmpty: boolean;
isWorkspaceEmpty = !vscode.workspace.workspaceFolders?.[0] ? true : false;
const isWorkspaceEmpty = !vscode.workspace.workspaceFolders?.[0]
? true
: false;
isWorkspaceEmpty === false
? vscode.commands.executeCommand('vscode.openFolder', uri, {
@ -731,11 +724,11 @@ function openWindoWithSituation(uri: vscode.Uri) {
}
interface BuildArgs {
output_file_name: string;
init_memory_size: string;
max_memory_size: string;
stack_size: string;
exported_symbols: string;
outputFileName: string;
initMemorySize: string;
maxMemorySize: string;
stackSize: string;
exportedSymbols: string;
}
/**
@ -748,25 +741,25 @@ export function writeIntoConfigFile(
includePathArr: string[],
excludeFileArr: string[],
buildArgs?: BuildArgs
) {
let jsonStr = JSON.stringify(
): void {
const jsonStr = JSON.stringify(
{
include_paths: includePathArr,
exclude_files: excludeFileArr,
build_args: buildArgs ? buildArgs : '{}',
includePaths: includePathArr,
excludeFiles: excludeFileArr,
buildArgs: buildArgs ? buildArgs : '{}',
},
null,
'\t'
);
let prjConfigDir = path.join(currentPrjDir, '.wamr');
let configFilePath = path.join(prjConfigDir, 'compilation_config.json');
const prjConfigDir = path.join(currentPrjDir, '.wamr');
const configFilePath = path.join(prjConfigDir, 'compilation_config.json');
writeIntoFile(configFilePath, jsonStr);
}
export function readFromConfigFile(): string {
let prjConfigDir = path.join(currentPrjDir, '.wamr');
let configFilePath = path.join(prjConfigDir, 'compilation_config.json');
const prjConfigDir = path.join(currentPrjDir, '.wamr');
const configFilePath = path.join(prjConfigDir, 'compilation_config.json');
return readFromFile(configFilePath);
}
@ -778,9 +771,9 @@ function generateCMakeFile(
excludeFileArr: string[]
): void {
// -Wl,--export=${EXPORT_SYMBOLS}
let srcFilePath = path.join(currentPrjDir, 'src');
let prjConfigDir = path.join(currentPrjDir, '.wamr');
let cmakeFilePath = path.join(prjConfigDir, 'project.cmake');
const srcFilePath = path.join(currentPrjDir, 'src');
const prjConfigDir = path.join(currentPrjDir, '.wamr');
const cmakeFilePath = path.join(prjConfigDir, 'project.cmake');
let strIncludeList = 'set (PROJECT_INCLUDES';
let strSrcList = 'set (PROJECT_SRC_LIST';
@ -795,17 +788,16 @@ function generateCMakeFile(
let i, s, e: number;
/* change the absolute path into relative path */
let _re = currentPrjDir;
let _substr = '${CMAKE_CURRENT_SOURCE_DIR}/..';
const _re = currentPrjDir;
const _substr = '${CMAKE_CURRENT_SOURCE_DIR}/..';
let srcPathArr: Array<{ path: string }> | undefined;
/**
* set PROJECT_SRC_LIST
* default ADD every c OR c++ OR cpp under the src/ path
* except the files saved in the exclude_files array
* except the files saved in the excludeFiles array
*/
srcPathArr = getAllSrcFiles(srcFilePath);
const srcPathArr = getAllSrcFiles(srcFilePath);
if (srcPathArr === undefined) {
return;
@ -818,46 +810,46 @@ function generateCMakeFile(
) === -1
) {
/* replace currentPrjDir with ${CMAKE_CURRENT_SOURCE_DIR} */
let _newStr = srcPathArr[s].path
const newStr = srcPathArr[s].path
.replace(_re, _substr)
.replace(/\\/g, '/');
strSrcList = strSrcList.concat(' ', _newStr);
strSrcList = strSrcList.concat(' ', newStr);
}
}
strSrcList = strSrcList.concat(' )');
for (i = 0; i < includePathArr.length; i++) {
let _newStr = includePathArr[i]
const newStr = includePathArr[i]
.replace(/../, _substr)
.replace(/\\/g, '/');
strIncludeList = strIncludeList.concat(' ', _newStr);
strIncludeList = strIncludeList.concat(' ', newStr);
}
strIncludeList = strIncludeList.concat(' )');
/* set up user customized input in configBuildArgs webview */
strOutputFileName = strOutputFileName.concat(
' ',
TargetConfigPanel.BUILD_ARGS.output_file_name + ')'
TargetConfigPanel.buildArgs.outputFileName + ')'
);
strInitMemSize = strInitMemSize.concat(
' ',
TargetConfigPanel.BUILD_ARGS.init_memory_size + ')'
TargetConfigPanel.buildArgs.initMemorySize + ')'
);
strMaxMemSize = strMaxMemSize.concat(
' ',
TargetConfigPanel.BUILD_ARGS.max_memory_size + ')'
TargetConfigPanel.buildArgs.maxMemorySize + ')'
);
strStackSize = strStackSize.concat(
' ',
TargetConfigPanel.BUILD_ARGS.stack_size + ')'
TargetConfigPanel.buildArgs.stackSize + ')'
);
let exportedSymbolArr =
TargetConfigPanel.BUILD_ARGS.exported_symbols.split(',');
const exportedSymbolArr =
TargetConfigPanel.buildArgs.exportedSymbols.split(',');
strExportedSymbols = strExportedSymbols.concat(' "');
@ -901,7 +893,7 @@ function getAllSrcFiles(_path: string) {
const folders = entries.filter(folder => folder.isDirectory());
for (const folder of folders) {
let fileArr = getAllSrcFiles(path.join(_path, folder.name));
const fileArr = getAllSrcFiles(path.join(_path, folder.name));
fileArr ? files.push(...fileArr) : '';
}
@ -911,7 +903,7 @@ function getAllSrcFiles(_path: string) {
}
}
function checkIfBuildSuccess(): Boolean {
function checkIfBuildSuccess(): boolean {
try {
let wasmExist = false;
const entries = fileSystem.readdirSync(
@ -933,10 +925,10 @@ function checkIfBuildSuccess(): Boolean {
}
}
function checkIfWasmProj(_path: string): Boolean {
function checkIfWasmProj(path: string): boolean {
try {
let isWasmProj = false;
const entries = fileSystem.readdirSync(_path, {
const entries = fileSystem.readdirSync(path, {
withFileTypes: true,
});

View File

@ -29,8 +29,8 @@ export class WasmTaskProvider implements vscode.TaskProvider {
public provideTasks(): Thenable<vscode.Task[]> | undefined {
if (!this.wasmPromise) {
/* target name is used for generated aot target */
let targetName =
TargetConfigPanel.BUILD_ARGS.output_file_name.split('.')[0];
const targetName =
TargetConfigPanel.buildArgs.outputFileName.split('.')[0];
if (
os.platform() === 'linux' ||
@ -219,7 +219,10 @@ export class WasmTaskProvider implements vscode.TaskProvider {
* @param _task
* @returns
*/
public resolveTask(_task: vscode.Task): vscode.Task | undefined {
public resolveTask(task: vscode.Task): vscode.Task | undefined {
if (task) {
return task;
}
return undefined;
}
}

View File

@ -31,7 +31,7 @@ export function createDirectory(
return false;
}
let parent = path.dirname(dest);
const parent = path.dirname(dest);
if (!createDirectory(parent, mode)) {
return false;
}
@ -44,6 +44,7 @@ export function createDirectory(
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function copyFiles(src: string, dest: string, flags?: number): boolean {
try {
fileSystem.copyFileSync(src, dest);
@ -64,7 +65,7 @@ export function writeIntoFile(path: string, data: string): void {
export function readFromFile(path: string): string {
try {
let data = fileSystem.readFileSync(path, { encoding: 'utf-8' });
const data = fileSystem.readFileSync(path, { encoding: 'utf-8' });
return data as string;
} catch (err) {
vscode.window.showErrorMessage(err as string);
@ -114,9 +115,9 @@ export function checkIfFileExists(path: string): boolean {
return false;
}
export function checkFolderName(folderName: string) {
export function checkFolderName(folderName: string): boolean {
let invalidCharacterArr: string[] = [];
var valid = true;
let valid = true;
if (folderName.length > 255) {
valid = false;
@ -143,6 +144,7 @@ export function downloadFile(
): Promise<void> {
return new Promise((resolve, reject) => {
const file = fileSystem.createWriteStream(destinationPath);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const stream = request(url, undefined, (error, response, body) => {
if (response.statusCode !== 200) {
reject(

View File

@ -9,6 +9,6 @@ export function getUri(
webview: Webview,
extensionUri: Uri,
pathList: string[]
) {
): Uri {
return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList));
}

View File

@ -37,6 +37,7 @@ function getLLDBUnzipFilePath(destinationFolder: string, filename: string) {
export function getWAMRExtensionVersion(
context: vscode.ExtensionContext
): string {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require(path.join(context.extensionPath, 'package.json')).version;
}
@ -64,7 +65,9 @@ export function isLLDBInstalled(context: vscode.ExtensionContext): boolean {
return checkIfFileExists(lldbBinaryPath);
}
export async function promptInstallLLDB(context: vscode.ExtensionContext) {
export async function promptInstallLLDB(
context: vscode.ExtensionContext
): Promise<void> {
const extensionPath = context.extensionPath;
const setupPrompt = 'setup';
const skipPrompt = 'skip';
@ -111,5 +114,7 @@ export async function promptInstallLLDB(context: vscode.ExtensionContext) {
);
// Remove the bundle.zip
fs.unlink(lldbZipPath, () => {});
fs.unlink(lldbZipPath, () => {
return;
});
}

View File

@ -15,35 +15,37 @@ import {
import { getUri } from '../utilities/getUri';
export class NewProjectPanel {
static USER_SET_WORKSPACE: string;
public static userSetWorkSpace: string;
public static currentPanel: NewProjectPanel | undefined;
private readonly _panel: vscode.WebviewPanel;
private _disposables: vscode.Disposable[] = [];
private readonly viewPanel: vscode.WebviewPanel;
private disposableArr: vscode.Disposable[] = [];
static readonly EXCUTION_SUCCESS: number = 0;
static readonly DIR_EXSITED_ERR: number = -1;
static readonly USER_INTPUT_ERR: number = -2;
static readonly DIR_PATH_INVALID_ERR: number = -3;
private static readonly executionSuccess = 0;
private static readonly dirExistedError = -1;
private static readonly userInputError = -2;
private static readonly dirPathInvalidError = -3;
constructor(extensionUri: vscode.Uri, panel: vscode.WebviewPanel) {
this._panel = panel;
this._panel.webview.html = this._getHtmlForWebview(
this._panel.webview,
this.viewPanel = panel;
this.viewPanel.webview.html = this.getHtmlForWebview(
this.viewPanel.webview,
extensionUri,
'resource/webview/page/newProject.html'
);
this._setWebviewMessageListener(this._panel.webview, extensionUri);
this._panel.onDidDispose(this.dispose, null, this._disposables);
this._setWebviewMessageListener(this.viewPanel.webview, extensionUri);
this.viewPanel.onDidDispose(this.dispose, null, this.disposableArr);
}
public static render(context: vscode.ExtensionContext) {
NewProjectPanel.USER_SET_WORKSPACE = vscode.workspace
public static render(context: vscode.ExtensionContext): void {
NewProjectPanel.userSetWorkSpace = vscode.workspace
.getConfiguration()
.get('WAMR-IDE.configWorkspace') as string;
/* check if current panel is initialized */
if (NewProjectPanel.currentPanel) {
NewProjectPanel.currentPanel._panel.reveal(vscode.ViewColumn.One);
NewProjectPanel.currentPanel.viewPanel.reveal(
vscode.ViewColumn.One
);
} else {
const panel = vscode.window.createWebviewPanel(
'newProject',
@ -62,25 +64,25 @@ export class NewProjectPanel {
}
}
private _creatNewProject(
private createNewProject(
projName: string,
template: string,
extensionUri: vscode.Uri
): number {
if (projName === '' || template === '') {
return NewProjectPanel.USER_INTPUT_ERR;
return NewProjectPanel.userInputError;
}
if (!checkFolderName(projName)) {
return NewProjectPanel.DIR_PATH_INVALID_ERR;
return NewProjectPanel.dirPathInvalidError;
}
let ROOT_PATH = path.join(NewProjectPanel.USER_SET_WORKSPACE, projName);
let EXT_PATH = extensionUri.fsPath;
const ROOT_PATH = path.join(NewProjectPanel.userSetWorkSpace, projName);
const EXT_PATH = extensionUri.fsPath;
if (fs.existsSync(ROOT_PATH)) {
if (fs.lstatSync(ROOT_PATH).isDirectory()) {
return NewProjectPanel.DIR_EXSITED_ERR;
return NewProjectPanel.dirExistedError;
}
}
@ -98,14 +100,14 @@ export class NewProjectPanel {
path.join(ROOT_PATH, '.wamr/project.cmake')
);
return NewProjectPanel.EXCUTION_SUCCESS;
return NewProjectPanel.executionSuccess;
}
public _getHtmlForWebview(
public getHtmlForWebview(
webview: vscode.Webview,
extensionUri: vscode.Uri,
templatePath: string
) {
): string {
const toolkitUri = getUri(webview, extensionUri, [
'node_modules',
'@vscode',
@ -146,14 +148,14 @@ export class NewProjectPanel {
message => {
switch (message.command) {
case 'create_new_project':
let createNewProjectStatus = this._creatNewProject(
const createNewProjectStatus = this.createNewProject(
message.projectName,
message.template,
extensionUri
);
if (
createNewProjectStatus ===
NewProjectPanel.EXCUTION_SUCCESS
NewProjectPanel.executionSuccess
) {
webview.postMessage({
command: 'proj_creation_finish',
@ -161,17 +163,17 @@ export class NewProjectPanel {
});
} else if (
createNewProjectStatus ===
NewProjectPanel.DIR_EXSITED_ERR
NewProjectPanel.dirExistedError
) {
vscode.window.showErrorMessage(
'Project : ' +
message.projectName +
' exsits in your current root path, please change project name or root path!'
' exists in your current root path, please change project name or root path!'
);
return;
} else if (
createNewProjectStatus ===
NewProjectPanel.USER_INTPUT_ERR
NewProjectPanel.userInputError
) {
vscode.window.showErrorMessage(
'Please fill chart before your submit!'
@ -179,7 +181,7 @@ export class NewProjectPanel {
return;
} else if (
createNewProjectStatus ===
NewProjectPanel.DIR_PATH_INVALID_ERR
NewProjectPanel.dirPathInvalidError
) {
if (os.platform() === 'win32') {
vscode.window.showErrorMessage(
@ -203,19 +205,18 @@ export class NewProjectPanel {
message.projectName +
' will be opened!'
);
let isWorkspaceEmpty: boolean;
let projPath = path.join(
NewProjectPanel.USER_SET_WORKSPACE,
const projPath = path.join(
NewProjectPanel.userSetWorkSpace,
message.projectName
);
let uri = vscode.Uri.file(projPath);
const uri = vscode.Uri.file(projPath);
/**
* check if the vscode workspace folder is empty,
* if yes, open new window, else open in current window
*/
isWorkspaceEmpty = !vscode.workspace
const isWorkspaceEmpty = !vscode.workspace
.workspaceFolders?.[0]
? true
: false;
@ -233,7 +234,7 @@ export class NewProjectPanel {
);
case 'close_webview':
this._panel.dispose();
this.viewPanel.dispose();
return;
default:
@ -241,16 +242,16 @@ export class NewProjectPanel {
}
},
undefined,
this._disposables
this.disposableArr
);
}
private dispose() {
NewProjectPanel.currentPanel = undefined;
this._panel.dispose();
this.viewPanel.dispose();
while (this._disposables.length) {
const disposable = this._disposables.pop();
while (this.disposableArr.length) {
const disposable = this.disposableArr.pop();
if (disposable) {
disposable.dispose();
}

View File

@ -11,19 +11,19 @@ import { getUri } from '../utilities/getUri';
export class TargetConfigPanel {
public static currentPanel: TargetConfigPanel | undefined;
private readonly _panel: vscode.WebviewPanel;
private readonly viewPanel: vscode.WebviewPanel;
private _disposables: vscode.Disposable[] = [];
public static BUILD_ARGS = {
output_file_name: 'main.wasm',
init_memory_size: '131072',
max_memory_size: '131072',
stack_size: '4096',
exported_symbols: 'main',
public static buildArgs = {
outputFileName: 'main.wasm',
initMemorySize: '131072',
maxMemorySize: '131072',
stackSize: '4096',
exportedSymbols: 'main',
};
static readonly USER_INTPUT_ERR: number = -2;
static readonly EXCUTION_SUCCESS: number = 0;
private static readonly userInputError: number = -2;
private static readonly executionSuccess: number = 0;
/**
*
@ -31,24 +31,26 @@ export class TargetConfigPanel {
* @param panelName
*/
constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
this._panel = panel;
this._panel.webview.html = this._getHtmlForWebview(
this._panel.webview,
this.viewPanel = panel;
this.viewPanel.webview.html = this._getHtmlForWebview(
this.viewPanel.webview,
extensionUri,
'resource/webview/page/configBuildTarget.html'
);
this._panel.onDidDispose(this.dispose, null, this._disposables);
this._setWebviewMessageListener(this._panel.webview);
this.viewPanel.onDidDispose(this.dispose, null, this._disposables);
this._setWebviewMessageListener(this.viewPanel.webview);
}
/**
*
* @param context
*/
public static render(context: vscode.ExtensionContext) {
public static render(context: vscode.ExtensionContext): void {
/* check if current panel is initialized */
if (TargetConfigPanel.currentPanel) {
TargetConfigPanel.currentPanel._panel.reveal(vscode.ViewColumn.One);
TargetConfigPanel.currentPanel.viewPanel.reveal(
vscode.ViewColumn.One
);
} else {
const panel = vscode.window.createWebviewPanel(
'targetConfig',
@ -67,59 +69,56 @@ export class TargetConfigPanel {
}
}
private _configBuildArgs(
private configBuildArgs(
outputFileName: string,
initmemSize: string,
maxmemSize: string,
initMemSize: string,
maxMemSize: string,
stackSize: string,
exportedSymbols: string
): number {
if (
outputFileName === '' ||
initmemSize === '' ||
maxmemSize === '' ||
initMemSize === '' ||
maxMemSize === '' ||
stackSize === '' ||
exportedSymbols === ''
) {
return TargetConfigPanel.USER_INTPUT_ERR;
return TargetConfigPanel.userInputError;
}
let _configStr: string;
let includePathArr = new Array();
let excludeFileArr = new Array();
let configJson: any;
let includePathArr = [];
let excludeFileArr = [];
let _configObj = {
output_file_name: outputFileName,
init_memory_size: initmemSize,
max_memory_size: maxmemSize,
stack_size: stackSize,
exported_symbols: exportedSymbols,
const configObj = {
outputFileName: outputFileName,
initMemorySize: initMemSize,
maxMemorySize: maxMemSize,
stackSize: stackSize,
exportedSymbols: exportedSymbols,
};
const configStr = readFromConfigFile();
TargetConfigPanel.BUILD_ARGS = _configObj;
TargetConfigPanel.buildArgs = configObj;
_configStr = readFromConfigFile();
if (_configStr !== '' && _configStr !== undefined) {
configJson = JSON.parse(_configStr);
if (configStr !== '' && configStr !== undefined) {
const configJson = JSON.parse(configStr);
includePathArr =
configJson['include_paths'] === undefined
configJson['includePaths'] === undefined
? []
: configJson['include_paths'];
: configJson['includePaths'];
excludeFileArr =
configJson['exclude_files'] === undefined
configJson['excludeFiles'] === undefined
? []
: configJson['exclude_files'];
: configJson['excludeFiles'];
}
writeIntoConfigFile(
includePathArr,
excludeFileArr,
TargetConfigPanel.BUILD_ARGS
TargetConfigPanel.buildArgs
);
return TargetConfigPanel.EXCUTION_SUCCESS;
return TargetConfigPanel.executionSuccess;
}
private _getHtmlForWebview(
@ -158,23 +157,23 @@ export class TargetConfigPanel {
.replace(/(\${styleUri})/, styleUri.toString())
.replace(
/(\${output_file_val})/,
TargetConfigPanel.BUILD_ARGS.output_file_name
TargetConfigPanel.buildArgs.outputFileName
)
.replace(
/(\${initial_mem_size_val})/,
TargetConfigPanel.BUILD_ARGS.init_memory_size
TargetConfigPanel.buildArgs.initMemorySize
)
.replace(
/(\${max_mem_size_val})/,
TargetConfigPanel.BUILD_ARGS.max_memory_size
TargetConfigPanel.buildArgs.maxMemorySize
)
.replace(
/(\${stack_size_val})/,
TargetConfigPanel.BUILD_ARGS.stack_size
TargetConfigPanel.buildArgs.stackSize
)
.replace(
/(\${exported_symbols_val})/,
TargetConfigPanel.BUILD_ARGS.exported_symbols
TargetConfigPanel.buildArgs.exportedSymbols
);
return html;
@ -187,8 +186,8 @@ export class TargetConfigPanel {
case 'config_build_target':
if (
message.outputFileName === '' ||
message.initmemSize === '' ||
message.maxmemSize === '' ||
message.initMemSize === '' ||
message.maxMemSize === '' ||
message.stackSize === '' ||
message.exportedSymbols === ''
) {
@ -197,13 +196,13 @@ export class TargetConfigPanel {
);
return;
} else if (
this._configBuildArgs(
this.configBuildArgs(
message.outputFileName,
message.initmemSize,
message.maxmemSize,
message.initMemSize,
message.maxMemSize,
message.stackSize,
message.exportedSymbols
) === TargetConfigPanel.EXCUTION_SUCCESS
) === TargetConfigPanel.executionSuccess
) {
vscode.window
.showInformationMessage(
@ -211,7 +210,7 @@ export class TargetConfigPanel {
'OK'
)
.then(() => {
this._panel.dispose();
this.viewPanel.dispose();
return;
});
}
@ -227,7 +226,7 @@ export class TargetConfigPanel {
private dispose() {
TargetConfigPanel.currentPanel = undefined;
this._panel.dispose();
this.viewPanel.dispose();
while (this._disposables.length) {
const disposable = this._disposables.pop();

View File

@ -1,21 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"outDir": "out",
"lib": [
"es6"
],
"sourceMap": true,
"rootDir": "src",
"strict": true /* enable all strict type-checking options */
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
},
"exclude": [
"node_modules",
".vscode-test"
]
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"outDir": "out",
"lib": ["es6"],
"sourceMap": true,
"rootDir": "src",
"strict": true /* enable all strict type-checking options */
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
},
"exclude": ["node_modules", ".vscode-test"]
}