Initial commit: run current file in mission and hooks env

This commit is contained in:
Omelette 蛋卷 2024-01-09 00:28:07 -05:00
commit 33b493bc73
15 changed files with 3313 additions and 0 deletions

30
.eslintrc.json Normal file
View File

@ -0,0 +1,30 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"@typescript-eslint/naming-convention": [
"warn",
{
"selector": "import",
"format": [ "camelCase", "PascalCase" ]
}
],
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": [
"out",
"dist",
"**/*.d.ts"
]
}

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
out
dist
node_modules
.vscode-test/
*.vsix
vsc-extension-quickstart.md

5
.vscode-test.mjs Normal file
View File

@ -0,0 +1,5 @@
import { defineConfig } from '@vscode/test-cli';
export default defineConfig({
files: 'out/test/**/*.test.js',
});

8
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,8 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint",
"ms-vscode.extension-test-runner"
]
}

21
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,21 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}

14
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,14 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off",
"cSpell.words": [
"reimplementation"
]
}

20
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,20 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

11
.vscodeignore Normal file
View File

@ -0,0 +1,11 @@
.vscode/**
.vscode-test/**
src/**
.gitignore
.yarnrc
vsc-extension-quickstart.md
**/tsconfig.json
**/.eslintrc.json
**/*.map
**/*.ts
**/.vscode-test.*

9
CHANGELOG.md Normal file
View File

@ -0,0 +1,9 @@
# Change Log
All notable changes to the "dcs-lua-runner" extension will be documented in this file.
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
## [Unreleased]
- Initial release

71
README.md Normal file
View File

