Compare commits

...
24 Commits
Author SHA1 Message Date
dutchie031 0c27905a43 updated the compiler to not leave whitespace when parsing tables
Publish Action Release / Derive release metadata (push) Successful in 4s
Publish Install Lua Addon Action / test_action (push) Successful in 7s
Publish Action Release / Publish tags (push) Successful in 5s
Publish Bundle Script Action / publish_action (push) Successful in 30s
Publish Action Release / Derive release metadata (push) Successful in 3s
Publish Action Release / Publish tags (push) Successful in 6s
Publish Install Lua Addon Action / publish_action (push) Successful in 13s
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 52s
2026-09-20 12:42:17 +02:00
dutchie031 51cd528040 updates to get it working again
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 6s
Publish Action Release / Derive release metadata (push) Successful in 6s
Publish Action Release / Publish tags (push) Successful in 10s
Publish Bundle Script Action / publish_action (push) Successful in 23s
2026-09-19 23:01:25 +02:00
dutchie031 7128a44adc updates to get it working again
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 5s
2026-09-19 23:00:57 +02:00
dutchie031 a46a3bb869 updates to get it working again
Publish Action Release / Derive release metadata (push) Successful in 4s
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 4s
Publish Action Release / Publish tags (push) Successful in 14s
Publish Bundle Script Action / publish_action (push) Successful in 30s
2026-09-19 22:58:34 +02:00
dutchie031 4a2dad60c6 updated reference after file moving
Publish Action Release / Derive release metadata (push) Successful in 3s
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 4s
Publish Action Release / Publish tags (push) Successful in 15s
Publish Bundle Script Action / publish_action (push) Successful in 33s
2026-09-19 22:54:04 +02:00
dutchie031 163b3e170c added package.lock
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 6s
Publish Action Release / Derive release metadata (push) Successful in 5s
Publish Action Release / Publish tags (push) Successful in 11s
Publish Bundle Script Action / publish_action (push) Successful in 24s
2026-09-19 22:47:52 +02:00
dutchie031 679271ec9e added package.lock
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 6s
2026-09-19 22:47:20 +02:00
dutchie031 c552cebbb6 Merge pull request 'Added Required logic if not found, and added better update logic' (#3) from feature/requireUpdates into main
Publish Action Release / Derive release metadata (push) Successful in 7s
Publish Install Lua Addon Action / test_action (push) Successful in 8s
Publish Action Release / Publish tags (push) Successful in 9s
Publish Bundle Script Action / publish_action (push) Successful in 38s
Publish Action Release / Derive release metadata (push) Successful in 4s
Publish Action Release / Publish tags (push) Successful in 10s
Publish Install Lua Addon Action / publish_action (push) Successful in 18s
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 55s
Reviewed-on: #3
2026-09-19 20:15:09 +00:00
dutchie031 949d72c394 Added Required logic if not found, and added better update logic 2026-09-19 22:13:03 +02:00
dutchie031 dcd1bf25e7 Added Required logic if not found, and added better update logic 2026-09-19 22:07:07 +02:00
dutchie031 45c988c989 updating flawed properties table definition
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 52s
2026-09-15 17:01:38 +02:00
dutchie031 2815c3e652 Updated type error
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 49s
2026-09-14 14:29:01 +02:00
dutchie031 4b311f8b4c Updated type error
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 6s
2026-09-14 14:27:56 +02:00
dutchie031 4712330faa Updated typo
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 55s
2026-09-14 12:27:11 +02:00
dutchie031 77ed355011 added trigger zones to mission table
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 56s
2026-09-14 12:06:37 +02:00
dutchie031 974d4a5e69 fixed naming error in MissionTable
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 51s
2026-09-14 11:50:33 +02:00
dutchie031 6c8adfea0d initial env.mission fields
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 51s
2026-09-14 11:27:31 +02:00
dutchie031 16599dce42 initial env.mission fields
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 5s
2026-09-14 11:27:13 +02:00
dutchie031 e1febc63f2 initial env.mission fields
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 56s
2026-09-14 11:11:24 +02:00
dutchie031 c7a65d6fbd Added test for publish bundle pipeline
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 5s
Publish Install Lua Addon Action / test_action (push) Successful in 8s
Publish Action Release / Derive release metadata (push) Successful in 6s
Publish Action Release / Publish tags (push) Successful in 10s
Publish Install Lua Addon Action / publish_action (push) Successful in 28s
2026-09-10 18:21:07 +02:00
dutchie031 12d3ad3341 Added test for publish bundle pipeline
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 5s
2026-09-10 18:20:23 +02:00
dutchie031 0443871583 Added test for publish bundle pipeline
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Successful in 8s
Publish Action Release / Derive release metadata (push) Successful in 5s
Publish Install Lua Addon Action / test_action (push) Failing after 18s
Publish Action Release / Publish tags (push) Successful in 21s
Publish Install Lua Addon Action / publish_action (push) Successful in 57s
2026-09-10 18:17:39 +02:00
dutchie031 1db8f3ccbb wip
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Failing after 7s
2026-09-10 17:09:59 +02:00
dutchie031 83df0813c6 removed obsolete weorkflow
publish-vs-code-extensions.yml / Publish VS Code Extension (push) Failing after 8s
2026-09-10 14:25:46 +02:00
25 changed files with 1988 additions and 955 deletions
-200
View File
@@ -1,200 +0,0 @@
name: Publish GitHub Action
on:
push:
branches:
- main
paths:
- github-action/package.json
permissions:
contents: write
jobs:
verify_action:
name: Verify action
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: github-action/package-lock.json
- name: Install action dependencies
working-directory: github-action
run: npm ci
- name: Create verification fixture
shell: bash
run: |
mkdir -p test-action-input
cat <<'EOF' > test-action-input/main.lua
local message = {}
message.hello = function()
return "hello"
end
return message
EOF
- name: Run action locally
uses: ./github-action
with:
source-root: test-action-input
output-file: test-action-output/compiled.lua
- name: Assert compiled output exists
shell: bash
run: test -f test-action-output/compiled.lua
derive_release:
name: Derive release metadata
runs-on: ubuntu-latest
needs: verify_action
outputs:
version: ${{ steps.derive.outputs.version }}
release_tag: ${{ steps.derive.outputs.release_tag }}
rolling_minor_tag: ${{ steps.derive.outputs.rolling_minor_tag }}
rolling_major_tag: ${{ steps.derive.outputs.rolling_major_tag }}
bump_kind: ${{ steps.derive.outputs.bump_kind }}
should_publish: ${{ steps.derive.outputs.should_publish }}
latest_release_tag: ${{ steps.derive.outputs.latest_release_tag }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Derive version and tags
id: derive
shell: bash
run: |
set -euo pipefail
version=$(node -p "require('./github-action/package.json').version")
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "github-action/package.json version must be semver X.Y.Z, got: $version" >&2
exit 1
fi
IFS='.' read -r major minor patch <<< "$version"
release_tag="action/v${version}"
rolling_minor_tag="action/v${major}.${minor}"
rolling_major_tag="action/v${major}"
latest_release_tag=$(git tag --list 'action/v*.*.*' --sort=-version:refname | head -n 1)
bump_kind="initial"
should_publish="true"
if [[ -n "$latest_release_tag" ]]; then
latest_version=${latest_release_tag#action/v}
if [[ "$version" == "$latest_version" ]]; then
should_publish="false"
bump_kind="duplicate"
else
IFS='.' read -r latest_major latest_minor latest_patch <<< "$latest_version"
if (( major < latest_major )) || \
(( major == latest_major && minor < latest_minor )) || \
(( major == latest_major && minor == latest_minor && patch < latest_patch )); then
echo "github-action/package.json version $version must be greater than latest published $latest_version" >&2
exit 1
fi
if (( major > latest_major )); then
bump_kind="major"
elif (( minor > latest_minor )); then
bump_kind="minor"
elif (( patch > latest_patch )); then
bump_kind="patch"
else
echo "Unable to derive release kind from $latest_version -> $version" >&2
exit 1
fi
fi
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "release_tag=$release_tag" >> "$GITHUB_OUTPUT"
echo "rolling_minor_tag=$rolling_minor_tag" >> "$GITHUB_OUTPUT"
echo "rolling_major_tag=$rolling_major_tag" >> "$GITHUB_OUTPUT"
echo "bump_kind=$bump_kind" >> "$GITHUB_OUTPUT"
echo "should_publish=$should_publish" >> "$GITHUB_OUTPUT"
echo "latest_release_tag=$latest_release_tag" >> "$GITHUB_OUTPUT"
- name: Summarize release plan
shell: bash
run: |
{
echo "## Action release plan"
echo ""
echo "- Version: ${{ steps.derive.outputs.version }}"
echo "- Release tag: ${{ steps.derive.outputs.release_tag }}"
echo "- Rolling minor tag: ${{ steps.derive.outputs.rolling_minor_tag }}"
echo "- Rolling major tag: ${{ steps.derive.outputs.rolling_major_tag }}"
echo "- Bump kind: ${{ steps.derive.outputs.bump_kind }}"
echo "- Latest published tag: ${{ steps.derive.outputs.latest_release_tag || 'none' }}"
echo "- Will publish: ${{ steps.derive.outputs.should_publish }}"
} >> "$GITHUB_STEP_SUMMARY"
publish_tags:
name: Publish tags
runs-on: ubuntu-latest
needs: derive_release
if: ${{ needs.derive_release.outputs.should_publish == 'true' }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Create immutable release tag
shell: bash
run: |
set -euo pipefail
release_tag='${{ needs.derive_release.outputs.release_tag }}'
if git rev-parse "$release_tag" >/dev/null 2>&1; then
echo "Release tag $release_tag already exists" >&2
exit 1
fi
git tag "$release_tag" "$GITHUB_SHA"
- name: Update rolling tags
shell: bash
run: |
set -euo pipefail
git tag -f '${{ needs.derive_release.outputs.rolling_minor_tag }}' "$GITHUB_SHA"
git tag -f '${{ needs.derive_release.outputs.rolling_major_tag }}' "$GITHUB_SHA"
- name: Push release tags
shell: bash
run: |
set -euo pipefail
git push origin '${{ needs.derive_release.outputs.release_tag }}'
git push origin '${{ needs.derive_release.outputs.rolling_minor_tag }}' --force
git push origin '${{ needs.derive_release.outputs.rolling_major_tag }}' --force
- name: Summarize published tags
shell: bash
run: |
{
echo "## Published action tags"
echo ""
echo "- Immutable: ${{ needs.derive_release.outputs.release_tag }}"
echo "- Rolling minor: ${{ needs.derive_release.outputs.rolling_minor_tag }}"
echo "- Rolling major: ${{ needs.derive_release.outputs.rolling_major_tag }}"
echo "- Bump kind: ${{ needs.derive_release.outputs.bump_kind }}"
} >> "$GITHUB_STEP_SUMMARY"
@@ -11,7 +11,50 @@ permissions:
contents: write contents: write
jobs: jobs:
## Verify that when the action has been run it actually has the lua addons installed
test_action:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: github-actions/install-lua-addon/package-lock.json
- name: Run Action Locally
uses: ./github-actions/install-lua-addon
with:
destination-path: './some/test/lua-addons'
- name: Verify lua addons were installed
run: |
echo "Listing contents of the Lua addons directory"
ls -la ./some/test/lua-addons
echo "Checking if dcs-types addon was installed"
if [ -d "./some/test/lua-addons/dcs-types" ]; then
echo "✓ dcs-types directory found"
else
echo "✗ dcs-types directory not found"
exit 1
fi
echo "Checking if config.json exists in dcs-types"
if [ -f "./some/test/lua-addons/dcs-types/config.json" ]; then
echo "✓ config.json found"
else
echo "✗ config.json not found"
exit 1
fi
echo "All checks passed!"
publish_action: publish_action:
needs: test_action
uses: ./.github/workflows/_publish-action-release.yml uses: ./.github/workflows/_publish-action-release.yml
with: with:
action-directory: github-actions/install-lua-addon action-directory: github-actions/install-lua-addon
@@ -34,20 +34,23 @@ jobs:
- name: Exit if tag exists - name: Exit if tag exists
if: steps.tag_check.outputs.tag_exists == 'true' if: steps.tag_check.outputs.tag_exists == 'true'
run: | run: |
echo "Tag already exists, exiting." echo "::warning::Tag already exists, exiting."
exit 1 exit 0
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@v4 uses: actions/setup-node@v4
if: steps.tag_check.outputs.tag_exists == 'false'
with: with:
node-version: '20' node-version: '20'
- name: Install dependencies - name: Install dependencies
if: steps.tag_check.outputs.tag_exists == 'false'
run: | run: |
cd dutchies-dcs-scripting-tools cd dutchies-dcs-scripting-tools
npm install npm install
- name: Build extension - name: Build extension
if: steps.tag_check.outputs.tag_exists == 'false'
run: | run: |
cd dutchies-dcs-scripting-tools cd dutchies-dcs-scripting-tools
npm run compile npm run compile
+1 -1
View File
@@ -16,7 +16,7 @@
"${workspaceFolder}/dutchies-dcs-scripting-tools/dist/**/*.js", "${workspaceFolder}/dutchies-dcs-scripting-tools/dist/**/*.js",
"${workspaceFolder}/compiler/dist/**/*.js" "${workspaceFolder}/compiler/dist/**/*.js"
], ],
"preLaunchTask": "watch" "timeout": 5000
} }
] ]
} }
+2 -1
View File
@@ -13,5 +13,6 @@
"cSpell.words": [ "cSpell.words": [
"dutchie", "dutchie",
"dutchies" "dutchies"
] ],
"Lua.workspace.library": [],
} }
+2 -2
View File
@@ -35,7 +35,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: dutchie031/DcsMissionScriptingTools/github-action@action/v1 - uses: https://git.dutchie031.com/dutchie031/DcsMissionScriptingTools/github-actions/bundle-script@bundle-script/v1
with: with:
source-root: 'src' source-root: 'src'
output-file: 'output/compiled.lua' output-file: 'output/compiled.lua'
@@ -59,7 +59,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: dutchie031/DcsMissionScriptingTools/github-actions/install-lua-addon@action/v1 - uses: https://git.dutchie031.com/dutchie031/DcsMissionScriptingTools/github-actions/install-lua-addon@install-lua-addon/v1
with: with:
destination-path: 'lua-addons' destination-path: 'lua-addons'
``` ```
+48 -22
View File
@@ -1,6 +1,6 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import { CompilationError } from './CompilationError'; import { CompilationError, CompilationErrorType } from './CompilationError';
/* /*
Block types. Block types.
@@ -10,7 +10,7 @@ import { CompilationError } from './CompilationError';
export enum BlockType { export enum BlockType {
CodeTextBlock, CodeTextBlock,
Function, Function,
If, If,
While, While,
For, For,
Do, Do,
@@ -68,10 +68,21 @@ export abstract class CodeBlock {
const fileContent = fs.readFileSync(luaFilePath, 'utf-8'); const fileContent = fs.readFileSync(luaFilePath, 'utf-8');
let leftCursor = 0; let leftCursor = 0;
let lineCursor = 0;
let lineCounter = 0; let lineCounter = 0;
const file: LuaFile = new LuaFile(); const file: LuaFile = new LuaFile();
let currentBlock: CodeBlock = file; let currentBlock: CodeBlock = file;
function advanceCursor(number: number = 1) {
leftCursor += number;
lineCursor += number;
}
function newLine() {
lineCounter++;
lineCursor = 0;
}
let currentWord = ''; let currentWord = '';
let currentBlockString = ''; let currentBlockString = '';
@@ -85,10 +96,6 @@ export abstract class CodeBlock {
currentBlockString += currentChar; currentBlockString += currentChar;
const nextChar = leftCursor < fileContent.length - 1 ? fileContent[leftCursor + 1] : ''; const nextChar = leftCursor < fileContent.length - 1 ? fileContent[leftCursor + 1] : '';
if (currentChar === '\n') {
lineCounter++;
}
if (currentChar === '-' && nextChar === '-') { if (currentChar === '-' && nextChar === '-') {
currentBlockString = currentBlockString.slice(0, -1); // Remove the '-' from the block string currentBlockString = currentBlockString.slice(0, -1); // Remove the '-' from the block string
const nextNextChar = leftCursor < fileContent.length - 2 ? fileContent[leftCursor + 2] : ''; const nextNextChar = leftCursor < fileContent.length - 2 ? fileContent[leftCursor + 2] : '';
@@ -97,19 +104,20 @@ export abstract class CodeBlock {
leftCursor += 3; // Skip the --[ leftCursor += 3; // Skip the --[
while (leftCursor < fileContent.length && !(fileContent[leftCursor] === ']' && fileContent[leftCursor + 1] === ']')) { while (leftCursor < fileContent.length && !(fileContent[leftCursor] === ']' && fileContent[leftCursor + 1] === ']')) {
if (fileContent[leftCursor] === '\n') { if (fileContent[leftCursor] === '\n') {
lineCounter++; newLine();
} }
leftCursor++; advanceCursor()
} }
leftCursor += 2; // Skip the closing ]] advanceCursor(2); // Skip the closing ]]
} else { } else {
// Comment line, skip to end of line // Comment line, skip to end of line
while (leftCursor < fileContent.length && fileContent[leftCursor] !== '\n') { while (leftCursor < fileContent.length && fileContent[leftCursor] !== '\n') {
leftCursor++; advanceCursor();
} }
if (fileContent[leftCursor] === '\n') { if (fileContent[leftCursor] === '\n') {
lineCounter++; newLine();
} }
advanceCursor();
} }
currentWord = ''; currentWord = '';
continue; continue;
@@ -117,14 +125,14 @@ export abstract class CodeBlock {
else if (currentChar === '"' || currentChar === "'") { else if (currentChar === '"' || currentChar === "'") {
// String literal, skip to closing quote // String literal, skip to closing quote
const quoteType = currentChar; const quoteType = currentChar;
leftCursor++; advanceCursor();
while (leftCursor < fileContent.length && fileContent[leftCursor] !== quoteType) { while (leftCursor < fileContent.length && fileContent[leftCursor] !== quoteType) {
// Add string but don't process it for keywords // Add string but don't process it for keywords
currentBlockString += fileContent[leftCursor]; currentBlockString += fileContent[leftCursor];
leftCursor++; advanceCursor();
} }
currentBlockString += quoteType; // Add the closing quote currentBlockString += quoteType; // Add the closing quote
leftCursor++; // Skip the closing quote advanceCursor(); // Skip the closing quote
currentWord = ''; currentWord = '';
continue; continue;
} }
@@ -144,6 +152,9 @@ export abstract class CodeBlock {
currentBlockString = ''; currentBlockString = '';
currentWord = ''; currentWord = '';
} }
newLine();
advanceCursor();
continue;
} }
else if (currentChar === ")" && currentBlock.blockType === BlockType.Require) { else if (currentChar === ")" && currentBlock.blockType === BlockType.Require) {
currentBlockString = trimEndPreserveNewlines(currentBlockString); // Remove trailing spaces/tabs currentBlockString = trimEndPreserveNewlines(currentBlockString); // Remove trailing spaces/tabs
@@ -152,6 +163,9 @@ export abstract class CodeBlock {
currentBlock.childBlocks.push(lineBlock); currentBlock.childBlocks.push(lineBlock);
currentBlockString = ''; currentBlockString = '';
// Update charEnd to include the closing parenthesis
(currentBlock as RequireBlock).charEnd = lineCursor + 1;
currentBlock = currentBlock.getParentBlock()!; currentBlock = currentBlock.getParentBlock()!;
} }
//Table blocks //Table blocks
@@ -178,7 +192,7 @@ export abstract class CodeBlock {
currentBlock = tableBlock; currentBlock = tableBlock;
let braceCounter = 1; let braceCounter = 1;
leftCursor++; advanceCursor();
while (leftCursor < fileContent.length && braceCounter > 0) { while (leftCursor < fileContent.length && braceCounter > 0) {
const char = fileContent[leftCursor]; const char = fileContent[leftCursor];
currentBlockString += char; currentBlockString += char;
@@ -194,23 +208,34 @@ export abstract class CodeBlock {
currentBlock.childBlocks.push(lineBlock); currentBlock.childBlocks.push(lineBlock);
currentBlockString = ''; currentBlockString = '';
lineCounter++; lineCounter++;
lineCursor = 0;
} }
leftCursor++; advanceCursor();
} }
// Find newline or other character // Find newline or other character
let tempCursor = leftCursor; let tempCursor = leftCursor;
let tempLineCursor = lineCursor;
while (tempCursor < fileContent.length && fileContent[tempCursor] !== '\n' && fileContent[tempCursor].trim() === '') { while (tempCursor < fileContent.length && fileContent[tempCursor] !== '\n' && fileContent[tempCursor].trim() === '') {
currentBlockString += fileContent[tempCursor]; currentBlockString += fileContent[tempCursor];
tempCursor++; tempCursor++;
tempLineCursor++;
} }
if (tempCursor < fileContent.length && fileContent[tempCursor] === '\n') { if (tempCursor < fileContent.length && fileContent[tempCursor] === '\n') {
currentBlockString += '\n'; currentBlockString = trimEndPreserveNewlines(currentBlockString) + '\n';
lineCounter++; lineCounter++;
lineCursor = 0;
leftCursor = tempCursor + 1;
} else if (tempCursor < fileContent.length && fileContent[tempCursor] === '-' && tempCursor + 1 < fileContent.length && fileContent[tempCursor + 1] === '-') {
// Found a comment after whitespace, trim the whitespace and position at the comment
currentBlockString = trimEndPreserveNewlines(currentBlockString) + '\n';
leftCursor = tempCursor;
lineCursor = tempLineCursor;
} else if (tempCursor > leftCursor) { } else if (tempCursor > leftCursor) {
// We found whitespace but no newline, so position cursor at last whitespace // We found whitespace but no newline, so position cursor at last whitespace
leftCursor = tempCursor - 1; leftCursor = tempCursor;
lineCursor = tempLineCursor;
} }
// else: no whitespace after table, leave leftCursor where it is // else: no whitespace after table, leave leftCursor where it is
@@ -279,7 +304,7 @@ export abstract class CodeBlock {
currentBlock.childBlocks.push(line); currentBlock.childBlocks.push(line);
} }
blockToAdd = new RequireBlock(lineCounter, currentBlock, leftCursor - currentWord.length, leftCursor); blockToAdd = new RequireBlock(lineCounter, currentBlock, Math.max(0, lineCursor - trimmedWord.length), lineCursor);
currentBlockString = trimmedWord; // Start the require block content with 'require' keyword currentBlockString = trimmedWord; // Start the require block content with 'require' keyword
} }
else if (trimmedWord === 'end') { else if (trimmedWord === 'end') {
@@ -288,7 +313,8 @@ export abstract class CodeBlock {
onError?.({ onError?.({
filePath: luaFilePath, filePath: luaFilePath,
line: fileContent.substring(0, leftCursor).split('\n').length - 1, line: fileContent.substring(0, leftCursor).split('\n').length - 1,
message: "Unexpected 'end' without matching block start" message: "Unexpected 'end' without matching block start",
type: CompilationErrorType.Syntax
}); });
} else { } else {
currentBlock = parent; currentBlock = parent;
@@ -302,7 +328,7 @@ export abstract class CodeBlock {
currentWord = ''; currentWord = '';
} }
leftCursor++; advanceCursor();
} }
// Handle case where file ends while in a ReturnBlock // Handle case where file ends while in a ReturnBlock
if (currentBlock.blockType === BlockType.Return) { if (currentBlock.blockType === BlockType.Return) {
@@ -548,7 +574,7 @@ export class FunctionBlock extends CodeBlock {
export class RequireBlock extends CodeBlock { export class RequireBlock extends CodeBlock {
constructor(sourceLineNumber: number, parent: CodeBlock, public readonly charStart?: number, public readonly charEnd?: number) { constructor(sourceLineNumber: number, parent: CodeBlock, public readonly charStart?: number, public charEnd?: number) {
super(sourceLineNumber, BlockType.Require, parent); super(sourceLineNumber, BlockType.Require, parent);
} }
+10
View File
@@ -6,4 +6,14 @@ export interface CompilationError {
charStart?: number; charStart?: number;
charEnd?: number; charEnd?: number;
message: string; message: string;
type: CompilationErrorType;
metaData?: Map<string, any>;
}
export enum CompilationErrorType {
Syntax = "Syntax",
Semantic = "Semantic",
Runtime = "Runtime",
DependencyCircular = "DependencyCircular",
DependencyNotFound = "DependencyNotFound"
} }
+13 -5
View File
@@ -1,7 +1,7 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import { LuaFile, BlockType, CodeBlock, RequireBlock, ReturnBlock, FunctionBlock, TableBlock } from './CodeBlocks'; import { LuaFile, BlockType, CodeBlock, RequireBlock, ReturnBlock, FunctionBlock, TableBlock } from './CodeBlocks';
import { CompilationError } from './CompilationError'; import { CompilationError, CompilationErrorType } from './CompilationError';
export interface ScriptCompilerOptions { export interface ScriptCompilerOptions {
sourcePath: string, sourcePath: string,
@@ -17,7 +17,7 @@ export interface ICompilationLogger {
writeLine(message: string): void; writeLine(message: string): void;
} }
export { CompilationError }; export { CompilationError, CompilationErrorType };
class Metrics { class Metrics {
public totalLinesRead : number = 0; public totalLinesRead : number = 0;
@@ -70,7 +70,8 @@ export class ScriptCompiler {
this.options.onError?.({ this.options.onError?.({
filePath: fullPath, filePath: fullPath,
line: 0, line: 0,
message: `Duplicate file key detected: ${key}. This can happen if two files have different capitalization. Lua is case sensitive, but the compiler treats file keys as case insensitive.` message: `Duplicate file key detected: ${key}. This can happen if two files have different capitalization. Lua is case sensitive, but the compiler treats file keys as case insensitive.`,
type: CompilationErrorType.Semantic
}); });
continue; continue;
} }
@@ -305,7 +306,8 @@ class Writer {
this.onError({ this.onError({
filePath: file.fullPath, filePath: file.fullPath,
line: 0, line: 0,
message: `Circular dependency detected: ${cycle.map(x => x.split('.').pop()).join(' -> ')}` message: `Circular dependency detected: ${cycle.map(x => x.split('.').pop()).join(' -> ')}`,
type: CompilationErrorType.DependencyCircular
}); });
} }
return true; return true;
@@ -348,7 +350,13 @@ class Writer {
line: dep.requiredAtLine, line: dep.requiredAtLine,
charStart: dep.charStart, charStart: dep.charStart,
charEnd: dep.charEnd, charEnd: dep.charEnd,
message: `Missing dependency: ${dep.fileKey}` message: `Missing dependency: ${dep.fileKey}`,
type: CompilationErrorType.DependencyNotFound,
metaData: new Map(
[
["dependency", dep.fileKey],
]
)
}); });
} }
} }
+1 -1
View File
@@ -32,7 +32,7 @@ async function main() {
format: 'cjs', format: 'cjs',
minify: production, minify: production,
sourcemap: !production, sourcemap: !production,
sourcesContent: false, sourcesContent: true,
platform: 'node', platform: 'node',
outfile: 'dist/extension.js', outfile: 'dist/extension.js',
external: ['vscode'], external: ['vscode'],
@@ -42,10 +42,107 @@
---@field Easting number ---@field Easting number
---@field Northing number ---@field Northing number
do --mission table
---@class MissionTable
---@field drawings Drawings
---@field coalition Coalitions
---@field triggers Triggers
---@field theatre string?
---@field version number
---@field start_time number
---@field goals table?
---@field weather table?
do -- drawings
---@class Drawings
---@field options DrawingOptions
---@field layers Array<DrawingLayer>
---@class DrawingOptions
---@field hiddenOnF10Map HiddenOnF10Map
---@class HiddenOnF10Map
---@field Observer HiddenOnF10MapSettings
---@field Instructor HiddenOnF10MapSettings
---@field ForwardObserver HiddenOnF10MapSettings
---@field Spectator HiddenOnF10MapSettings
---@field ArtilleryCommander HiddenOnF10MapSettings
---@field Pilot HiddenOnF10MapSettings
---@class HiddenOnF10MapSettings
---@field Neutral boolean
---@field Blue boolean
---@field Red boolean
---@class DrawingLayer
---@field name string
---@field visible boolean
---@field objects Array<DrawingObject>
end
do -- coalitions
---@class Coalitions
---@field red Coalition
---@field blue Coalition
---@field neutral Coalition
---@class Coalition
---@field bullseye Vec2
---@field name string
---@field nav_points Array<NavPoint>
---@field country Array<Country>
---@class NavPoint
---@field type string
---@field comment string
---@field callSignStr string
---@field id number
---@field properties table
---@class Country
---@field id number
---@field name string
---@field vehicle Groups
---@field plane Groups
---@field helicopter Groups
---@field static Groups
---@field ship Groups
---@class Groups
---@field group Array<table>
end
do -- triggers
---@class Triggers
---@field zones Array<MissionTriggerZone>
---@class MissionTriggerZone
---@field radius number
---@field zoneId number
---@field properties Array<TriggerZoneProperty>
---@field hidden boolean
---@field x number
---@field y number
---@field name string
---@field type number
---@field heading number
---@field verticies Array<Vec2>
---@class TriggerZoneProperty
---@field key string
---@field value string
end
end
do -- env do -- env
---@class env ---@class env
---@field mission table TODO: Mission ---@field mission MissionTable
---@field warehouses table ---@field warehouses table
---@field info fun(log:string, showMessageBox:boolean?) Prints passed log line with prefix 'info' ---@field info fun(log:string, showMessageBox:boolean?) Prints passed log line with prefix 'info'
---@field warning fun(log:string, showMessageBox:boolean?) Prints passed log line with prefix 'warning' ---@field warning fun(log:string, showMessageBox:boolean?) Prints passed log line with prefix 'warning'
@@ -0,0 +1,68 @@
---@meta LfsTypes
---@alias lfs.AttributeName
---|'dev' -- on Unix systems, this represents the device that the inode resides on. On Windows systems, represents the drive number of the disk containing the file
---|'ino' -- on Unix systems, this represents the inode number. On Windows systems this has no meaning
---|'mode' -- string representing the associated protection mode (the values could be file, directory, link, socket, named pipe, char device, block device or other)
---|'nlink' -- number of hard links to the file
---|'uid' -- user-id of owner (Unix only, always 0 on Windows)
---|'gid' -- group-id of owner (Unix only, always 0 on Windows)
---|'rdev' -- on Unix systems, represents the device type, for special file inodes. On Windows systems represents the same as dev
---|'access' -- time of last access
---|'modification' -- time of last data modification
---|'change' -- time of last file status change
---|'size' -- file size, in bytes
---|'permissions' -- file permissions string
---|'blocks' -- block allocated for file; (Unix only)
---|'blksize' -- optimal file system I/O blocksize; (Unix only)
---@alias lfs.AttributeMode
---|'file'
---|'directory'
---|'link'
---|'socket'
---|'char device'
---|"block device"
---|"named pipe"
---@class lfs.Attributes
---@field [lfs.AttributeName] any
---@field ['mode'] lfs.AttributeMode
---@alias lfs.FileMode
---| "binary"
---| "text"
---@class lfs.Lock
---@field free fun() Releases the lock on the file/directory.
---@class lfs.DirObject
---@field next fun(self: lfs.DirObject): string? Returns a directory entry's name as a string, or `nil` if there are no more entries.
---@field close fun(self: lfs.DirObject) Explicitly closes the directory before iteration finishes.
---@class lfs
---@field attributes fun(path:string, result_param: lfs.AttributeName | lfs.Attributes | table): lfs.Attributes? Returns a table with the file attributes corresponding to filepath (or `nil` followed by an error message and a system-dependent error code in case of error). If the second optional argument is given and is a string, then only the value of the named attribute is returned (this use is equivalent to lfs.attributes(filepath)[request_name], but the table is not created and only one attribute is retrieved from the O.S.). if a table is passed as the second argument, it (result_table) is filled with attributes and returned instead of a new table
---@field chdir fun(path:string) : boolean?, string? Changes the current working directory to the given path. <br> Returns true in case of success or `nil` plus an error string.
---@field lock_dir fun(path:string, seconds_stale: number?) : lfs.Lock?, string? Creates a lockfile (called lockfile.lfs) in path if it does not exist and returns the lock. If the lock already exists checks if it's stale, using the second parameter (default for the second parameter is `INT_MAX`, which in practice means the lock will never be stale. To free the the lock call `lock:free()`. <br>In case of any errors it returns `nil` and the error message. In particular, if the lock exists and is not stale it returns the "File exists" message.
---@field currentdir fun(): string?, string? Returns a string with the current working directory or `nil` plus an error string.
---@field dir fun(path: string): fun(): string?, lfs.DirObject Lua iterator over the entries of a given directory. Each time the iterator is called with `dir_obj` it returns a directory entry's name as a string, or `nil` if there are no more entries. You can also iterate by calling `dir_obj:next()`, and explicitly close the directory before the iteration finished with `dir_obj:close()`. Raises an error if `path` is not a directory.
---@field lock fun(filehandle, mode: string, start?: number, length?: number): boolean?, string? Locks a file or a part of it. The mode can be `'r'` (read/shared lock) or `'w'` (write/exclusive lock). Returns `true` if successful, or `nil` plus an error string in case of error.
---@field link fun(old: string, new: string, symlink?: boolean): boolean?, string?, number? Creates a link. If the optional third argument is true, creates a symbolic link; otherwise creates a hard link.
---@field mkdir fun(dirname: string): boolean?, string?, number? Creates a new directory. Returns `true` in case of success or `nil`, an error message and a system-dependent error code in case of error.
---@field rmdir fun(dirname: string): boolean?, string?, number? Removes an existing directory. Returns `true` in case of success or `nil`, an error message and a system-dependent error code in case of error.
---@field setmode fun(file, mode: lfs.FileMode): boolean?, string? Sets the writing mode for a file. The mode can be `'binary'` or `'text'`. Returns `true` followed by the previous mode string, or `nil` followed by an error string in case of error. On non-Windows platforms, setting the mode has no effect and is always returned as `'binary'`.
---@field symlinkattributes fun(filepath: string, request_name?: lfs.AttributeName | string): lfs.Attributes? | any Gets information about a symlink itself (not the file it refers to). Identical to `lfs.attributes` but also adds a `target` field containing the filename the symlink points to. On Windows, this is identical to `lfs.attributes`.
---@field touch fun(filepath: string, atime?: number, mtime?: number): boolean?, string?, number? Sets access and modification times of a file. Times are in seconds (from `os.time()`). If `mtime` is omitted, `atime` is used; if both are omitted, the current time is used. Returns `true` in case of success or `nil`, an error message and a system-dependent error code in case of error.
---@field unlock fun(filehandle, start?: number, length?: number): boolean?, string? Unlocks a file or a part of it. Returns `true` if successful, or `nil` plus an error string in case of error.
---@class DcsLfs : lfs
---@field tempdir fun(): string Returns the DCS temporary directory.
---@field writedir fun(): string Returns the Saved Games directory.
---@field realpath fun(path: string): string Returns the absolute path of a file.
---@field normpath fun(path: string): string Returns the normalized path.
---@field md5sum fun(path: string): string Returns the MD5 checksum of the file at the given path.
---@field locations fun(): table Returns available drives.
-- In DCS lfs can be removed, hence the option of it being `nil`.
---@type DcsLfs|nil
lfs = lfs or nil
+11 -4
View File
@@ -2,7 +2,7 @@
"name": "dutchies-dcs-scripting-tools", "name": "dutchies-dcs-scripting-tools",
"displayName": "Dutchies Dcs Scripting Tools", "displayName": "Dutchies Dcs Scripting Tools",
"description": "Scripting tools to create DCS script and frameworks easier", "description": "Scripting tools to create DCS script and frameworks easier",
"version": "0.1.0", "version": "0.2.1",
"author": { "author": {
"name": "dutchie031", "name": "dutchie031",
"email": "54616262+dutchie031@users.noreply.github.com" "email": "54616262+dutchie031@users.noreply.github.com"
@@ -36,7 +36,7 @@
"properties": { "properties": {
"dutchies-dcs-scripting-tools.dcsTypes": { "dutchies-dcs-scripting-tools.dcsTypes": {
"type": "boolean", "type": "boolean",
"default": true, "default": false,
"description": "Enable or disable DCS Types (adds types for DCS functions and objects)" "description": "Enable or disable DCS Types (adds types for DCS functions and objects)"
}, },
"dutchies-dcs-scripting-tools.spearheadTypes": { "dutchies-dcs-scripting-tools.spearheadTypes": {
@@ -64,7 +64,15 @@
"type":"string", "type":"string",
"default": "${workspaceFolder}/dist", "default": "${workspaceFolder}/dist",
"description": "Where the compiled Lua files will be output. default: ${workspaceFolder}/dist" "description": "Where the compiled Lua files will be output. default: ${workspaceFolder}/dist"
} },
"dutchies-dcs-scripting-tools.globalRequirables": {
"type": "array",
"items": {
"type": "string"
},
"default": [],
"description": "List of global requirable Lua scripts that will be included automatically."
}
} }
}, },
"grammars": [ "grammars": [
@@ -114,7 +122,6 @@
"watch": "npm-run-all -p watch:*", "watch": "npm-run-all -p watch:*",
"watch:esbuild": "node esbuild.js --watch", "watch:esbuild": "node esbuild.js --watch",
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json", "watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
"watch:compiler": "cd ../compiler && npm run watch",
"package": "npm run check-types && npm run lint && node esbuild.js --production", "package": "npm run check-types && npm run lint && node esbuild.js --production",
"compile-tests": "tsc -p . --outDir out", "compile-tests": "tsc -p . --outDir out",
"watch-tests": "tsc -p . -w --outDir out", "watch-tests": "tsc -p . -w --outDir out",
+190 -115
View File
@@ -1,7 +1,8 @@
// The module 'vscode' contains the VS Code extensibility API // The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below // Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import { ScriptCompiler, ScriptCompilerOptions, CompilationError, ICompilationLogger } from 'dcs-script-compiler'; import * as path from 'path';
import { ScriptCompiler, ScriptCompilerOptions, CompilationError, ICompilationLogger, CompilationErrorType } from 'dcs-script-compiler';
import { Logger } from './logger'; import { Logger } from './logger';
import * as luaAddonsManager from './lua-addons-manager'; import * as luaAddonsManager from './lua-addons-manager';
@@ -9,17 +10,24 @@ const luaWorkSpaceSettingKey = "Lua.workspace";
const librarySettingsKey = "library"; const librarySettingsKey = "library";
const diagnosticCollection = vscode.languages.createDiagnosticCollection('lua-transpiler'); const diagnosticCollection = vscode.languages.createDiagnosticCollection('lua-transpiler');
// Diagnostic codes
const DIAGNOSTIC_CODE_MISSING_GLOBAL = 'lua-missing-global-dependency';
const logger = new Logger(); const logger = new Logger();
const luaAddonNames: string[] = [ "dcs-types" ];
const extensionName = 'dutchies-dcs-scripting-tools'; const extensionName = 'dutchies-dcs-scripting-tools';
const publisherName = 'dutchie031'; const publisherName = 'dutchie031';
const extensionSettingsFilter = `@ext:${publisherName}.${extensionName}`; const extensionSettingsFilter = `@ext:${publisherName}.${extensionName}`;
let luaAddonsManagerInstance: luaAddonsManager.LuaAddonsManager | undefined;
// State tracking for addon updates // State tracking for addon updates
let extensionPath: string | undefined; let extensionPath: string | undefined;
let workspaceRoot: string | undefined; let workspaceRoot: string | undefined;
let luaAddonsTargetPath: string | undefined;
let currentExtensionVersion: string | undefined; let currentExtensionVersion: string | undefined;
let installedAddonPaths: Map<string, string> = new Map();
let isUpdatingAddons = false; let isUpdatingAddons = false;
//TODO: //TODO:
@@ -32,9 +40,22 @@ export async function activate(context: vscode.ExtensionContext) {
extensionPath = context.extensionPath; extensionPath = context.extensionPath;
workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath; workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
if (workspaceRoot === undefined) {
vscode.window.showErrorMessage('Workspace root not found. Lua addons manager cannot be initialized.');
return;
}
luaAddonsTargetPath = path.join(workspaceRoot, '.vscode' , 'lua-addons');
luaAddonsManagerInstance = new luaAddonsManager.LuaAddonsManager(luaAddonsTargetPath, context.extensionPath);
if (!luaAddonsManagerInstance) {
vscode.window.showErrorMessage('Failed to initialize Lua addons manager.');
return;
}
// Initialize extension version // Initialize extension version
try { try {
currentExtensionVersion = await luaAddonsManager.getExtensionVersion(extensionPath); currentExtensionVersion = await luaAddonsManagerInstance.getPackageVersion();
logger.debug(`Extension version: ${currentExtensionVersion}`); logger.debug(`Extension version: ${currentExtensionVersion}`);
} catch (err) { } catch (err) {
logger.error(`Failed to determine extension version: ${err instanceof Error ? err.message : String(err)}`); logger.error(`Failed to determine extension version: ${err instanceof Error ? err.message : String(err)}`);
@@ -70,6 +91,23 @@ export async function activate(context: vscode.ExtensionContext) {
}) })
); );
// Register code actions provider for quick fixes
context.subscriptions.push(
vscode.languages.registerCodeActionsProvider('lua', new LuaQuickFixProvider(), {
providedCodeActionKinds: [vscode.CodeActionKind.QuickFix]
})
);
// Register command to add global requirable
context.subscriptions.push(
vscode.commands.registerCommand(
'dutchies-dcs-scripting-tools.addGlobalRequirable',
async (dependency: string) => {
await addGlobalRequirable(dependency);
}
)
);
vscode.workspace.onDidSaveTextDocument(async(document) => { vscode.workspace.onDidSaveTextDocument(async(document) => {
logger.info(`Document saved: ${document.uri.fsPath} | Language: ${document.languageId}`); logger.info(`Document saved: ${document.uri.fsPath} | Language: ${document.languageId}`);
if (document.languageId === 'lua') { if (document.languageId === 'lua') {
@@ -164,16 +202,40 @@ async function compileLuaScripts() {
logger.error('Compilation failed: ' + (err as Error).message + '\n' + (err as Error).stack); logger.error('Compilation failed: ' + (err as Error).message + '\n' + (err as Error).stack);
} }
const globalRequirables: string[] = config.get<string[]>('globalRequirables') || [];
// Update diagnostics // Update diagnostics
diagnosticCollection.clear(); diagnosticCollection.clear();
for (const [filePath, errors] of errorsByFile) { for (const [filePath, errors] of errorsByFile) {
const uri = vscode.Uri.file(filePath); const uri = vscode.Uri.file(filePath);
const diagnostics = errors.map(error => { const diagnostics = errors.map(error => {
const range = new vscode.Range(error.line, error.charStart ?? 0, error.line, error.charEnd ?? 0); if (error.type === CompilationErrorType.DependencyNotFound) {
const diagnostic = new vscode.Diagnostic(range, error.message, vscode.DiagnosticSeverity.Error); const dependencyStr = error.metaData?.get("dependency") ?? undefined;
diagnostic.source = 'DCS Lua Transpiler'; if (dependencyStr) {
return diagnostic; if (globalRequirables.includes(dependencyStr)) {
}); // Do nothing, it is a globally requirable dependency
const range = new vscode.Range(error.line, error.charStart ?? 0, error.line, error.charEnd ?? 0);
const diagnostic = new vscode.Diagnostic(range, "Unchecked: Globally marked dependency", vscode.DiagnosticSeverity.Hint);
diagnostic.source = 'DCS Lua Transpiler';
return diagnostic;
} else {
const range = new vscode.Range(error.line, error.charStart ?? 0, error.line, error.charEnd ?? 0);
const diagnostic = new vscode.Diagnostic(range, error.message, vscode.DiagnosticSeverity.Error);
diagnostic.code = { value: DIAGNOSTIC_CODE_MISSING_GLOBAL, target: vscode.Uri.parse('https://example.com') };
diagnostic.source = 'DCS Lua Transpiler';
// Store the dependency name for the quick fix to access
(diagnostic as any).dependency = dependencyStr;
return diagnostic;
}
}
return undefined; //Something weird happened, let's ignore it for now.
} else {
const range = new vscode.Range(error.line, error.charStart ?? 0, error.line, error.charEnd ?? 0);
const diagnostic = new vscode.Diagnostic(range, error.message, vscode.DiagnosticSeverity.Error);
diagnostic.source = 'DCS Lua Transpiler';
return diagnostic;
}
}).filter(diagnostic => diagnostic !== undefined);
diagnosticCollection.set(uri, diagnostics); diagnosticCollection.set(uri, diagnostics);
} }
} }
@@ -186,6 +248,7 @@ async function enableIntellisense() {
} }
await updateLuaAddons(); await updateLuaAddons();
await addPluginPathsToSettings();
await vscode.commands.executeCommand( await vscode.commands.executeCommand(
"lua.startServer" "lua.startServer"
); );
@@ -199,18 +262,8 @@ async function disableIntellisense() {
} }
await removeVersionedPluginPathsFromSettings(); await removeVersionedPluginPathsFromSettings();
if(luaAddonsManagerInstance){
// Clean up all addon versions from workspace await luaAddonsManagerInstance.removeAllExtensions(luaAddonNames);
if (workspaceRoot) {
try {
const discoveredAddons = await luaAddonsManager.discoverLuaAddons(extensionPath || '');
for (const addonName of discoveredAddons.keys()) {
await luaAddonsManager.deleteAllVersionsOfAddon(workspaceRoot, addonName);
logger.debug(`Deleted all versions of ${addonName} from workspace.`);
}
} catch (err) {
logger.error(`Failed to clean up addons: ${err instanceof Error ? err.message : String(err)}`);
}
} }
await vscode.commands.executeCommand( await vscode.commands.executeCommand(
@@ -237,41 +290,28 @@ async function updateLuaAddons(): Promise<void> {
isUpdatingAddons = true; isUpdatingAddons = true;
if (luaAddonsManagerInstance === undefined) {
logger.warn('Lua Addons Manager instance is not available.');
isUpdatingAddons = false;
return;
}
try { try {
logger.info('Starting lua-addons update...'); logger.info('Starting lua-addons update...');
// Discover bundled addons for (const addonName of luaAddonNames) {
const discoveredAddons = await luaAddonsManager.discoverLuaAddons(extensionPath); const packageVersion = await luaAddonsManagerInstance.getPackageVersion();
const addonVersion = await luaAddonsManagerInstance.getExtensionVersion(addonName);
if (discoveredAddons.size === 0) {
logger.info('No lua-addons found in extension bundle.'); if (packageVersion && packageVersion !== addonVersion) {
isUpdatingAddons = false; logger.warn(
return; `Version mismatch for addon ${addonName}: package=${packageVersion}, installed=${addonVersion}`
);
luaAddonsManagerInstance.removeExtension(addonName);
luaAddonsManagerInstance.installExtension(addonName);
}
} }
logger.debug(`Discovered ${discoveredAddons.size} lua-addon(s): ${Array.from(discoveredAddons.keys()).join(', ')}`);
// Copy addons with versioned names
const copiedAddons = await luaAddonsManager.copyLuaAddons(
extensionPath,
workspaceRoot,
currentExtensionVersion,
discoveredAddons
);
// Store paths for settings management
installedAddonPaths = copiedAddons;
logger.debug(`Copied ${copiedAddons.size} addon(s) to workspace.`);
// Clean up old versions
for (const addonName of discoveredAddons.keys()) {
await luaAddonsManager.deleteOldVersions(workspaceRoot, addonName, currentExtensionVersion);
logger.debug(`Cleaned old versions of ${addonName}.`);
}
// Update Lua settings with new paths
await addVersionedPluginPathsToSettings(copiedAddons);
logger.info(`Lua-addons update completed successfully (version ${currentExtensionVersion}).`); logger.info(`Lua-addons update completed successfully (version ${currentExtensionVersion}).`);
} catch (err) { } catch (err) {
@@ -304,27 +344,22 @@ async function checkAndUpdateAddonsOnStartup(): Promise<void> {
logger.debug('Checking lua-addons versions on startup...'); logger.debug('Checking lua-addons versions on startup...');
// Get installed addons if (!luaAddonsManagerInstance) {
const installedAddons = await luaAddonsManager.getInstalledAddons(workspaceRoot); logger.debug('Lua Addons Manager instance is not available, skipping addon version check.');
const discoveredAddons = await luaAddonsManager.discoverLuaAddons(extensionPath); return;
}
// Check each discovered addon
let updateNeeded = false; let updateNeeded = false;
for (const addonName of discoveredAddons.keys()) { for (const addonName of luaAddonNames) {
const installed = installedAddons.get(addonName); const packageVersion = await luaAddonsManagerInstance.getPackageVersion();
const installedVersion = installed?.version; const addonVersion = await luaAddonsManagerInstance.getExtensionVersion(addonName);
if (packageVersion && packageVersion !== addonVersion) {
if (luaAddonsManager.requiresUpdate(installedVersion, currentExtensionVersion)) {
logger.info(
`Version mismatch for ${addonName}: installed=${installedVersion || 'none'}, current=${currentExtensionVersion}`
);
updateNeeded = true; updateNeeded = true;
break; break;
} }
} }
if (updateNeeded) { if (updateNeeded) {
logger.info('Lua-addons update needed, prompting user...');
const userChoice = await vscode.window.showInformationMessage( const userChoice = await vscode.window.showInformationMessage(
'DCS-Types are not up to date with the current extension version. Do you want to update them?', 'DCS-Types are not up to date with the current extension version. Do you want to update them?',
{ modal: false }, { modal: false },
@@ -337,17 +372,7 @@ async function checkAndUpdateAddonsOnStartup(): Promise<void> {
} else { } else {
logger.info('User declined DCS-Types update.'); logger.info('User declined DCS-Types update.');
} }
} else {
logger.debug('Lua-addons versions are current, no update needed.');
// Ensure paths are in settings even if no update needed
const pathsMap = new Map<string, string>();
for (const [name, info] of installedAddons.entries()) {
pathsMap.set(name, info.path);
}
installedAddonPaths = pathsMap;
await addVersionedPluginPathsToSettings(installedAddonPaths);
} }
} catch (err) { } catch (err) {
logger.error( logger.error(
`Error checking lua-addons on startup: ${err instanceof Error ? err.message : String(err)}` `Error checking lua-addons on startup: ${err instanceof Error ? err.message : String(err)}`
@@ -377,14 +402,12 @@ function convertToWorkspaceFolderPath(absolutePath: string): string {
} }
/** /**
* Adds versioned addon paths to the Lua workspace library settings * Adds the lua-addons directory to the Lua workspace library settings.
* @param addonPaths - Map of addon name to installed path * Lua Language Server automatically discovers versioned addons within this directory.
*/ */
async function addVersionedPluginPathsToSettings(addonPaths?: Map<string, string>): Promise<void> { async function addPluginPathsToSettings(): Promise<void> {
const pathsToAdd = addonPaths || installedAddonPaths; if (!luaAddonsTargetPath) {
logger.warn('Lua addons target path not available.');
if (pathsToAdd.size === 0) {
logger.debug('No addon paths to add to settings.');
return; return;
} }
@@ -392,58 +415,110 @@ async function addVersionedPluginPathsToSettings(addonPaths?: Map<string, string
const luaSettings = vscode.workspace.getConfiguration(luaWorkSpaceSettingKey); const luaSettings = vscode.workspace.getConfiguration(luaWorkSpaceSettingKey);
let librarySettings = luaSettings.get<string[]>(librarySettingsKey) || []; let librarySettings = luaSettings.get<string[]>(librarySettingsKey) || [];
// Add each addon path if not already present const workspaceFolderPath = convertToWorkspaceFolderPath(luaAddonsTargetPath);
for (const addonPath of pathsToAdd.values()) {
const workspaceFolderPath = convertToWorkspaceFolderPath(addonPath); if (!librarySettings.includes(workspaceFolderPath)) {
if (!librarySettings.includes(workspaceFolderPath)) { librarySettings.push(workspaceFolderPath);
librarySettings.push(workspaceFolderPath); logger.debug(`Added lua-addons path to Lua settings: ${workspaceFolderPath}`);
logger.debug(`Added addon path to settings: ${workspaceFolderPath}`); await luaSettings.update(librarySettingsKey, librarySettings, vscode.ConfigurationTarget.Workspace);
} } else {
logger.debug('Lua-addons path already in settings.');
} }
await luaSettings.update(librarySettingsKey, librarySettings, vscode.ConfigurationTarget.Workspace);
} catch (err) { } catch (err) {
logger.error(`Failed to add addon paths to settings: ${err instanceof Error ? err.message : String(err)}`); logger.error(`Failed to add lua-addons path to settings: ${err instanceof Error ? err.message : String(err)}`);
throw err; throw err;
} }
} }
/** /**
* Removes all addon paths from the Lua workspace library settings * Removes the lua-addons directory from the Lua workspace library settings
*/ */
async function removeVersionedPluginPathsFromSettings(): Promise<void> { async function removeVersionedPluginPathsFromSettings(): Promise<void> {
if (!luaAddonsTargetPath) {
logger.debug('Lua addons target path not available, skipping removal.');
return;
}
try { try {
const luaSettings = vscode.workspace.getConfiguration(luaWorkSpaceSettingKey); const luaSettings = vscode.workspace.getConfiguration(luaWorkSpaceSettingKey);
let librarySettings = luaSettings.get<string[]>(librarySettingsKey) || []; let librarySettings = luaSettings.get<string[]>(librarySettingsKey) || [];
const workspaceFolderPath = convertToWorkspaceFolderPath(luaAddonsTargetPath);
const filteredSettings = librarySettings.filter(path => path !== workspaceFolderPath);
if (filteredSettings.length !== librarySettings.length) {
await luaSettings.update(librarySettingsKey, filteredSettings, vscode.ConfigurationTarget.Workspace);
logger.debug(`Removed lua-addons path from Lua settings: ${workspaceFolderPath}`);
} else {
logger.debug('Lua-addons path not found in settings.');
}
} catch (err) {
logger.error(`Failed to remove lua-addons path from settings: ${err instanceof Error ? err.message : String(err)}`);
throw err;
}
}
if (workspaceRoot) { /**
// Get all installed addons to know what paths to remove * Code actions provider for Lua quick fixes
const installedAddons = await luaAddonsManager.getInstalledAddons(workspaceRoot); */
class LuaQuickFixProvider implements vscode.CodeActionProvider {
provideCodeActions(
document: vscode.TextDocument,
range: vscode.Range | vscode.Selection,
context: vscode.CodeActionContext,
): vscode.CodeAction[] {
const codeActions: vscode.CodeAction[] = [];
// Check for missing global dependency diagnostics
for (const diagnostic of context.diagnostics) {
const codeValue = typeof diagnostic.code === 'object' && diagnostic.code !== null
? (diagnostic.code as any).value
: diagnostic.code;
for (const addonInfo of installedAddons.values()) { if (codeValue === DIAGNOSTIC_CODE_MISSING_GLOBAL) {
// Try both absolute and workspace-relative paths for compatibility const dependency = (diagnostic as any).dependency;
const absolutePath = addonInfo.path; if (dependency) {
const relativePath = convertToWorkspaceFolderPath(absolutePath); const action = new vscode.CodeAction(
`Mark '${dependency}' as globally available`,
// Remove absolute path if present vscode.CodeActionKind.QuickFix
let index = librarySettings.indexOf(absolutePath); );
if (index !== -1) { action.command = {
librarySettings.splice(index, 1); title: `Add '${dependency}' to global requireables`,
logger.debug(`Removed addon path from settings: ${absolutePath}`); command: 'dutchies-dcs-scripting-tools.addGlobalRequirable',
} arguments: [dependency]
};
// Remove relative path if present action.diagnostics = [diagnostic];
index = librarySettings.indexOf(relativePath); codeActions.push(action);
if (index !== -1) {
librarySettings.splice(index, 1);
logger.debug(`Removed addon path from settings: ${relativePath}`);
} }
} }
} }
await luaSettings.update(librarySettingsKey, librarySettings, vscode.ConfigurationTarget.Workspace); return codeActions;
}
}
/**
* Adds a dependency to the global requireables list in workspace settings
* @param dependency - The dependency name to add
*/
async function addGlobalRequirable(dependency: string): Promise<void> {
try {
const config = vscode.workspace.getConfiguration(extensionName);
const globalRequirables = config.get<string[]>('globalRequirables') || [];
if (!globalRequirables.includes(dependency)) {
globalRequirables.push(dependency);
await config.update('globalRequirables', globalRequirables, vscode.ConfigurationTarget.Workspace);
vscode.window.showInformationMessage(`Added '${dependency}' to global requireables.`);
// Recompile to update diagnostics
await compileLuaScripts();
} else {
vscode.window.showInformationMessage(`'${dependency}' is already in global requireables.`);
}
} catch (err) { } catch (err) {
logger.error(`Failed to remove addon paths from settings: ${err instanceof Error ? err.message : String(err)}`); const errorMsg = err instanceof Error ? err.message : String(err);
throw err; vscode.window.showErrorMessage(`Failed to add global requirable: ${errorMsg}`);
logger.error(`Error adding global requirable: ${errorMsg}`);
} }
} }
@@ -1,354 +1,149 @@
import * as fs from 'fs/promises'; import path from "path";
import * as path from 'path'; import * as fs from 'fs/promises';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
/** /*
* Manages lua-addons: discovery, versioning, copying, and cleanup. * Lua addon naming conventions:
* All operations assume semver versioning (X.Y.Z format). * <addon-name>.<major>.<minor>.<patch>
* Addon folder names follow the pattern: `<addon-name>.<version>` (e.g., dcs-types.0.0.5) */
*/
export class LuaAddonsManager {
interface LuaAddonInfo {
name: string; /** Path where addons are installed */
sourceDir: string; private targetPath: string;
version: string;
} /** Path where addon sources are located */
private sourceExtensionPath: string;
interface InstalledAddonInfo {
name: string; private extensionContextPath: string;
version: string;
path: string; /**
} * Creates a new LuaAddonsManager instance.
*
/** * @param extensionPath - Directory where addons are installed
* Reads the extension's version from package.json * @param sourceExtensionPath - Directory where addon sources are located
* @param extensionRoot - Absolute path to the extension root directory */
* @returns The semantic version string (e.g., "0.0.5") public constructor(luaTargetPath: string, extensionPath: string) {
* @throws Error if package.json cannot be read or version is not found this.targetPath = luaTargetPath;
*/ this.sourceExtensionPath = path.join(extensionPath, "lua-addons");
export async function getExtensionVersion(extensionRoot: string): Promise<string> { this.extensionContextPath = extensionPath;
try { }
const packageJsonPath = path.join(extensionRoot, 'package.json');
const content = await fs.readFile(packageJsonPath, 'utf-8');
const packageJson = JSON.parse(content); /**
* Retrieves the version of an installed addon by name.
const version = packageJson.version as string | undefined; *
if (!version) { * Searches for a folder matching the naming pattern `<name>.<major>.<minor>.<patch>`
throw new Error('Version field not found in package.json'); * and returns the version string.
} *
* @param name - The addon name to search for (without version suffix)
return version; * @returns The version string in format "major.minor.patch", or undefined if not found
} catch (err) { * @throws Never throws, returns undefined if addon not found
throw new Error( */
`Failed to read extension version: ${err instanceof Error ? err.message : String(err)}` async getExtensionVersion(name: string): Promise<string | undefined> {
); const folders = await fs.readdir(this.targetPath, { withFileTypes: true });
} for (const folder of folders) {
} if (!folder.isDirectory()) { continue; }
/** const versionMatch = folder.name.match(/^(.+)\.(\d+)\.(\d+)\.(\d+)$/);
* Discovers all lua-addons in the bundled lua-addons directory if (!versionMatch) { continue; }
* @param extensionPath - Absolute path to the extension installation directory
* @returns Map of addon name to source directory path const addonName = versionMatch[1];
* @throws Error if lua-addons directory cannot be read if (addonName === name) {
*/ return `${versionMatch[2]}.${versionMatch[3]}.${versionMatch[4]}`;
export async function discoverLuaAddons(extensionPath: string): Promise<Map<string, string>> { }
const luaAddonsDir = path.join(extensionPath, 'lua-addons'); }
const addons = new Map<string, string>();
return undefined;
try { }
// Check if lua-addons directory exists
if (!existsSync(luaAddonsDir)) { /**
return addons; // Empty map if no lua-addons * Reads the version from the package.json file in the extension path.
} *
* @returns The version string from package.json
const entries = await fs.readdir(luaAddonsDir, { withFileTypes: true }); * @throws Error if package.json cannot be read or is missing the version field
*/
for (const entry of entries) { async getPackageVersion(): Promise<string | undefined> {
if (entry.isDirectory()) { try {
const addonName = entry.name; const packageJsonPath = path.join(this.extensionContextPath,'package.json');
const addonPath = path.join(luaAddonsDir, addonName); const content = await fs.readFile(packageJsonPath, 'utf-8');
addons.set(addonName, addonPath); const packageJson = JSON.parse(content);
}
} const version = packageJson.version as string | undefined;
if (!version) {
return addons; throw new Error('Version field not found in package.json');
} catch (err) { }
throw new Error(
`Failed to discover lua-addons: ${err instanceof Error ? err.message : String(err)}` return version;
); } catch (err) {
} throw new Error(
} `Failed to read extension version: ${err instanceof Error ? err.message : String(err)}`
);
/** }
* Determines the workspace lua-addons directory path (.vscode/lua-addons) }
* @param workspaceRoot - Absolute path to the workspace root
* @returns Absolute path to .vscode/lua-addons /**
*/ * Removes a single addon by name.
export function getWorkspaceLuaAddonsDir(workspaceRoot: string): string { *
return path.join(workspaceRoot, '.vscode', 'lua-addons'); * Deletes the addon directory matching the given name, regardless of version.
} *
* @param name - The addon name to remove (without version suffix)
/** * @throws Error if the removal operation fails
* Parses installed addon versions from the workspace lua-addons directory */
* Expects folder names in format: `<addon-name>.<version>` (e.g., dcs-types.0.0.5) async removeExtension(name: string): Promise<void> {
* @param workspaceRoot - Absolute path to the workspace root return this.removeAllExtensions([name]);
* @returns Map of addon name to version string; returns empty map if directory doesn't exist }
* @throws Error if directory cannot be read
*/ /**
export async function getInstalledVersions( * Removes multiple addons by name.
workspaceRoot: string *
): Promise<Map<string, InstalledAddonInfo>> { * Scans the extension directory for folders matching the addon naming pattern
const luaAddonsDir = getWorkspaceLuaAddonsDir(workspaceRoot); * `<name>.<major>.<minor>.<patch>` and removes those whose base name is in the
const installed = new Map<string, InstalledAddonInfo>(); * provided list. Removes all versions of matched addons.
*
try { * @param names - Array of addon names to remove (without version suffix)
// Return empty map if directory doesn't exist yet * @throws Error if the removal operation fails
if (!existsSync(luaAddonsDir)) { */
return installed; async removeAllExtensions(names: string[]): Promise<void> {
} const folders = await fs.readdir(this.targetPath, { withFileTypes: true });
for (const folder of folders) {
const entries = await fs.readdir(luaAddonsDir, { withFileTypes: true }); if (!folder.isDirectory()) { continue; }
for (const entry of entries) { // Check if folder name matches versioning pattern: name.major.minor.patch
if (entry.isDirectory()) { const versionMatch = folder.name.match(/^(.+)\.(\d+)\.(\d+)\.(\d+)$/);
const folderName = entry.name; if (!versionMatch) { continue; }
const parsed = parseAddonFolderName(folderName);
// Extract addon name from the versioned folder name
if (parsed) { const addonName = versionMatch[1];
installed.set(parsed.name, {
name: parsed.name, if (names.includes(addonName)) {
version: parsed.version, const folderPath = path.join(this.targetPath, folder.name);
path: path.join(luaAddonsDir, folderName) await fs.rm(folderPath, { recursive: true, force: true });
}); }
} }
} }
}
/**
return installed; * Installs an addon from source to the target installation directory.
} catch (err) { *
throw new Error( * Copies the addon directory from sourceExtensionPath to extensionPath.
`Failed to read installed versions: ${err instanceof Error ? err.message : String(err)}` * The source directory name should match the addon name.
); *
} * @param name - The addon name/directory to install (without version suffix)
} * @throws Error if source directory not found or copy operation fails
*/
/** async installExtension(name: string): Promise<void> {
* Copies lua-addons from the extension bundle to the workspace with versioned folder names const sourceFolderPath = path.join(this.sourceExtensionPath, name);
* @param extensionPath - Absolute path to the extension installation directory
* @param workspaceRoot - Absolute path to the workspace root const version = await this.getPackageVersion();
* @param extensionVersion - The current extension version string const versionedName = `${name}.${version}`;
* @param addonsToCopy - Map of addon name to source directory (from discoverLuaAddons) const targetFolderPath = path.join(this.targetPath, versionedName);
* @returns Map of addon name to installed path in workspace
* @throws Error if copy fails or directory creation fails if (!existsSync(sourceFolderPath)) {
*/ throw new Error(`Source extension folder not found: ${sourceFolderPath}`);
export async function copyLuaAddons( }
extensionPath: string, await fs.mkdir(targetFolderPath, { recursive: true });
workspaceRoot: string, await fs.cp(sourceFolderPath, targetFolderPath, { recursive: true });
extensionVersion: string, }
addonsToCopy: Map<string, string>
): Promise<Map<string, string>> { }
const luaAddonsDir = getWorkspaceLuaAddonsDir(workspaceRoot);
const results = new Map<string, string>();
try {
// Ensure .vscode directory exists
const vscodeDir = path.join(workspaceRoot, '.vscode');
await ensureDirectoryExists(vscodeDir);
// Ensure lua-addons directory exists
await ensureDirectoryExists(luaAddonsDir);
// Copy each addon
for (const [addonName, sourceDir] of addonsToCopy) {
const versionedFolderName = `${addonName}.${extensionVersion}`;
const destDir = path.join(luaAddonsDir, versionedFolderName);
// Remove destination if it already exists (shouldn't happen, but be safe)
if (existsSync(destDir)) {
await fs.rm(destDir, { recursive: true, force: true });
}
// Copy the addon
await copyDirectory(sourceDir, destDir);
results.set(addonName, destDir);
}
return results;
} catch (err) {
throw new Error(
`Failed to copy lua-addons: ${err instanceof Error ? err.message : String(err)}`
);
}
}
/**
* Deletes all old versions of a specific addon
* @param workspaceRoot - Absolute path to the workspace root
* @param addonName - Name of the addon (e.g., "dcs-types")
* @param currentVersion - Version to keep (e.g., "0.0.5")
* @throws Error if directory operations fail
*/
export async function deleteOldVersions(
workspaceRoot: string,
addonName: string,
currentVersion: string
): Promise<void> {
const luaAddonsDir = getWorkspaceLuaAddonsDir(workspaceRoot);
try {
// Return silently if directory doesn't exist
if (!existsSync(luaAddonsDir)) {
return;
}
const entries = await fs.readdir(luaAddonsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const parsed = parseAddonFolderName(entry.name);
// Delete if it's an old version of this addon
if (parsed && parsed.name === addonName && parsed.version !== currentVersion) {
const oldPath = path.join(luaAddonsDir, entry.name);
await fs.rm(oldPath, { recursive: true, force: true });
}
}
}
} catch (err) {
throw new Error(
`Failed to delete old versions of ${addonName}: ${
err instanceof Error ? err.message : String(err)
}`
);
}
}
/**
* Checks if an addon needs to be updated (version mismatch)
* @param installedVersion - Currently installed version or undefined if not installed
* @param currentExtensionVersion - Current extension version to compare against
* @returns true if no version is installed or version doesn't match
*/
export function requiresUpdate(
installedVersion: string | undefined,
currentExtensionVersion: string
): boolean {
return !installedVersion || installedVersion !== currentExtensionVersion;
}
/**
* Deletes all versioned addon folders for a specific addon name
* @param workspaceRoot - Absolute path to the workspace root
* @param addonName - Name of the addon to clean up completely
* @throws Error if directory operations fail
*/
export async function deleteAllVersionsOfAddon(
workspaceRoot: string,
addonName: string
): Promise<void> {
const luaAddonsDir = getWorkspaceLuaAddonsDir(workspaceRoot);
try {
// Return silently if directory doesn't exist
if (!existsSync(luaAddonsDir)) {
return;
}
const entries = await fs.readdir(luaAddonsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const parsed = parseAddonFolderName(entry.name);
// Delete all versions of this addon
if (parsed && parsed.name === addonName) {
const addonPath = path.join(luaAddonsDir, entry.name);
await fs.rm(addonPath, { recursive: true, force: true });
}
}
}
} catch (err) {
throw new Error(
`Failed to delete all versions of ${addonName}: ${
err instanceof Error ? err.message : String(err)
}`
);
}
}
/**
* Gets the currently installed addon info for all addons
* @param workspaceRoot - Absolute path to the workspace root
* @returns Map of addon name to its latest installed version info
*/
export async function getInstalledAddons(
workspaceRoot: string
): Promise<Map<string, InstalledAddonInfo>> {
return getInstalledVersions(workspaceRoot);
}
// ============================================================================
// Private Helper Functions
// ============================================================================
/**
* Parses an addon folder name in format `<name>.<version>`
* @param folderName - The folder name to parse
* @returns Object with name and version, or null if format doesn't match
*/
function parseAddonFolderName(
folderName: string
): { name: string; version: string } | null {
// Split only on the last dot to handle addon names with dots (unlikely, but safe)
const lastDotIndex = folderName.lastIndexOf('.');
if (lastDotIndex === -1) {
return null;
}
const name = folderName.substring(0, lastDotIndex);
const version = folderName.substring(lastDotIndex + 1);
// Validate semver format (basic check)
if (!/^\d+\.\d+\.\d+/.test(version)) {
return null;
}
return { name, version };
}
/**
* Ensures a directory exists, creating it if necessary
* @param dirPath - Absolute path to the directory
*/
async function ensureDirectoryExists(dirPath: string): Promise<void> {
try {
await fs.mkdir(dirPath, { recursive: true });
} catch (err) {
// Ignore EEXIST errors
if ((err as NodeJS.ErrnoException).code !== 'EEXIST') {
throw err;
}
}
}
/**
* Recursively copies a directory and its contents
* @param srcDir - Source directory path
* @param destDir - Destination directory path
*/
async function copyDirectory(srcDir: string, destDir: string): Promise<void> {
await ensureDirectoryExists(destDir);
const entries = await fs.readdir(srcDir, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(srcDir, entry.name);
const destPath = path.join(destDir, entry.name);
if (entry.isDirectory()) {
await copyDirectory(srcPath, destPath);
} else {
await fs.copyFile(srcPath, destPath);
}
}
}
@@ -3,14 +3,14 @@ import * as fs from 'fs/promises';
import * as path from 'path'; import * as path from 'path';
import * as os from 'os'; import * as os from 'os';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import * as luaAddonsManager from '../lua-addons-manager'; import { LuaAddonsManager } from '../lua-addons-manager';
/** /**
* Integration tests for lua-addons-manager * Integration tests for LuaAddonsManager
* Uses temporary directories to avoid polluting the file system * Uses temporary directories to avoid polluting the file system
*/ */
suite('lua-addons-manager', () => { suite('LuaAddonsManager', () => {
let tempDir: string; let tempDir: string;
suiteSetup(async () => { suiteSetup(async () => {
@@ -24,287 +24,232 @@ suite('lua-addons-manager', () => {
}); });
suite('getExtensionVersion', () => { suite('getExtensionVersion', () => {
test('should read version from package.json', async () => { test('should return undefined if addon not found', async () => {
const testDir = path.join(tempDir, 'getExtensionVersion-1'); const extensionDir = path.join(tempDir, 'getExtensionVersion-1');
await fs.mkdir(testDir, { recursive: true }); const sourceDir = path.join(tempDir, 'getExtensionVersion-1-source');
const packageJson = path.join(testDir, 'package.json'); await fs.mkdir(extensionDir, { recursive: true });
await fs.writeFile(packageJson, JSON.stringify({ version: '1.2.3' })); await fs.mkdir(sourceDir, { recursive: true });
const version = await luaAddonsManager.getExtensionVersion(testDir); const manager = new LuaAddonsManager(extensionDir, sourceDir);
const version = await manager.getExtensionVersion('nonexistent');
assert.strictEqual(version, undefined);
});
test('should return version string for installed addon', async () => {
const extensionDir = path.join(tempDir, 'getExtensionVersion-2');
const sourceDir = path.join(tempDir, 'getExtensionVersion-2-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
await fs.mkdir(path.join(extensionDir, 'dcs-types.1.2.3'), { recursive: true });
const manager = new LuaAddonsManager(extensionDir, sourceDir);
const version = await manager.getExtensionVersion('dcs-types');
assert.strictEqual(version, '1.2.3'); assert.strictEqual(version, '1.2.3');
}); });
test('should throw error if package.json not found', async () => { test('should return first matching version if multiple versions exist', async () => {
const testDir = path.join(tempDir, 'getExtensionVersion-2'); const extensionDir = path.join(tempDir, 'getExtensionVersion-3');
await fs.mkdir(testDir, { recursive: true }); const sourceDir = path.join(tempDir, 'getExtensionVersion-3-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon.1.0.0'), { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon.2.0.0'), { recursive: true });
const manager = new LuaAddonsManager(extensionDir, sourceDir);
const version = await manager.getExtensionVersion('addon');
// Should return one of the versions (first found)
assert.match(version!, /^[12]\.0\.0$/);
});
});
suite('getPackageVersion', () => {
test('should read version from package.json', async () => {
const extensionDir = path.join(tempDir, 'getPackageVersion-1');
const sourceDir = path.join(tempDir, 'getPackageVersion-1-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
const packageJson = path.join(extensionDir, 'package.json');
await fs.writeFile(packageJson, JSON.stringify({ version: '2.1.0' }));
const manager = new LuaAddonsManager(extensionDir, sourceDir);
const version = await manager.getPackageVersion();
assert.strictEqual(version, '2.1.0');
});
test('should throw error if package.json not found', async () => {
const extensionDir = path.join(tempDir, 'getPackageVersion-2');
const sourceDir = path.join(tempDir, 'getPackageVersion-2-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
const manager = new LuaAddonsManager(extensionDir, sourceDir);
await assert.rejects( await assert.rejects(
() => luaAddonsManager.getExtensionVersion(testDir), () => manager.getPackageVersion(),
/Failed to read extension version/ /Failed to read extension version/
); );
}); });
test('should throw error if version field missing', async () => { test('should throw error if version field missing', async () => {
const testDir = path.join(tempDir, 'getExtensionVersion-3'); const extensionDir = path.join(tempDir, 'getPackageVersion-3');
await fs.mkdir(testDir, { recursive: true }); const sourceDir = path.join(tempDir, 'getPackageVersion-3-source');
const packageJson = path.join(testDir, 'package.json'); await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
const packageJson = path.join(extensionDir, 'package.json');
await fs.writeFile(packageJson, JSON.stringify({ name: 'test' })); await fs.writeFile(packageJson, JSON.stringify({ name: 'test' }));
const manager = new LuaAddonsManager(extensionDir, sourceDir);
await assert.rejects( await assert.rejects(
() => luaAddonsManager.getExtensionVersion(testDir), () => manager.getPackageVersion(),
/Version field not found/ /Version field not found/
); );
}); });
}); });
suite('discoverLuaAddons', () => { suite('removeExtension', () => {
test('should discover lua-addons directories', async () => { test('should remove addon by name', async () => {
const testDir = path.join(tempDir, 'discoverLuaAddons-1'); const extensionDir = path.join(tempDir, 'removeExtension-1');
const luaAddonsDir = path.join(testDir, 'lua-addons'); const sourceDir = path.join(tempDir, 'removeExtension-1-source');
await fs.mkdir(path.join(luaAddonsDir, 'addon1'), { recursive: true }); await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'addon2'), { recursive: true }); await fs.mkdir(sourceDir, { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon1.1.0.0'), { recursive: true });
const addons = await luaAddonsManager.discoverLuaAddons(testDir); const manager = new LuaAddonsManager(extensionDir, sourceDir);
await manager.removeExtension('addon1');
assert.strictEqual(addons.size, 2); const remaining = await fs.readdir(extensionDir);
assert.strictEqual(addons.has('addon1'), true); assert.strictEqual(remaining.length, 0);
assert.strictEqual(addons.has('addon2'), true);
}); });
test('should return empty map if lua-addons directory does not exist', async () => { test('should not affect other addons', async () => {
const testDir = path.join(tempDir, 'discoverLuaAddons-2'); const extensionDir = path.join(tempDir, 'removeExtension-2');
await fs.mkdir(testDir, { recursive: true }); const sourceDir = path.join(tempDir, 'removeExtension-2-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon1.1.0.0'), { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon2.1.0.0'), { recursive: true });
const addons = await luaAddonsManager.discoverLuaAddons(testDir); const manager = new LuaAddonsManager(extensionDir, sourceDir);
await manager.removeExtension('addon1');
assert.strictEqual(addons.size, 0); const remaining = await fs.readdir(extensionDir);
}); assert.strictEqual(remaining.length, 1);
assert.strictEqual(remaining[0], 'addon2.1.0.0');
test('should ignore non-directory entries', async () => {
const testDir = path.join(tempDir, 'discoverLuaAddons-3');
const luaAddonsDir = path.join(testDir, 'lua-addons');
await fs.mkdir(luaAddonsDir, { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'addon1'), { recursive: true });
await fs.writeFile(path.join(luaAddonsDir, 'file.txt'), 'test');
const addons = await luaAddonsManager.discoverLuaAddons(testDir);
assert.strictEqual(addons.size, 1);
assert.strictEqual(addons.has('addon1'), true);
}); });
}); });
suite('getWorkspaceLuaAddonsDir', () => { suite('removeAllExtensions', () => {
test('should return correct .vscode/lua-addons path', () => { test('should remove multiple addons by name', async () => {
const workspaceRoot = '/path/to/workspace'; const extensionDir = path.join(tempDir, 'removeAllExtensions-1');
const result = luaAddonsManager.getWorkspaceLuaAddonsDir(workspaceRoot); const sourceDir = path.join(tempDir, 'removeAllExtensions-1-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon1.1.0.0'), { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon2.1.0.0'), { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon3.1.0.0'), { recursive: true });
assert.strictEqual(result, path.join(workspaceRoot, '.vscode', 'lua-addons')); const manager = new LuaAddonsManager(extensionDir, sourceDir);
}); await manager.removeAllExtensions(['addon1', 'addon2']);
});
suite('getInstalledVersions', () => { const remaining = await fs.readdir(extensionDir);
test('should parse installed addon versions from folder names', async () => { assert.deepStrictEqual(remaining.sort(), ['addon3.1.0.0']);
const testDir = path.join(tempDir, 'getInstalledVersions-1');
const luaAddonsDir = path.join(testDir, '.vscode', 'lua-addons');
await fs.mkdir(path.join(luaAddonsDir, 'dcs-types.0.0.5'), { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'mission-utils.1.2.3'), { recursive: true });
const installed = await luaAddonsManager.getInstalledVersions(testDir);
assert.strictEqual(installed.size, 2);
assert.strictEqual(installed.has('dcs-types'), true);
assert.strictEqual(installed.has('mission-utils'), true);
assert.strictEqual(installed.get('dcs-types')?.version, '0.0.5');
assert.strictEqual(installed.get('mission-utils')?.version, '1.2.3');
}); });
test('should return empty map if directory does not exist', async () => { test('should delete all versions of matching addons', async () => {
const testDir = path.join(tempDir, 'getInstalledVersions-2'); const extensionDir = path.join(tempDir, 'removeAllExtensions-2');
await fs.mkdir(testDir, { recursive: true }); const sourceDir = path.join(tempDir, 'removeAllExtensions-2-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon1.0.0.1'), { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon1.0.0.2'), { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon1.0.0.3'), { recursive: true });
await fs.mkdir(path.join(extensionDir, 'addon2.1.0.0'), { recursive: true });
const installed = await luaAddonsManager.getInstalledVersions(testDir); const manager = new LuaAddonsManager(extensionDir, sourceDir);
await manager.removeAllExtensions(['addon1']);
assert.strictEqual(installed.size, 0); const remaining = await fs.readdir(extensionDir);
assert.deepStrictEqual(remaining.sort(), ['addon2.1.0.0']);
}); });
test('should ignore folders with invalid version format', async () => { test('should ignore folders with invalid version format', async () => {
const testDir = path.join(tempDir, 'getInstalledVersions-3'); const extensionDir = path.join(tempDir, 'removeAllExtensions-3');
const luaAddonsDir = path.join(testDir, '.vscode', 'lua-addons'); const sourceDir = path.join(tempDir, 'removeAllExtensions-3-source');
await fs.mkdir(path.join(luaAddonsDir, 'dcs-types.0.0.5'), { recursive: true }); await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'invalid-addon'), { recursive: true }); await fs.mkdir(sourceDir, { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'bad-format.v1'), { recursive: true }); await fs.mkdir(path.join(extensionDir, 'addon1.1.0.0'), { recursive: true });
await fs.mkdir(path.join(extensionDir, 'invalid-folder'), { recursive: true });
const installed = await luaAddonsManager.getInstalledVersions(testDir); const manager = new LuaAddonsManager(extensionDir, sourceDir);
await manager.removeAllExtensions(['addon1']);
assert.strictEqual(installed.size, 1); const remaining = await fs.readdir(extensionDir);
assert.strictEqual(installed.has('dcs-types'), true); assert.deepStrictEqual(remaining.sort(), ['invalid-folder']);
assert.strictEqual(installed.has('invalid-addon'), false); });
assert.strictEqual(installed.has('bad-format'), false);
test('should not throw if addon does not exist', async () => {
const extensionDir = path.join(tempDir, 'removeAllExtensions-4');
const sourceDir = path.join(tempDir, 'removeAllExtensions-4-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
const manager = new LuaAddonsManager(extensionDir, sourceDir);
// Should not throw
await manager.removeAllExtensions(['nonexistent']);
}); });
}); });
suite('copyLuaAddons', () => { suite('installExtension', () => {
test('should copy addons with versioned folder names', async () => { test('should copy addon from source to target', async () => {
const testDir = path.join(tempDir, 'copyLuaAddons-1'); const extensionDir = path.join(tempDir, 'installExtension-1');
const sourceAddon1 = path.join(testDir, 'source-addons', 'addon1'); const sourceDir = path.join(tempDir, 'installExtension-1-source');
await fs.mkdir(sourceAddon1, { recursive: true }); await fs.mkdir(extensionDir, { recursive: true });
await fs.writeFile(path.join(sourceAddon1, 'file1.lua'), 'content1'); await fs.mkdir(sourceDir, { recursive: true });
const sourceAddon = path.join(sourceDir, 'addon1');
await fs.mkdir(sourceAddon, { recursive: true });
await fs.writeFile(path.join(sourceAddon, 'file.lua'), 'content');
const addonsToCopy = new Map<string, string>([ const manager = new LuaAddonsManager(extensionDir, sourceDir);
['addon1', sourceAddon1] await manager.installExtension('addon1');
]);
const result = await luaAddonsManager.copyLuaAddons( const targetAddon = path.join(extensionDir, 'addon1');
testDir, assert.strictEqual(existsSync(targetAddon), true);
testDir, assert.strictEqual(existsSync(path.join(targetAddon, 'file.lua')), true);
'1.0.0',
addonsToCopy
);
assert.strictEqual(result.size, 1);
const copiedPath = result.get('addon1');
assert.strictEqual(copiedPath !== undefined, true);
if (copiedPath) {
assert.strictEqual(copiedPath.includes('addon1.1.0.0'), true);
assert.strictEqual(existsSync(path.join(copiedPath, 'file1.lua')), true);
}
}); });
test('should create .vscode directory if it does not exist', async () => { test('should throw error if source directory does not exist', async () => {
const testDir = path.join(tempDir, 'copyLuaAddons-2'); const extensionDir = path.join(tempDir, 'installExtension-2');
const sourceAddon = path.join(testDir, 'source', 'addon1'); const sourceDir = path.join(tempDir, 'installExtension-2-source');
await fs.mkdir(sourceAddon, { recursive: true }); await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
const addonsToCopy = new Map<string, string>([ const manager = new LuaAddonsManager(extensionDir, sourceDir);
['addon1', sourceAddon] await assert.rejects(
]); () => manager.installExtension('nonexistent'),
/Source extension folder not found/
await luaAddonsManager.copyLuaAddons(
testDir,
testDir,
'1.0.0',
addonsToCopy
); );
const vscodeDir = path.join(testDir, '.vscode');
assert.strictEqual(existsSync(vscodeDir), true);
}); });
test('should copy nested directories recursively', async () => { test('should copy nested directories recursively', async () => {
const testDir = path.join(tempDir, 'copyLuaAddons-3'); const extensionDir = path.join(tempDir, 'installExtension-3');
const sourceAddon = path.join(testDir, 'source', 'addon1'); const sourceDir = path.join(tempDir, 'installExtension-3-source');
await fs.mkdir(extensionDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
const sourceAddon = path.join(sourceDir, 'addon1');
await fs.mkdir(path.join(sourceAddon, 'subdir'), { recursive: true }); await fs.mkdir(path.join(sourceAddon, 'subdir'), { recursive: true });
await fs.writeFile(path.join(sourceAddon, 'file.lua'), 'root'); await fs.writeFile(path.join(sourceAddon, 'file.lua'), 'root');
await fs.writeFile(path.join(sourceAddon, 'subdir', 'file.lua'), 'nested'); await fs.writeFile(path.join(sourceAddon, 'subdir', 'file.lua'), 'nested');
const addonsToCopy = new Map<string, string>([ const manager = new LuaAddonsManager(extensionDir, sourceDir);
['addon1', sourceAddon] await manager.installExtension('addon1');
]);
const result = await luaAddonsManager.copyLuaAddons( const targetAddon = path.join(extensionDir, 'addon1');
testDir, assert.strictEqual(existsSync(path.join(targetAddon, 'file.lua')), true);
testDir, assert.strictEqual(existsSync(path.join(targetAddon, 'subdir', 'file.lua')), true);
'1.0.0',
addonsToCopy
);
const copiedPath = result.get('addon1')!;
assert.strictEqual(existsSync(path.join(copiedPath, 'file.lua')), true);
assert.strictEqual(existsSync(path.join(copiedPath, 'subdir', 'file.lua')), true);
});
});
suite('deleteOldVersions', () => {
test('should delete old versions of an addon', async () => {
const testDir = path.join(tempDir, 'deleteOldVersions-1');
const luaAddonsDir = path.join(testDir, '.vscode', 'lua-addons');
await fs.mkdir(path.join(luaAddonsDir, 'addon1.0.0.1'), { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'addon1.0.0.2'), { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'addon1.0.0.3'), { recursive: true });
await luaAddonsManager.deleteOldVersions(testDir, 'addon1', '0.0.3');
const remaining = await fs.readdir(luaAddonsDir);
assert.deepStrictEqual(remaining.sort(), ['addon1.0.0.3']);
});
test('should not delete other addons', async () => {
const testDir = path.join(tempDir, 'deleteOldVersions-2');
const luaAddonsDir = path.join(testDir, '.vscode', 'lua-addons');
await fs.mkdir(path.join(luaAddonsDir, 'addon1.0.0.1'), { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'addon1.0.0.2'), { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'addon2.0.0.1'), { recursive: true });
await luaAddonsManager.deleteOldVersions(testDir, 'addon1', '0.0.2');
const remaining = await fs.readdir(luaAddonsDir);
assert.strictEqual(remaining.includes('addon1.0.0.2'), true);
assert.strictEqual(remaining.includes('addon2.0.0.1'), true);
assert.strictEqual(remaining.includes('addon1.0.0.1'), false);
});
test('should handle missing directory gracefully', async () => {
const testDir = path.join(tempDir, 'deleteOldVersions-3');
await fs.mkdir(testDir, { recursive: true });
// Should not throw
await luaAddonsManager.deleteOldVersions(testDir, 'addon1', '0.0.1');
});
});
suite('deleteAllVersionsOfAddon', () => {
test('should delete all versions of an addon', async () => {
const testDir = path.join(tempDir, 'deleteAllVersionsOfAddon-1');
const luaAddonsDir = path.join(testDir, '.vscode', 'lua-addons');
await fs.mkdir(path.join(luaAddonsDir, 'addon1.0.0.1'), { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'addon1.0.0.2'), { recursive: true });
await fs.mkdir(path.join(luaAddonsDir, 'addon2.0.0.1'), { recursive: true });
await luaAddonsManager.deleteAllVersionsOfAddon(testDir, 'addon1');
const remaining = await fs.readdir(luaAddonsDir);
assert.deepStrictEqual(remaining.sort(), ['addon2.0.0.1']);
});
});
suite('requiresUpdate', () => {
test('should return true if no version installed', () => {
const result = luaAddonsManager.requiresUpdate(undefined, '1.0.0');
assert.strictEqual(result, true);
});
test('should return true if versions do not match', () => {
const result = luaAddonsManager.requiresUpdate('1.0.0', '1.0.1');
assert.strictEqual(result, true);
});
test('should return false if versions match', () => {
const result = luaAddonsManager.requiresUpdate('1.0.0', '1.0.0');
assert.strictEqual(result, false);
});
});
suite('getInstalledAddons', () => {
test('should return installed addon information', async () => {
const testDir = path.join(tempDir, 'getInstalledAddons-1');
const luaAddonsDir = path.join(testDir, '.vscode', 'lua-addons');
await fs.mkdir(path.join(luaAddonsDir, 'dcs-types.0.0.5'), { recursive: true });
const installed = await luaAddonsManager.getInstalledAddons(testDir);
assert.strictEqual(installed.size, 1);
const addonInfo = installed.get('dcs-types');
assert.strictEqual(addonInfo !== undefined, true);
if (addonInfo) {
assert.strictEqual(addonInfo.name, 'dcs-types');
assert.strictEqual(addonInfo.version, '0.0.5');
assert.strictEqual(addonInfo.path.includes('dcs-types.0.0.5'), true);
}
}); });
}); });
}); });
+2 -2
View File
@@ -1,4 +1,4 @@
const esbuild = require("esbuild"); import esbuild from "esbuild";
const production = process.argv.includes('--production'); const production = process.argv.includes('--production');
const watch = process.argv.includes('--watch'); const watch = process.argv.includes('--watch');
@@ -9,7 +9,7 @@ async function main() {
'src/index.ts' 'src/index.ts'
], ],
bundle: true, bundle: true,
format: 'cjs', format: 'esm',
minify: production, minify: production,
sourcemap: !production, sourcemap: !production,
sourcesContent: false, sourcesContent: false,
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1,6 +1,7 @@
{ {
"name": "gh-scripting-compiler", "name": "gh-scripting-compiler",
"version": "1.0.0", "version": "1.1.5",
"type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"build": "node esbuild.js", "build": "node esbuild.js",
+1 -1
View File
@@ -8,7 +8,7 @@
"skipLibCheck": true, "skipLibCheck": true,
"paths": { "paths": {
"dcs-script-compiler":[ "dcs-script-compiler":[
"../compiler/src/ScriptCompiler.ts" "../../compiler/src/ScriptCompiler.ts"
] ]
} }
}, },
@@ -9,12 +9,6 @@ inputs:
runs: runs:
using: 'composite' using: 'composite'
steps: steps:
- name: Copy lua-addons
run: |
cp -r ../dutchies-dcs-scripting-tools/lua-addons ./lua-addons
shell: bash
working-directory: ${{ github.action_path }}
- name: Build action - name: Build action
run: | run: |
npm ci npm ci
@@ -1,9 +1,36 @@
const esbuild = require("esbuild"); const esbuild = require("esbuild");
const fs = require("fs");
const path = require("path");
const production = process.argv.includes('--production'); const production = process.argv.includes('--production');
const watch = process.argv.includes('--watch'); const watch = process.argv.includes('--watch');
async function copyDirectory(src, dest) {
await fs.promises.mkdir(dest, { recursive: true });
const entries = await fs.promises.readdir(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
await copyDirectory(srcPath, destPath);
} else {
await fs.promises.copyFile(srcPath, destPath);
}
}
}
async function main() { async function main() {
// Copy lua-addons to dist directory
const luaAddonsSource = path.join(__dirname, '../../dutchies-dcs-scripting-tools/lua-addons');
const luaAddonsDest = path.join(__dirname, 'dist/lua-addons');
if (fs.existsSync(luaAddonsSource)) {
await copyDirectory(luaAddonsSource, luaAddonsDest);
console.log('Lua addons copied to dist/');
}
const ctx = await esbuild.context({ const ctx = await esbuild.context({
entryPoints: [ entryPoints: [
'src/index.ts' 'src/index.ts'
@@ -1,6 +1,6 @@
{ {
"name": "gh-lua-addon-installer", "name": "gh-lua-addon-installer",
"version": "1.0.0", "version": "1.1.1",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"build": "node esbuild.js", "build": "node esbuild.js",
@@ -27,9 +27,9 @@ async function run() {
return; return;
} }
// Reference lua-addons relative to the dist directory // Reference lua-addons bundled in dist directory
// __dirname is dist/, so lua-addons is one level up // __dirname is dist/, lua-addons is bundled alongside
const bundledAddonsDir = path.resolve(__dirname, '../lua-addons'); const bundledAddonsDir = path.resolve(__dirname, './lua-addons');
// Verify bundled addons directory exists // Verify bundled addons directory exists
if (!existsSync(bundledAddonsDir)) { if (!existsSync(bundledAddonsDir)) {
+1 -6
View File
@@ -32,7 +32,7 @@
} }
}, },
"dutchies-dcs-scripting-tools": { "dutchies-dcs-scripting-tools": {
"version": "0.0.5", "version": "0.1.7",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@types/mocha": "10.0.10", "@types/mocha": "10.0.10",
@@ -1449,7 +1449,6 @@
"integrity": "sha512-zYvrmj9Yxd63UGaXw+kdt6A0F0s0qveJyuatIM77bYC2DE4pgmg7a50u8LR7PRtXd0x+h+Tl3eXabGm06SWd3Q==", "integrity": "sha512-zYvrmj9Yxd63UGaXw+kdt6A0F0s0qveJyuatIM77bYC2DE4pgmg7a50u8LR7PRtXd0x+h+Tl3eXabGm06SWd3Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/scope-manager": "8.70.0",
"@typescript-eslint/types": "8.70.0", "@typescript-eslint/types": "8.70.0",
@@ -1734,7 +1733,6 @@
"integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@@ -2671,7 +2669,6 @@
"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1", "@eslint-community/regexpp": "^4.12.1",
@@ -5771,7 +5768,6 @@
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -5902,7 +5898,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"