Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements on unit tests and linting checks, added custom external formatter error message #12

Merged
merged 3 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/cicd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ jobs:
- name: Install npm dependencies
run: npm install

- name: Run compile, formatting and linting checks
run: npm run pretest

- name: Build and run automation tests
run: npm run test

Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Change Log

## [0.0.15]

- Added custom error message when registering an external formatter via `custom.registerExternalFormatter`.
- Improved unit tests and linter checks (added code formatting check)

## [0.0.14]

- Added `custom.registerExternalFormatter` to support external formatters that send code snippets to a HTTP endpoint.
Expand Down
260 changes: 101 additions & 159 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "This extension allows you to remotely control Visual Studio Code via a REST endpoint, taking automation to the next level.",
"publisher": "dpar39",
"license": "MIT",
"version": "0.0.14",
"version": "0.0.15",
"engines": {
"vscode": "^1.55.0"
},
Expand Down Expand Up @@ -73,8 +73,9 @@
"test-compile": "tsc -p ./",
"test-watch": "tsc -watch -p ./",
"pretest": "npm run test-compile && npm run lint",
"lint": "eslint src --ext ts",
"test": "xvfb-run -a node ./out/test/runTest.js"
"lint": "eslint src --ext ts && npx prettier --check './**/*.{js,ts}'",
"test": "xvfb-run -a node ./out/test/runTest.js",
"format": "npx prettier --write './**/*.{js,jsx,mjs,cjs,ts,tsx}'"
},
"devDependencies": {
"@types/glob": "^7.1.6",
Expand Down
57 changes: 28 additions & 29 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const startHttpServer = async (
context: vscode.ExtensionContext,
host: string,
port: number,
fallbackPorts: number[]
fallbackPorts: number[],
): Promise<void> => {
let isInUse = false;
if (port) {
Expand All @@ -60,51 +60,50 @@ const startHttpServer = async (
}
}

const endBadRequest = (err: any, res: ServerResponse) => {
res.statusCode = 400;
const errStringJson = JSON.stringify(err, Object.getOwnPropertyNames(err));
const sendResponse = (res: ServerResponse, body: string, statusCode: number = 200) => {
res.statusCode = statusCode;
res.setHeader("Access-Control-Allow-Origin", "*");
res.write(errStringJson);
res.setHeader("Content-Type", "application/json");
res.write(body);
res.end();
};

const endBadRequest = (err: any, res: ServerResponse) => {
const errStringJson = JSON.stringify(err, Object.getOwnPropertyNames(err));
sendResponse(res, errStringJson, 400);
Logger.error(errStringJson);
};

const processRequest = (cmd: string, args: string[], res: ServerResponse) => {
processRemoteControlRequest(cmd, args)
.then((data) => {
res.setHeader("Content-Type", "application/json");
res.setHeader("Access-Control-Allow-Origin", "*");
res.write(JSON.stringify(data || null));
res.end();
})
.then((data) => sendResponse(res, JSON.stringify(data || null)))
.catch((err) => endBadRequest(err, res));
};

const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
let body = "";
let controlCommand: any = {};
let command: string | null;
let args: any[] = [];
if (req.url && req.url.indexOf("?") >= 0) {
const url = new URL(req.url, `http://${req.headers.host}/`);
const queryParams = new URLSearchParams(url.search);
try {
const cmd = queryParams.get("command");
const args = queryParams.has("args")
? JSON.parse(decodeURIComponent(queryParams.get("args")!))
: [];
Logger.info(`Remote request command=${cmd}, args=${args}`);
processRequest(cmd!, args, res);
} catch (err) {
endBadRequest(err, res);
command = queryParams.get("command");
if (queryParams.has("args")) {
args = JSON.parse(decodeURIComponent(queryParams.get("args")!));
}
}

let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
Logger.info(`Remote request payload: ${body}`);
const reqData = body ? JSON.parse(body) : controlCommand;
processRequest(reqData.command, reqData.args || [], res);
if (body) {
const reqData = JSON.parse(body);
command = reqData.command || command;
args = reqData.args || args;
}
Logger.info(`Remote Control request with command=${command}, args=${args}`);
processRequest(command!, args, res);
});
};
// Start the HTTP server
Expand All @@ -127,15 +126,15 @@ const startHttpServer = async (
function getDefaultPortForWorkspace(): number {
const identifier = vscode.workspace.workspaceFile
? vscode.workspace.workspaceFile.toString()
: vscode.workspace.workspaceFolders?.map(f => f.uri.toString()).join("");
: vscode.workspace.workspaceFolders?.map((f) => f.uri.toString()).join("");
if (!identifier) {
return 37100;
}
const hash = identifier.split("").reduce((a: number, b: string) => {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
const port = 37100 + (Math.abs(hash) % (65535-37100));
const port = 37100 + (Math.abs(hash) % (65535 - 37100));
return port;
}

Expand All @@ -149,7 +148,7 @@ function httpPortToPid(context: vscode.ExtensionContext, port: number): string {

function killPreviousVscodeProcessIfUsingTcpPort(
context: vscode.ExtensionContext,
port: number | undefined
port: number | undefined,
) {
Logger.info(`Checking if we need to kill previous process using port = ${port}`);
if (!port) {
Expand Down Expand Up @@ -188,7 +187,7 @@ function setupRestControl(context: vscode.ExtensionContext) {
context,
"127.0.0.1",
port,
(fallbackPorts || []).filter((p: number) => p !== port)
(fallbackPorts || []).filter((p: number) => p !== port),
);
Logger.info("VSCode REST Control is now active!");
} else {
Expand Down
20 changes: 16 additions & 4 deletions src/services/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,25 @@ import * as http from "http";
import * as https from "https";

let formatterRegistration: vscode.Disposable;
const defaultErrorMessage =
"Error sending request to the external formatter. Make sure the formatter HTTP endpoint is up and running.";
export async function registerExternalFormatter(
formatterEndpoint: string,
languages: string[],
httpMethod: string
httpMethod: string,
onErrorMessage: string,
) {
languages = languages || (await vscode.languages.getLanguages());
httpMethod = httpMethod || "POST";
onErrorMessage = onErrorMessage || defaultErrorMessage;

if (formatterRegistration) {
formatterRegistration.dispose();
}
const url = new URL(formatterEndpoint);
formatterRegistration = vscode.languages.registerDocumentFormattingEditProvider(languages, {
provideDocumentFormattingEdits(
doc: vscode.TextDocument
doc: vscode.TextDocument,
): vscode.ProviderResult<vscode.TextEdit[]> {
const payload = JSON.stringify({
file: doc.fileName,
Expand All @@ -29,13 +34,15 @@ export async function registerExternalFormatter(
path: url.pathname,
method: httpMethod,
headers: {
// eslint-disable-next-line @typescript-eslint/naming-convention
"Content-Type": "application/json",
// eslint-disable-next-line @typescript-eslint/naming-convention
"Content-Length": Buffer.byteLength(payload),
},
};
const range = new vscode.Range(
doc.lineAt(0).range.start,
doc.lineAt(doc.lineCount - 1).range.end
doc.lineAt(doc.lineCount - 1).range.end,
);
return new Promise((accept, reject) => {
const httpModule = url.protocol.startsWith("https") ? https : http;
Expand All @@ -51,10 +58,15 @@ export async function registerExternalFormatter(
accept([]); // no edits
vscode.window.showErrorMessage(
`Failed to format document with custom formatter: ${err}`,
"OK"
"OK",
);
});
});
req.on("error", (err) => {
req.destroy();
accept([]); // no edits
vscode.window.showErrorMessage(`${onErrorMessage} - ${err}`, "OK");
});
req.write(payload);
req.end();
});
Expand Down
2 changes: 1 addition & 1 deletion src/services/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class Logger {
}

Logger.channel?.appendLine(
`["${type}" - ${new Date().getHours()}:${new Date().getMinutes()}] ${message}`
`["${type}" - ${new Date().getHours()}:${new Date().getMinutes()}] ${message}`,
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/services/quickPick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export async function quickPick(data: any) {
picker.onDidHide(() => {
resolve(picker.selectedItems);
disposable.dispose();
})
}),
);
for (const item of picker.items) {
if (item.label === defaultLabel) {
Expand Down
7 changes: 3 additions & 4 deletions src/services/requestProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ export async function processRemoteControlRequest(command: string, args: any[]):
}

if (command === "custom.eval") {
eval(args[0]);
return;
return eval(args[0]);
}

if (command === "custom.listInstalledExtensions") {
Expand Down Expand Up @@ -125,7 +124,7 @@ export async function processRemoteControlRequest(command: string, args: any[]):
}
let uri = null;
if (!path.isAbsolute(filePath)) {
let candidates = await vscode.workspace.findFiles(args[0]);
let candidates = await vscode.workspace.findFiles(filePath);
if (candidates.length === 1) {
uri = candidates[0];
}
Expand All @@ -143,7 +142,7 @@ export async function processRemoteControlRequest(command: string, args: any[]):
}

if (command === "custom.registerExternalFormatter") {
return await registerExternalFormatter(args[0], args[1], args[2]);
return await registerExternalFormatter(args[0], args[1], args[2], args[3]);
}

// try to run an arbitrary command with the arguments provided as is
Expand Down
36 changes: 28 additions & 8 deletions src/test/suite/extension.test.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,56 @@
import * as assert from "assert";
import { EXTENSION_ID } from "../../extension";
import * as fs from "fs";

// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import { makeRequest } from "./sendPostRequest";

suite("Extension Test Suite", () => {
suiteSetup(async () => { });
suiteSetup(async () => {});

suiteTeardown(async () => { });
suiteTeardown(async () => {});

test("check can list extensions", async () => {
const extensionIds: string[] = (await makeRequest("custom.listInstalledExtensions")) as string[];
const extensionIds: string[] = (await makeRequest(
"custom.listInstalledExtensions",
)) as string[];
assert(extensionIds.includes(EXTENSION_ID));
}).timeout(5000);

test("get workspace folders", async () => {
const workspaceFolders = (await makeRequest("custom.workspaceFolders")) as string[];
const workspaceFolders = (await makeRequest("custom.workspaceFolders")) as any[];
assert(workspaceFolders.length === 1);
const ws = workspaceFolders[0] as any;
assert(ws.name === 'workspace1');
const ws = workspaceFolders[0];
assert(ws.name === "workspace1");
assert(ws.index === 0);
assert(ws.uri.startsWith("file://"));
assert(ws.uri.endsWith("/workspace1"));

const workspaceFile = await makeRequest("custom.workspaceFile", undefined, undefined, false) as any;
const workspaceFile = (await makeRequest(
"custom.workspaceFile",
undefined,
undefined,
false,
)) as any;
assert(workspaceFile === null); // no workspace file
});

test("get all commands registred in vscode", async () => {
test("get all commands registered in vscode", async () => {
const commands: string[] = (await makeRequest("custom.getCommands")) as string[];
assert(commands.length > 100);
});

test("test can open document and get its content", async () => {
const xx = await makeRequest("custom.goToFileLineCharacter", ["demo.py:17:28"]);
const content: string = (await makeRequest("custom.eval", [
"vscode.window.activeTextEditor?.document.getText()",
])) as string;
const workspaceFolders = (await makeRequest("custom.workspaceFolders")) as any[];
const workspaceAbsPath = workspaceFolders[0].uri.slice("file://".length);
const expectedContent = fs.readFileSync(workspaceAbsPath + "/demo.py", {
encoding: "utf-8",
});
assert(content === expectedContent);
});
});
8 changes: 4 additions & 4 deletions src/test/suite/sendPostRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ export async function makeRequest(
command: string,
args: any[] = [],
port: number = 0,
urlEncoded = true
urlEncoded = true,
) {
return new Promise((resolve, reject) => {
const path = urlEncoded
? `/?command=${command}&args=${encodeURIComponent(JSON.stringify(args))}`
: '/';
: "/";
const req = http.request(
{
method: "POST",
hostname: "localhost",
port: port || getListeningPort(),
path: path
path: path,
},
(res) => {
const chunks: any[] = [];
Expand All @@ -25,7 +25,7 @@ export async function makeRequest(
const resBody = Buffer.concat(chunks);
resolve(JSON.parse(resBody.toString()));
});
}
},
);
req.on("error", reject);
if (!urlEncoded) {
Expand Down
Loading