@ -0,0 +1,71 @@
# dcs-lua-runner README
This is the README for your extension "dcs-lua-runner". After writing up a brief description, we recommend including the following sections.
## Features
Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.
For example if there is an image subfolder under your extension project workspace:
\!\[feature X\]\(images/feature-x.png\)
> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.
## Requirements
If you have any requirements or dependencies, add a section describing those and how to install and configure them.
## Extension Settings
Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.
For example:
This extension contributes the following settings:
* `myExtension.enable`: Enable/disable this extension.
* `myExtension.thing`: Set to `blah` to do something.
## Known Issues
Calling out known issues can help limit users opening duplicate issues against your extension.
## Release Notes
Users appreciate release notes as you update your extension.
### 1.0.0
Initial release of ...
### 1.0.1
Fixed issue #.
### 1.1.0
Added features X, Y, and Z.
---
## Following extension guidelines
Ensure that you've read through the extensions guidelines and follow the best practices for creating your extension.
* [Extension Guidelines](https://code.visualstudio.com/api/references/extension-guidelines)
## Working with Markdown
You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:
* Split the editor (`Cmd+\` on macOS or `Ctrl+\` on Windows and Linux).
* Toggle preview (`Shift+Cmd+V` on macOS or `Shift+Ctrl+V` on Windows and Linux).
* Press `Ctrl+Space` (Windows, Linux, macOS) to see a list of Markdown snippets.
## For more information
* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)
**Enjoy!**

2890
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

101
package.json Normal file
View File

@ -0,0 +1,101 @@
{
"name": "dcs-lua-runner",
"displayName": "DCS Lua Runner",
"description": "Run lua code in DCS World Mission Scripting Environment (local or remote server). A reimplementation of the DCS Fiddle lua console in VS Code.",
"version": "0.0.1",
"engines": {
"vscode": "^1.85.0"
},
"categories": [
"Other"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"configuration": {
"title": "DCS Lua Runner",
"properties": {
"dcsLuaRunner.serverAddress": {
"type": "string",
"default": "127.0.0.1",
"description": "DCS server address."
},
"dcsLuaRunner.serverPort": {
"type": "number",
"default": 12080,
"description": "DCS Fiddle port."
},
"dcsLuaRunner.useHttps": {
"type": "boolean",
"default": false,
"description": "If server is behind a HTTPS reverse proxy. You should also change the port to 443."
},
"dcsLuaRunner.webAuthUsername": {
"type": "string",
"default": "username",
"description": "The username for authentication."
},
"dcsLuaRunner.webAuthPassword": {
"type": "string",
"default": "password",
"description": "The password for authentication."
}
}
},
"menus": {
"editor/title/run": [
{
"command": "dcs-lua-runner.run-file-mission",
"group": "navigation@0",
"when": "editorLangId == lua"
},
{
"command": "dcs-lua-runner.run-file-hooks",
"group": "navigation@1",
"when": "editorLangId == lua"
}
]
},
"commands": [
{
"command": "dcs-lua-runner.get-theatre",
"group": "navigation@0",
"title": "DCS Lua: Get Mission Theatre"
},
{
"command": "dcs-lua-runner.run-file-mission",
"group": "navigation@1",
"title": "DCS Lua: Run Current File in Mission Environment",
"icon": "$(run)"
},
{
"command": "dcs-lua-runner.run-file-hooks",
"group": "navigation@2",
"title": "DCS Lua: Run Current File in Hooks Environment",
"icon": "$(debug-coverage)"
}
]
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts",
"test": "vscode-test"
},
"devDependencies": {
"@types/mocha": "^10.0.6",
"@types/node": "18.x",
"@types/vscode": "^1.85.0",
"@typescript-eslint/eslint-plugin": "^6.15.0",
"@typescript-eslint/parser": "^6.15.0",
"@vscode/test-cli": "^0.0.4",
"@vscode/test-electron": "^2.3.8",
"eslint": "^8.56.0",
"typescript": "^5.3.3"
},
"dependencies": {
"axios": "^1.6.5"
}
}

95
src/extension.ts Normal file
View File

@ -0,0 +1,95 @@
import * as vscode from 'vscode';
import axios from 'axios';
import * as fs from 'fs';
import * as path from 'path';
async function runLua(lua: string, outputChannel: vscode.OutputChannel, filename: string = 'none', portOffset: boolean = false) {
const lua_base64 = Buffer.from(lua).toString('base64');
const config = vscode.workspace.getConfiguration('dcsLuaRunner');
const serverAddress = config.get('serverAddress') as string;
const serverPort = config.get('serverPort') as number + (portOffset ? 1 : 0);
const useHttps = config.get('useHttps') as boolean;
const authUsername = config.get('webAuthUsername') as string;
const authPassword = config.get('webAuthPassword') as string;
const protocol = useHttps ? 'https' : 'http';
const prefix = portOffset ? 'Hooks' : 'Mission';
try {
const response = await axios.get(`${protocol}://${serverAddress}:${serverPort}/${lua_base64}?env=default`, {
auth: {
username: authUsername,
password: authPassword
},
timeout: 3000
});
outputChannel.show(true);
if (response.data.hasOwnProperty('result')) {
outputChannel.appendLine(`[DCS] ${new Date().toLocaleString()} (${filename} > ${prefix}):\n${JSON.stringify(response.data.result, null, 2)}`);
} else {
outputChannel.appendLine(`[DCS] ${new Date().toLocaleString()} (${filename} > ${prefix}):\nResult not found in response.`);
}
} catch (error: any) {
if (error.response && error.response.status === 500) {
vscode.window.showErrorMessage('Internal server error occurred.');
outputChannel.appendLine(`[DCS] ${new Date().toLocaleString()} (${filename} > ${prefix}):\n${JSON.stringify(error.response.data.error, null, 2)}`);
} else {
vscode.window.showErrorMessage(`Error: ${error}`);
}
}
}
function getCurrentFileLua() {
const editor = vscode.window.activeTextEditor;
if (editor) {
const document = editor.document;
if (document.languageId === 'lua') {
const lua = document.getText();
const filename = path.basename(document.uri.fsPath);
return { lua, filename };
} else {
vscode.window.showErrorMessage('The active file is not a Lua file.');
}
} else {
vscode.window.showErrorMessage('No active file.');
}
return null;
}
export function activate(context: vscode.ExtensionContext) {
let outputChannel = vscode.window.createOutputChannel("DCS Return");
context.subscriptions.push(vscode.commands.registerCommand('dcs-lua-runner.get-theatre', async () => {
const lua = 'return env.mission.theatre';
await runLua(lua, outputChannel, 'env.mission.theatre');
}));
context.subscriptions.push(vscode.commands.registerCommand('dcs-lua-runner.run-file-mission', async () => {
const currentFileLua = getCurrentFileLua();
if (currentFileLua) {
const { lua, filename } = currentFileLua;
await runLua(lua, outputChannel, filename);
}
}));
context.subscriptions.push(vscode.commands.registerCommand('dcs-lua-runner.run-file-hooks', async () => {
const currentFileLua = getCurrentFileLua();
if (currentFileLua) {
const { lua, filename } = currentFileLua;
await runLua(lua, outputChannel, filename, true);
}
}));
// Update the 'luaFileActive' context when the active editor changes
vscode.window.onDidChangeActiveTextEditor(editor => {
if (editor) {
vscode.commands.executeCommand('setContext', 'luaFileActive', editor.document.languageId === 'lua');
}
});
// Set the 'luaFileActive' context for the current active editor
if (vscode.window.activeTextEditor) {
vscode.commands.executeCommand('setContext', 'luaFileActive', vscode.window.activeTextEditor.document.languageId === 'lua');
}
}
export function deactivate() {}

View File

@ -0,0 +1,15 @@
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../../extension';
suite('Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});

17
tsconfig.json Normal file
View File

@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "Node16",
"target": "ES2022",
"outDir": "out",
"lib": [
"ES2022"
],
"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. */
}
}