Skip to content

Commit

Permalink
Merge pull request #35 from Shresht7:hover
Browse files Browse the repository at this point in the history
Create `LocalizationHoverProvider`
  • Loading branch information
Shresht7 committed Jan 2, 2024
2 parents 0723f40 + fbc034e commit a1675a7
Show file tree
Hide file tree
Showing 32 changed files with 741 additions and 315 deletions.
6 changes: 5 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off",
// Limit the markdown table of contents to levels 2 through 4
"markdown.extension.toc.levels": "2..4"
"markdown.extension.toc.levels": "2..4",
// List of words to be considered correct by the spell checker
"cSpell.words": [
"contentuid"
]
}
103 changes: 50 additions & 53 deletions src/commands/bumpVersionNumber.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
// Library
import * as vscode from 'vscode';
import { bg3 } from '../library';

// Helpers
import { utils } from '../helpers';

/** Convert Int64 version number to string format or vice-versa */
// Type Definitions
import type { VersionKind } from '../types';

// ---------------------------
// BUMP VERSION NUMBER COMMAND
// ---------------------------

/** Bump the version number of the current project */
export async function bumpVersionNumber() {

// Exit early if no folder or workspace is open
Expand All @@ -12,68 +21,56 @@ export async function bumpVersionNumber() {
}

// Prompt the user for the kind of version bump
const options: bg3.VersionKind[] = [
bg3.VersionKind.MAJOR,
bg3.VersionKind.MINOR,
bg3.VersionKind.REVISION,
bg3.VersionKind.BUILD,
];
const response = await vscode.window.showQuickPick(options.map(opt => ({
label: utils.capitalize(opt),
selection: opt
})), {
title: "Kind"
});

// Exit early if no selection was made
if (!response?.selection) { return; };
const response = await promptForVersion();
if (!response?.selection) { return; }; // Exit early if no response

// ! Warning: Hacky code ahead. Several points of failure. Needs a second pass of improvement.

// Find the `meta.lsx` file in the workspace
// TODO: Handle case where multiple meta.lsx files are found
const metaLsxPaths = await vscode.workspace.findFiles("**/meta.lsx", null, 1);

// Return if no `meta.lsx` was found
if (!metaLsxPaths?.length) {
return vscode.window.showErrorMessage("Could not find any `meta.lsx` files in this workspace");
// Parse the `meta.lsx` file so we can get the current version number
let meta: bg3.MetaLsx;
try {
meta = await bg3.metaLsx.load();
} catch (e) {
vscode.window.showErrorMessage("No `meta.lsx` file found in the workspace");
return;
}

// Get the first `meta.lsx` path
// ? Not sure if this is the best way to deal with the problem
const metaLsxPath = metaLsxPaths[0];

// Read the fist `meta.lsx` file
let fileBuffer = await vscode.workspace.fs.readFile(metaLsxPath);
let fileContents = Buffer.from(fileBuffer).toString('utf8');

// Perform regex match for the version attribute line in the file contents
const regexExecArray = bg3.Version.lsxRegex.exec(fileContents);
if (!regexExecArray?.length) { return; } // Return early if no match was found

// Parse the bigint version from the regex capture
let bigIntVersion;
// Get the current version number
let bigIntVersion: bigint;
try {
bigIntVersion = BigInt(regexExecArray[1]);
bigIntVersion = BigInt(meta.ModuleInfo.Version64);
} catch (e) {
const message = `Failed to parse version from the meta.lsx file (${metaLsxPath})`;
return vscode.window.showErrorMessage(message);
vscode.window.showErrorMessage(`The \`meta.lsx\` file does not contain a valid version number (${meta.ModuleInfo.Version64})`);
return;
}

// Determine the updated version
// Bump the version number
const version = new bg3.Version(bigIntVersion).bump(response.selection);
meta.updateModuleInfo("Version64", version.toInt64().toString());

// Replace file contents with the new version
fileContents = fileContents.replace(
bg3.Version.lsxRegex,
`<attribute id="Version64" type="int64" value="${version.toInt64().toString()}"/>`
);
fileBuffer = Buffer.from(fileContents, 'utf8');

// Write the new file contents back to the `meta.lsx` file
vscode.workspace.fs.writeFile(metaLsxPath, fileBuffer);
// Update the version number in the `meta.lsx` file
try {
await bg3.metaLsx.save();
} catch (e) {
vscode.window.showErrorMessage(`Failed to save the updated version number (${version}) to the \`meta.lsx\` file`);
return;
}

// Show an information message for the version bump
vscode.window.showInformationMessage(`Version bumped to ${version.toString()}`);
vscode.window.showInformationMessage(`Version bumped to ${version}`);

}

// HELPER FUNCTIONS
// ----------------

/** Prompt the user for the kind of version bump */
async function promptForVersion() {
/** The set of version options */
const options: VersionKind[] = ["major", "minor", "revision", "build"];
/** The options to show to the user in the quick pick menu */
const quickPickOptions = options.map(opt => ({ label: utils.capitalize(opt), selection: opt }));
// Prompt the user to select the kind of version bump
return vscode.window.showQuickPick(quickPickOptions, {
title: "Kind",
placeHolder: "Select the kind of version bump"
});
}
42 changes: 26 additions & 16 deletions src/commands/convertVersionNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,38 @@ import { bg3 } from '../library';
// Helpers
import { editor } from '../helpers';

// ------------------------------
// CONVERT VERSION NUMBER COMMAND
// ------------------------------

/** Convert Int64 version number to string format or vice-versa */
export async function convertVersionNumber() {

// Prompt the user for the version number
const v = await vscode.window.showInputBox({
const v = await promptForVersion();
if (!v) { return; } // Exit early if no response

// Convert the version from one format to the other
const result = v.includes(".")
? new bg3.Version(v).toInt64().toString()
: new bg3.Version(BigInt(v)).toString();

// Insert the version at the cursor selection
editor.insertAtSelection(result);

}

// HELPER FUNCTIONS
// ----------------

/** Prompt the user for the version number */
async function promptForVersion() {
return vscode.window.showInputBox({

title: "Version",
prompt: "Version Number",
placeHolder: 'Example: 1.0.0.0 or 36028797018963968',

// Pre-fill the value with the currently selected text
value: editor.getSelection(),
value: editor.getSelection(), // Pre-fill the value with the currently selected text

// Perform validation on the input value
validateInput: (value) => {
Expand All @@ -31,17 +52,6 @@ export async function convertVersionNumber() {
}
}
}
});

// Return early if the input is empty
if (!v) { return; }

// Convert the version from one format to the other
const result = v.includes(".")
? new bg3.Version(v).toInt64().toString()
: new bg3.Version(BigInt(v)).toString();

// Insert the version at the cursor selection
editor.insertAtSelection(result);

});
}
14 changes: 13 additions & 1 deletion src/commands/copyModUUID.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,21 @@
import * as vscode from 'vscode';
import { bg3 } from "../library";

// ---------------------
// COPY MOD UUID COMMAND
// ---------------------

/** Copies the mod's UUID to the clipboard */
export async function copyModUUID() {

// Get mod's metadata from the `meta.lsx` file
const meta = await bg3.getMetadata();
let meta: bg3.MetaLsx;
try {
meta = await bg3.metaLsx.load();
} catch (e) {
vscode.window.showErrorMessage("No `meta.lsx` file found in the workspace");
return;
}

// Copy the UUID to the clipboard
const uuid = meta.ModuleInfo.UUID;
Expand All @@ -14,4 +25,5 @@ export async function copyModUUID() {
// Show an information message notifying the user about the action
const modName = meta.ModuleInfo.Name;
vscode.window.showInformationMessage(`📋 ${modName}'s UUID copied to clipboard! -- ${uuid}`);

}
4 changes: 4 additions & 0 deletions src/commands/generateHandle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { bg3 } from "../library";
// Helpers
import { editor } from "../helpers";

// -----------------------
// GENERATE HANDLE COMMAND
// -----------------------

/**
* Generate a random handle
* and inserts it at the active editor selection
Expand Down
4 changes: 4 additions & 0 deletions src/commands/generateUUID.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import { webcrypto } from "crypto";
// Helpers
import { editor } from "../helpers";

// ---------------------
// GENERATE UUID COMMAND
// ---------------------

/**
* Generate a random v4 UUID
* and inserts it at the active editor selection
Expand Down
6 changes: 6 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
// The module `vscode` contains the VS Code extensibility API
import * as vscode from 'vscode';

// Initializers
import { initialize } from './initializers';

// Commands
import { commands } from './commands';

Expand All @@ -17,6 +20,9 @@ export async function activate(context: vscode.ExtensionContext) {
// Show Information Message when the extension is activated
vscode.window.showInformationMessage("BG3 Modding Extension Activated!");

// Initialize Localization Contributions
initialize.localization();

// Register all the commands and providers, and subscribe to their disposables
context.subscriptions.push(
...commands,
Expand Down
55 changes: 0 additions & 55 deletions src/helpers/fs.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@

export * as editor from './editor';
export * as utils from './utils';
export * as fs from './fs';
export * as xml from './xml';
53 changes: 53 additions & 0 deletions src/helpers/xml.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Library
import * as vscode from 'vscode';
import { XMLBuilder, XMLParser, X2jOptions, XmlBuilderOptions } from "fast-xml-parser";

// --------------------
// XML HELPER FUNCTIONS
// --------------------

// DEFAULT OPTIONS
// ---------------

/** Default options for the XML parser */
const defaultParserOptions: Partial<X2jOptions> = {
ignoreAttributes: false,
attributeNamePrefix: "",
};

/** Default options for the XML builder */
const defaultBuilderOptions: Partial<XmlBuilderOptions> = {
ignoreAttributes: false,
attributeNamePrefix: "",
};

/**
* Reads the xml file at the given path and parses it as an object
* @param path The path (vscode.Uri) of the xml file to read
* @param options {@link X2jOptions} - (Default: {@link defaultParserOptions})
* @returns The parsed XML object
*/
export async function read<T extends Record<string, any>>(
path: vscode.Uri,
options: Partial<X2jOptions> = defaultParserOptions
): Promise<T> {
const buf = await vscode.workspace.fs.readFile(path);
const contents = Buffer.from(buf).toString('utf8');
return new XMLParser(options).parse(contents) as T;
}

/**
* Builds and writes the object as xml to the given path
* @param path The path (vscode.Uri) of the xml file to write to
* @param obj The object to convert to xml
* @param options {@link XmlBuilderOptions} - (Default: {@link defaultBuilderOptions})
*/
export async function write<T extends Record<string, any>>(
path: vscode.Uri,
obj: T,
options: Partial<XmlBuilderOptions> = defaultBuilderOptions
) {
const contents = new XMLBuilder(options).build(obj);
const buf = Buffer.from(contents, 'utf8');
return vscode.workspace.fs.writeFile(path, buf);
}
10 changes: 10 additions & 0 deletions src/initializers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Library
import { initializeLocalization } from './localization';

// ============
// INITIALIZERS
// ============

export const initialize = {
localization: initializeLocalization
};

0 comments on commit a1675a7

Please sign in to comment.