vscode#extensions TypeScript Examples
The following examples show how to use
vscode#extensions.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ALLangServerProxy.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* Get actual AL Language extension.
*/
public GetALExtension() : Extension<any> | undefined {
let storeVersion = extensions.getExtension('ms-dynamics-smb.al');
let vsixVersion = extensions.getExtension('Microsoft.al');
if ((storeVersion) && (vsixVersion)) {
if (storeVersion.isActive) {
return storeVersion;
}
if (vsixVersion.isActive) {
return vsixVersion;
}
return storeVersion;
}
if (storeVersion) {
return storeVersion;
}
return vsixVersion;
}
Example #2
Source File: pythonEnvironment.ts From vscode-dbt-power-user with MIT License | 6 votes |
private async activatePythonExtension(): Promise<PythonExecutionDetails> {
const extension = extensions.getExtension("ms-python.python")!;
if (!extension.isActive) {
await extension.activate();
}
await extension.exports.ready;
const settings = extension.exports.settings;
return (this.executionDetails = {
getPythonPath: () =>
settings.getExecutionDetails(workspace.workspaceFile).execCommand[0],
onDidChangeExecutionDetails: settings.onDidChangeExecutionDetails,
});
}
Example #3
Source File: DrawioExtensionApi.ts From vscode-drawio with GNU General Public License v3.0 | 6 votes |
export function getDrawioExtensions(): DrawioExtension[] {
return extensions.all
.filter(
(e) =>
(e.packageJSON as DrawioExtensionJsonManifest)
.isDrawioExtension === true
)
.map((e) => new DrawioExtension(e));
}
Example #4
Source File: telemetry.ts From vscode-recall with MIT License | 6 votes |
constructor(private enabled: boolean) {
const extensionId = 'frenya.vscode-recall';
const extension = extensions.getExtension(extensionId)!;
const extensionVersion = extension.packageJSON.version;
// following key just allows you to send events to azure insights API
// so it does not need to be protected
// but obfuscating anyways - bots scan github for keys, but if you want my key you better work for it, damnit!
const innocentKitten = Buffer.from(
'NmE3YmNjOTYtZjVmYi00NDIwLTgyZjktYzRhNDUxNzhiMGE2',
'base64',
).toString();
this.reporter = new TelemetryReporter(extensionId, extensionVersion, innocentKitten);
this.resetMeasurements();
}
Example #5
Source File: extension.test.ts From intersystems-servermanager with MIT License | 6 votes |
suite("Extension Test Suite", () => {
suiteSetup(async function () {
// make sure extension is activated
const ext = extensions.getExtension(extensionId);
if (ext) {
await ext.activate();
} else {
assert.fail("Extension not found");
}
});
before(() => {
window.showInformationMessage("Start all tests.");
});
test("Extension started", () => {
assert.ok("All good");
});
});
Example #6
Source File: settings.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
static async update(_wsRoot: string): Promise<Required<CodeConfigChanges>> {
const ctx = "WorkspaceConfig:update";
const src = ExtensionProvider.getWorkspaceConfig();
const changes = await Settings.upgrade(src, _SETTINGS);
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
const vpath = pathForVaultRoot({ wsRoot, vault: vaults[0] });
const vscodeDir = path.join(vpath, ".vscode");
const snippetChanges = await Snippets.upgradeOrCreate(vscodeDir);
Logger.info({ ctx, vscodeDir, snippetChanges });
return {
extensions: {},
settings: changes,
snippetChanges,
};
}
Example #7
Source File: settings.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
/**
* Get Dendron recommended extensions
*/
static getDendronExtensionRecommendations() {
return _.filter(Extensions.configEntries(), (ent) => {
return _.isUndefined(ent.action);
}).map((ent) => {
return {
id: ent.default,
extension: extensions.getExtension(ent.default),
};
});
}
Example #8
Source File: UpgradeSettings.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
async execute(_opts: UpgradeSettingsCommandOpts) {
const ctx = "Upgrade:execute";
L.info({ ctx });
const wsRoot = (await DendronExtension.workspaceRoots())[0];
const newConfig = await WorkspaceConfig.update(wsRoot!);
this.L.info({ ctx, newConfig });
// vscode doesn't let us uninstall extensions
// tell user to uninstall extensions we no longer want
const badExtensions: Extension<any>[] =
(newConfig.extensions.unwantedRecommendations
?.map((ext) => {
return extensions.getExtension(ext);
})
.filter(Boolean) as Extension<any>[]) || [];
this.L.info({ ctx, badExtensions });
if (!_.isEmpty(badExtensions)) {
const msg = [
"Manual action needed!",
"The following extensions need to be uninstalled: ",
]
.concat([
badExtensions.map((ext) => ext.packageJSON.displayName).join(", "),
])
.concat([
"- Reload the window afterwards and Dendron will offer to install the Dendron version of the extension",
]);
window.showWarningMessage(msg.join(" "));
}
return { configUpdate: newConfig };
}
Example #9
Source File: extension.ts From plugin-vscode with Apache License 2.0 | 6 votes |
constructor() {
this.ballerinaHome = '';
this.ballerinaCmd = '';
this.ballerinaVersion = '';
this.webviewPanels = {};
this.sdkVersion = window.createStatusBarItem(StatusBarAlignment.Left, 100);
this.sdkVersion.text = `Ballerina SDK: Detecting`;
this.sdkVersion.command = `ballerina.showLogs`;
this.sdkVersion.show();
this.isSwanLake = false;
this.is12x = false;
// Load the extension
this.extension = extensions.getExtension(EXTENSION_ID)!;
this.clientOptions = {
documentSelector: [{ scheme: 'file', language: LANGUAGE.BALLERINA }, { scheme: 'file', language: LANGUAGE.TOML }],
synchronize: { configurationSection: LANGUAGE.BALLERINA },
outputChannel: getOutputChannel(),
revealOutputChannelOn: RevealOutputChannelOn.Never,
};
this.telemetryReporter = createTelemetryReporter(this);
}
Example #10
Source File: spFormat.ts From sourcepawn-vscode with MIT License | 6 votes |
getNativeBinary() {
let nativeBinary;
const sysPlatform = platform();
const sysArch = arch();
const ext = extensions.getExtension("Sarrus.sourcepawn-vscode");
if (ext === undefined) {
throw Error("Extension not found.");
}
const myExtDir = ext.extensionPath;
if (sysPlatform === "win32") {
nativeBinary = join(myExtDir, "/bin/win32/clang-format.exe");
} else {
nativeBinary = join(
myExtDir,
`/bin/${sysPlatform}_${sysArch}/clang-format`
);
}
if (existsSync(nativeBinary)) {
return nativeBinary;
}
// Let arm64 macOS fall back to x64
if (sysPlatform === "darwin" && sysArch === "arm64") {
nativeBinary = join(myExtDir, `/bin/darwin_x64/clang-format`);
if (existsSync(nativeBinary)) {
return nativeBinary;
}
}
const message =
"This module doesn't bundle the clang-format executable for your platform. " +
`(${sysPlatform}_${sysArch})\n` +
"Please let the author know on GitHub.\n";
throw new Error(message);
}
Example #11
Source File: extension.ts From vscode-microprofile with Apache License 2.0 | 6 votes |
async function getJavaExtensionAPI() : Promise<JavaExtensionAPI> {
const vscodeJava = extensions.getExtension(JAVA_EXTENSION_ID);
if (!vscodeJava) {
throw new Error("VSCode java is not installed");
}
const api = await vscodeJava.activate();
if (!api) {
throw new Error("VSCode java api not found");
}
return Promise.resolve(api);
}
Example #12
Source File: extension.ts From language-tools with MIT License | 6 votes |
function warnIfOldExtensionInstalled() {
if (extensions.getExtension('JamesBirtles.svelte-vscode')) {
window.showWarningMessage(
'It seems you have the old and deprecated extension named "Svelte" installed. Please remove it. ' +
'Through the UI: You can find it when searching for "@installed" in the extensions window (searching "Svelte" won\'t work). ' +
'Command line: "code --uninstall-extension JamesBirtles.svelte-vscode"'
);
}
}
Example #13
Source File: tsplugin.ts From language-tools with MIT License | 6 votes |
private async toggleTsPlugin(enable: boolean) {
const extension = extensions.getExtension('vscode.typescript-language-features');
if (!extension) {
return;
}
// This somewhat semi-public command configures our TypeScript plugin.
// The plugin itself is always present, but enabled/disabled depending on this config.
// It is done this way because it allows us to toggle the plugin without restarting VS Code
// and without having to do hacks like updating the extension's package.json.
commands.executeCommand('_typescript.configurePlugin', 'typescript-svelte-plugin', {
enable
});
}
Example #14
Source File: createCHANGELOG.ts From sourcepawn-vscode with MIT License | 6 votes |
export function run(rootpath?: string) {
// get workspace folder
let workspaceFolders = Workspace.workspaceFolders;
if (workspaceFolders === undefined) {
window.showErrorMessage("No workspace are opened.");
return 1;
}
//Select the rootpath
if (rootpath === undefined || typeof rootpath !== "string") {
rootpath = workspaceFolders?.[0].uri.fsPath;
}
// Check if CHANGELOG.md already exists
let changelogFilePath = join(rootpath, "CHANGELOG.md");
if (existsSync(changelogFilePath)) {
window.showErrorMessage("CHANGELOG.md already exists, aborting.");
return 2;
}
let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
.extensionPath;
let changelogTemplatePath: string = join(
myExtDir,
"templates/CHANGELOG_template.md"
);
copyFileSync(changelogTemplatePath, changelogFilePath);
return 0;
}
Example #15
Source File: DoExport.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* Verify Prerequisites for exporting documentations.
* @returns True if export can be processed. Otherwise false.
*/
private VerifyPrerequisite(): boolean {
if (this.activeEditor === undefined || this.activeEditor === null) {
window.showErrorMessage('Please open a file in the project you want to export the documentation for.');
return false;
}
if (ALObjectCache.ALObjects.length === 0) {
window.showErrorMessage('No objects to export found in AL Object Cache.');
return false;
}
var _extension = extensions.getExtension(Configuration.ExtensionName());
if ((_extension === undefined) || (_extension === null)) {
window.showErrorMessage('Unable to find Visual Studio Code extension. Please try re-install.');
return false;
}
this.extension = _extension;
this.extensionManifest = this.extension?.packageJSON;
return true;
}
Example #16
Source File: q-conn.ts From vscode-q with MIT License | 5 votes |
customizedAuthExtension = extensions.getExtension('jshinonome.vscode-q-auth')
Example #17
Source File: Git.ts From al-objid with MIT License | 5 votes |
public getGitAPI(): any {
const gitExtension = extensions?.getExtension("vscode.git")?.exports;
const git = gitExtension?.getAPI(1);
return git;
}
Example #18
Source File: constants.ts From al-objid with MIT License | 5 votes |
EXTENSION_VERSION = extensions.getExtension("vjeko.vjeko-al-objid")?.packageJSON?.version
Example #19
Source File: md.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
static hasLegacyPreview() {
return !_.isUndefined(
extensions.getExtension("dendron.dendron-markdown-preview-enhanced")
);
}
Example #20
Source File: createScript.ts From sourcepawn-vscode with MIT License | 5 votes |
export function run(rootpath?: string) {
let AuthorName: string = Workspace.getConfiguration("sourcepawn").get(
"AuthorName"
);
if (!AuthorName) {
window
.showWarningMessage("You didn't specify an author name.", "Open Settings")
.then((choice) => {
if (choice === "Open Settings") {
commands.executeCommand(
"workbench.action.openSettings",
"@ext:sarrus.sourcepawn-vscode"
);
}
});
}
let GithubName: string = Workspace.getConfiguration("sourcepawn").get(
"GithubName"
);
// get workspace folder
let workspaceFolders = Workspace.workspaceFolders;
if (!workspaceFolders) {
window.showErrorMessage("No workspace are opened.");
return 1;
}
//Select the rootpath
if (rootpath === undefined) {
rootpath = workspaceFolders?.[0].uri.fsPath;
}
let rootname = basename(rootpath);
// create a scripting folder if it doesn't exist
let scriptingFolderPath = join(rootpath, "scripting");
if (!existsSync(scriptingFolderPath)) {
mkdirSync(scriptingFolderPath);
}
// Check if file already exists
let scriptFileName: string = rootname + ".sp";
let scriptFilePath = join(rootpath, "scripting", scriptFileName);
if (existsSync(scriptFilePath)) {
window.showErrorMessage(scriptFileName + " already exists, aborting.");
return 2;
}
let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
.extensionPath;
let tasksTemplatesPath: string = join(
myExtDir,
"templates/plugin_template.sp"
);
copyFileSync(tasksTemplatesPath, scriptFilePath);
// Replace placeholders
try {
let data = readFileSync(scriptFilePath, "utf8");
let result = data.replace(/\${AuthorName}/gm, AuthorName);
result = result.replace(/\${plugin_name}/gm, rootname);
result = result.replace(/\${GithubName}/gm, GithubName);
writeFileSync(scriptFilePath, result, "utf8");
} catch (err) {
console.log(err);
return 3;
}
workspace
.openTextDocument(URI.file(scriptFilePath))
.then((document) => window.showTextDocument(document));
return 0;
}
Example #21
Source File: createREADME.ts From sourcepawn-vscode with MIT License | 5 votes |
export function run(rootpath?: string) {
let GithubName: string = Workspace.getConfiguration("sourcepawn").get(
"GithubName"
);
if (!GithubName) {
window
.showWarningMessage(
"You didn't specify a GitHub username.",
"Open Settings"
)
.then((choice) => {
if (choice === "Open Settings") {
commands.executeCommand(
"workbench.action.openSettings",
"@ext:sarrus.sourcepawn-vscode"
);
}
});
}
// get workspace folder
let workspaceFolders = Workspace.workspaceFolders;
if (!workspaceFolders) {
window.showErrorMessage("No workspace are opened.");
return 1;
}
//Select the rootpath
if (rootpath === undefined) {
rootpath = workspaceFolders?.[0].uri.fsPath;
}
let rootname = basename(rootpath);
// Check if README.md already exists
let readmeFilePath = join(rootpath, "README.md");
if (existsSync(readmeFilePath)) {
window.showErrorMessage("README.md already exists, aborting.");
return 2;
}
let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
.extensionPath;
let tasksTemplatesPath: string = join(
myExtDir,
"templates/README_template.MD"
);
copyFileSync(tasksTemplatesPath, readmeFilePath);
// Replace placeholders
try {
let result = readFileSync(readmeFilePath, "utf8");
result = result.replace(/\${plugin_name}/gm, rootname);
result = result.replace(/\${GithubName}/gm, GithubName);
writeFileSync(readmeFilePath, result, "utf8");
} catch (err) {
console.log(err);
return 3;
}
return 0;
}
Example #22
Source File: createGitHubActions.ts From sourcepawn-vscode with MIT License | 5 votes |
export function run(rootpath?: string) {
// get workspace folder
let workspaceFolders = Workspace.workspaceFolders;
if (!workspaceFolders) {
let err: string = "No workspace are opened.";
window.showErrorMessage(err);
console.log(err);
return 1;
}
//Select the rootpath
if (rootpath === undefined) {
rootpath = workspaceFolders?.[0].uri.fsPath;
}
let rootname = basename(rootpath);
// create .github folder if it doesn't exist
let masterFolderPath = join(rootpath, ".github");
if (!existsSync(masterFolderPath)) {
mkdirSync(masterFolderPath);
}
// create workflows folder if it doesn't exist
masterFolderPath = join(rootpath, ".github", "workflows");
if (!existsSync(masterFolderPath)) {
mkdirSync(masterFolderPath);
}
// Check if main.yml already exists
let masterFilePath = join(rootpath, ".github/workflows/main.yml");
if (existsSync(masterFilePath)) {
let err: string = "main.yml already exists, aborting.";
window.showErrorMessage(err);
console.log(err);
return 2;
}
let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
.extensionPath;
let tasksTemplatesPath: string = join(
myExtDir,
"templates/main_template.yml"
);
let result = readFileSync(tasksTemplatesPath, "utf-8");
// Replace placeholders
try {
result = result.replace(/\${plugin_name}/gm, rootname);
writeFileSync(masterFilePath, result, "utf8");
} catch (err) {
console.log(err);
return 3;
}
// Check if test.yml already exists
masterFilePath = join(rootpath, ".github/workflows/test.yml");
if (existsSync(masterFilePath)) {
let err: string = "test.yml already exists, aborting.";
window.showErrorMessage(err);
console.log(err);
return 2;
}
tasksTemplatesPath = join(myExtDir, "templates/test_template.yml");
result = readFileSync(tasksTemplatesPath, "utf-8");
// Replace placeholders
try {
result = result.replace(/\${plugin_name}/gm, rootname);
writeFileSync(masterFilePath, result, "utf8");
} catch (err) {
console.log(err);
return 4;
}
return 0;
}
Example #23
Source File: tool.ts From git-commit-plugin with MIT License | 5 votes |
getGitExtension = ()=> {
const vscodeGit = extensions.getExtension<GitExtension>('vscode.git');
const gitExtension = vscodeGit && vscodeGit.exports;
return gitExtension;
}
Example #24
Source File: spLinter.ts From sourcepawn-vscode with MIT License | 4 votes |
/**
* Lint a TextDocument object and add its diagnostics to the
* @param {TextDocument} document The document to lint.
* @returns void
*/
export function refreshDiagnostics(document: TextDocument): void {
// Check if the user specified not to enable the linter for this file.
const range = new Range(0, 0, 1, 0);
const text = document.getText(range);
// Check if the setting to activate the linter is set to true.
const workspaceFolder = Workspace.getWorkspaceFolder(document.uri);
const enableLinter: boolean = Workspace.getConfiguration(
"sourcepawn",
workspaceFolder
).get<boolean>("enableLinter");
// Stop early if linter is disabled.
if (
text === "" ||
/\/\/linter=false/.test(text) ||
!enableLinter ||
extname(document.fileName) !== ".sp"
) {
compilerDiagnostics.set(document.uri, []);
return;
}
const tmpPath = join(
extensions.getExtension("Sarrus.sourcepawn-vscode").extensionPath,
"tmpCompiled.smx"
);
const tmpFile = join(__dirname, "temp.sp");
const spcomp =
Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>(
"SpcompPath"
) || "";
if (!spcomp) {
return;
}
// Get the previous instance of spcomp if it exists
let throttle = throttles[document.uri.path];
if (throttle === undefined) {
throttle = new TimeoutFunction();
throttles[document.uri.path] = throttle;
}
// Cancel the previous instance and start a new one.
throttle.cancel();
throttle.start(() => {
const mainPath = findMainPath(document.uri);
// Separate the cases if we are using mainPath or not.
let scriptingFolder: string;
let filePath: string;
if (mainPath !== undefined && mainPath !== "") {
scriptingFolder = dirname(mainPath);
filePath = mainPath;
} else {
scriptingFolder = dirname(document.uri.fsPath);
let file = openSync(tmpFile, "w", 0o765);
writeSync(file, document.getText());
closeSync(file);
filePath = tmpFile;
}
// Generate compiler arguments.
const compilerArgs = [
"-i" +
Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
"SourcemodHome"
) || "",
"-i" + scriptingFolder,
"-i" + join(scriptingFolder, "include"),
"-v0",
filePath,
"-o" + tmpPath,
];
// Add a space at the beginning of every element, for security.
Workspace.getConfiguration("sourcepawn", workspaceFolder)
.get<string[]>("linterCompilerOptions")
.forEach((e) => compilerArgs.push(" " + e));
// Add the optional includes folders.
getAllPossibleIncludeFolderPaths(document.uri, true).forEach((e) =>
compilerArgs.push(`-i${e}`)
);
// Run the blank compile.
execFile(spcomp, compilerArgs, (error, stdout) => {
// If it compiled successfully, delete the temporary files.
if (!error) {
unlink(tmpPath, (err) => {
if (err) {
console.error(err);
}
});
}
parseSPCompErrors(
stdout,
compilerDiagnostics,
mainPath === undefined ? document.uri.fsPath : undefined
);
});
}, 300);
}
Example #25
Source File: main.ts From karma-test-explorer with MIT License | 4 votes |
activate = async () => {
const workspaceOutputChannel = new OutputChannelLog(EXTENSION_OUTPUT_CHANNEL_NAME);
const testExplorerExtension = extensions.getExtension<TestHub>(testExplorerExtensionId);
const logger: SimpleLogger = new SimpleLogger(workspaceOutputChannel, 'Main', LogLevel.DEBUG); // FIXME to INFO
disposables.push(workspaceOutputChannel, logger);
if (!testExplorerExtension) {
const errorMsg = 'ERROR: Could not find Test Explorer UI extension';
logger.error(() => errorMsg);
throw new Error(errorMsg);
}
const testHub = testExplorerExtension.exports;
const workspaceFolders = workspace.workspaceFolders ?? [];
const workspaceType = workspaceFolders.length > 1 ? WorkspaceType.MultiFolder : WorkspaceType.SingleFolder;
const projectFactory = new ProjectFactory(workspaceType, new SimpleLogger(logger, ProjectFactory.name));
const allProjects = projectFactory.createProjectsForWorkspaceFolders(...workspaceFolders);
const isMultiProjectWorkspace = allProjects.length > 1;
const portAcquisitionManager = new PortAcquisitionManager(new SimpleLogger(logger, PortAcquisitionManager.name));
const multiStatusDisplay = new MultiStatusDisplay(window.createStatusBarItem());
const configChangeManager = new ConfigChangeManager<ConfigSetting>(
new SimpleLogger(logger, ConfigChangeManager.name),
{ configNamespace: EXTENSION_CONFIG_PREFIX }
);
disposables.push(portAcquisitionManager, configChangeManager);
const sharedAdapterComponents: SharedAdapterComponents = {
portAcquisitionManager,
multiStatusDisplay
};
processAddedProjects(
allProjects,
isMultiProjectWorkspace,
workspaceOutputChannel,
testHub,
sharedAdapterComponents,
logger
);
const processAddedWorkspaceFolders = (addedWorkspaceFolders: readonly WorkspaceFolder[]) => {
const addedProjects = projectFactory.createProjectsForWorkspaceFolders(...addedWorkspaceFolders);
processAddedProjects(
addedProjects,
isMultiProjectWorkspace,
workspaceOutputChannel,
testHub,
sharedAdapterComponents,
logger
);
};
const processRemovedWorkspaceFolders = async (removedWorkspaceFolders: readonly WorkspaceFolder[]) => {
const removedProjects = [...workspaceProjects].filter(project =>
removedWorkspaceFolders.some(folder => folder.uri.fsPath === project.workspaceFolder.uri.fsPath)
);
await processRemovedProjects(removedProjects, testHub, logger);
};
const processChangedWorkspaceFolders = async (changedWorkspaceFolders: readonly WorkspaceFolder[]) => {
await processRemovedWorkspaceFolders(changedWorkspaceFolders);
processAddedWorkspaceFolders(changedWorkspaceFolders);
};
workspaceFolders.forEach(workspaceFolder => {
logger.debug(() => 'Subscribing for workspace config changes');
const workspaceFolderName = basename(normalizePath(workspaceFolder.uri.fsPath));
const configChangePrompt = `Settings changed for workspace folder ${workspaceFolderName}. Apply settings?`;
configChangeManager.watchForConfigChange(
workspaceFolder,
Object.values(WorkspaceConfigSetting),
async () => processChangedWorkspaceFolders([workspaceFolder]),
{ promptMessage: configChangePrompt }
);
});
const workspaceFolderChangeSubscription = workspace.onDidChangeWorkspaceFolders(folderChangeEvent => {
processAddedWorkspaceFolders(folderChangeEvent.added);
processRemovedWorkspaceFolders(folderChangeEvent.removed);
});
disposables.push(workspaceFolderChangeSubscription, workspaceOutputChannel);
const selectProjectsCommand = commands.registerCommand(ExtensionCommands.SelectProjects, () =>
processProjectCommand(
'Select workspace projects to include',
project =>
activateProject(
project,
isMultiProjectWorkspace,
workspaceOutputChannel,
testHub,
sharedAdapterComponents,
logger
),
project => deactivateProject(project, testHub, logger)
)
);
const executeFunctionCommand = commands.registerCommand(ExtensionCommands.ExecuteFunction, (fn: () => void) => fn());
disposables.push(selectProjectsCommand, executeFunctionCommand);
}
Example #26
Source File: extension.test.ts From vscode-file-downloader with MIT License | 4 votes |
suite(`Integration Tests`, () => {
window.showInformationMessage(`Start all tests.`);
let fileDownloader: IFileDownloader;
suiteSetup(async () => {
const downloaderExtension = extensions.getExtension(`mindaro-dev.file-downloader`);
assert(downloaderExtension);
await downloaderExtension.activate();
fileDownloader = downloaderExtension.exports;
});
teardown(async () => {
await rimrafAsync(MockGlobalStoragePath);
});
test(`Activate extension`, () => {
assert(fileDownloader);
});
test(`Simple download`, async () => {
assert(
await fileDownloader.downloadFile(
TestDownloadUri,
TestDownloadFilename,
MockExtensionContext
)
);
});
test(`Get item with no downloads`, async () => {
await assert.rejects(fileDownloader.getItem(TestDownloadFilename, MockExtensionContext));
});
test(`Get item with one download`, async () => {
const downloadedUri: Uri = await fileDownloader.downloadFile(TestDownloadUri, TestDownloadFilename, MockExtensionContext);
const getItemResult: Uri = await fileDownloader.getItem(TestDownloadFilename, MockExtensionContext);
assert.deepStrictEqual(downloadedUri, getItemResult);
await assert.doesNotReject(fs.promises.access(getItemResult.fsPath));
});
test(`Get item with multiple downloads`, async () => {
const downloadedItem1 = await fileDownloader.downloadFile(TestDownloadUri, `1.pdf`, MockExtensionContext);
const downloadedItem2 = await fileDownloader.downloadFile(TestDownloadUri, `2.pdf`, MockExtensionContext);
const downloadedItem3 = await fileDownloader.downloadFile(TestDownloadUri, `3.pdf`, MockExtensionContext);
const getItem1 = await fileDownloader.getItem(`1.pdf`, MockExtensionContext);
const getItem2 = await fileDownloader.getItem(`2.pdf`, MockExtensionContext);
const getItem3 = await fileDownloader.getItem(`3.pdf`, MockExtensionContext);
assert.deepStrictEqual(downloadedItem1, getItem1);
assert.deepStrictEqual(downloadedItem2, getItem2);
assert.deepStrictEqual(downloadedItem3, getItem3);
});
test(`Overwrite existing folder`, async () => {
const fullDownloadFilePath = path.join(MockGlobalStoragePath, `file-downloader-downloads`, `file`);
await fs.promises.mkdir(fullDownloadFilePath, { recursive: true });
await assert.doesNotReject(fileDownloader.downloadFile(TestDownloadUri, `file`, MockExtensionContext));
});
test(`tryGetItem with no downloads`, async () => {
const getItemResult = await fileDownloader.tryGetItem(TestDownloadFilename, MockExtensionContext);
assert.equal(getItemResult, undefined);
});
test(`tryGetItem with one download`, async () => {
const downloadedUri: Uri = await fileDownloader.downloadFile(TestDownloadUri, TestDownloadFilename, MockExtensionContext);
const getItemResult: Uri | undefined = await fileDownloader.tryGetItem(TestDownloadFilename, MockExtensionContext);
assert(getItemResult != null);
assert.deepStrictEqual(downloadedUri, getItemResult);
await assert.doesNotReject(fs.promises.access(getItemResult.fsPath));
});
test(`List items with no downloads`, async () => {
const result: Uri[] = await fileDownloader.listDownloadedItems(MockExtensionContext);
assert.equal(result.length, 0);
});
test(`List items with one download`, async () => {
const downloadedItemUri = await fileDownloader.downloadFile(TestDownloadUri, TestDownloadFilename, MockExtensionContext);
const result: Uri[] = await fileDownloader.listDownloadedItems(MockExtensionContext);
assert.equal(result.length, 1);
assert.deepStrictEqual(downloadedItemUri, result[0]);
});
test(`List items with multiple downloads`, async () => {
const downloadedItem1 = await fileDownloader.downloadFile(TestDownloadUri, `1.pdf`, MockExtensionContext);
const downloadedItem2 = await fileDownloader.downloadFile(TestDownloadUri, `2.pdf`, MockExtensionContext);
const downloadedItem3 = await fileDownloader.downloadFile(TestDownloadUri, `3.pdf`, MockExtensionContext);
const result: Uri[] = await fileDownloader.listDownloadedItems(MockExtensionContext);
assert.equal(result.length, 3);
assert.deepStrictEqual(downloadedItem1.toString(), result[0].toString());
assert.deepStrictEqual(downloadedItem2.toString(), result[1].toString());
assert.deepStrictEqual(downloadedItem3.toString(), result[2].toString());
});
test(`Delete one item`, async () => {
const downloadedItemUri = await fileDownloader.downloadFile(TestDownloadUri, TestDownloadFilename, MockExtensionContext);
await assert.doesNotReject(fileDownloader.deleteItem(TestDownloadFilename, MockExtensionContext));
assert.deepStrictEqual(await fileDownloader.listDownloadedItems(MockExtensionContext), []);
});
test(`Delete one item with no downloads`, async () => {
await assert.doesNotReject(fileDownloader.deleteItem(TestDownloadFilename, MockExtensionContext));
});
test(`Delete one item out of multiple`, async () => {
const downloadedItem1 = await fileDownloader.downloadFile(TestDownloadUri, `1.pdf`, MockExtensionContext);
const downloadedItem2 = await fileDownloader.downloadFile(TestDownloadUri, `2.pdf`, MockExtensionContext);
const downloadedItem3 = await fileDownloader.downloadFile(TestDownloadUri, `3.pdf`, MockExtensionContext);
await fileDownloader.deleteItem(`1.pdf`, MockExtensionContext);
const result: Uri[] = await fileDownloader.listDownloadedItems(MockExtensionContext);
assert.equal(result.length, 2);
assert.deepStrictEqual(downloadedItem2.toString(), result[0].toString());
assert.deepStrictEqual(downloadedItem3.toString(), result[1].toString());
});
test(`Delete all items`, async () => {
const downloadedItem1 = await fileDownloader.downloadFile(TestDownloadUri, `1.pdf`, MockExtensionContext);
const downloadedItem2 = await fileDownloader.downloadFile(TestDownloadUri, `2.pdf`, MockExtensionContext);
const downloadedItem3 = await fileDownloader.downloadFile(TestDownloadUri, `3.pdf`, MockExtensionContext);
await fileDownloader.deleteAllItems(MockExtensionContext);
assert.deepStrictEqual(await fileDownloader.listDownloadedItems(MockExtensionContext), []);
});
test(`Delete all items with no downloads`, async () => {
await assert.doesNotReject(fileDownloader.deleteAllItems(MockExtensionContext));
});
test(`Download progress callback`, async () => {
let reportedTotalBytes;
let reportedDownloadedBytes;
const downloadProgressCallback = (downloadedBytes: number, totalBytes: number | undefined) => {
reportedDownloadedBytes = downloadedBytes;
reportedTotalBytes = totalBytes ?? 0;
assert(reportedTotalBytes === 0 || reportedDownloadedBytes <= reportedTotalBytes);
};
await fileDownloader.downloadFile(
TestDownloadUri,
TestDownloadFilename,
MockExtensionContext,
/* cancellationToken */ undefined,
downloadProgressCallback
);
assert(reportedTotalBytes);
assert(reportedDownloadedBytes);
assert.equal(reportedDownloadedBytes, reportedTotalBytes);
});
test(`Decompress zip file`, async () => {
const filePath = await fileDownloader.downloadFile(
Uri.parse(`https://github.com/microsoft/cascadia-code/releases/download/v2005.15/CascadiaCode_2005.15.zip`),
`cascadia2`,
MockExtensionContext,
/* cancellationToken */ undefined,
/* onDownloadProgressChange */ undefined,
{ shouldUnzip: true }
);
assert(filePath);
assert(await fs.promises.readdir(filePath.fsPath));
});
test(`Decompress non-zip file`, () => {
assert.rejects(
fileDownloader.downloadFile(
TestDownloadUri,
TestDownloadFilename,
MockExtensionContext,
/* cancellationToken */ undefined,
/* onDownloadProgressChange */ undefined,
{ shouldUnzip: true }
)
);
});
test(`Delete extracted folder`, async () => {
const downloadedItemUri = await fileDownloader.downloadFile(
Uri.parse(`https://github.com/microsoft/cascadia-code/releases/download/v2005.15/CascadiaCode_2005.15.zip`),
`cascadia`,
MockExtensionContext,
/* cancellationToken */ undefined,
/* onDownloadProgressChange */ undefined,
{ shouldUnzip: true }
);
await fileDownloader.deleteItem(`cascadia`, MockExtensionContext);
const items = await fileDownloader.listDownloadedItems(MockExtensionContext);
for (const item of items) {
assert(!item.fsPath.includes(`cascadia`));
}
});
test(`Uri with no scheme`, async () => {
await assert.rejects(
fileDownloader.downloadFile(
Uri.parse(`ipv4.download.thinkbroadband.com/5MB.zip`),
TestDownloadFilename,
MockExtensionContext
)
);
});
test(`Uri with improper scheme`, async () => {
await assert.rejects(
fileDownloader.downloadFile(
Uri.parse(`scheme://ipv4.download.thinkbroadband.com/5MB.zip`),
TestDownloadFilename,
MockExtensionContext
)
);
});
test(`Nonexistent website with correct Uri format`, async () => {
try {
await fileDownloader.downloadFile(
Uri.parse(`https://c0de104c1e68625629646025d15a6129a2b4b6496cd9ceacd7f7b5078e1849ba.com`),
TestDownloadFilename,
MockExtensionContext
);
assert.fail();
}
catch (error) {
if (error instanceof Error) {
assert(error.name.includes(`RetriesExceededError`));
}
else {
assert.fail(`unexpected error type`);
}
}
});
test(`404 status code`, async () => {
try {
await fileDownloader.downloadFile(
Uri.parse(`http://httpstat.us/404`),
TestDownloadFilename,
MockExtensionContext
);
assert.fail();
}
catch (error) {
if (error instanceof Error) {
if (`response` in error) {
// eslint-disable-next-line @typescript-eslint/dot-notation
assert(error[`response`][`status`] === 404);
}
assert.notEqual(error.name, `RetriesExceededError`);
}
else {
assert.fail(`unexpected error type`);
}
}
});
test(`Cancel download`, async () => {
const cancellationTokenSource = new CancellationTokenSource();
const cancellationToken = cancellationTokenSource.token;
const downloadPromise = fileDownloader.downloadFile(
Uri.parse(`http://ipv4.download.thinkbroadband.com/50MB.zip`),
`50MB.zip`,
MockExtensionContext,
cancellationToken
);
setTimeout(() => {
cancellationTokenSource.cancel();
}, 1000);
try {
await downloadPromise;
assert.fail();
}
catch (error) {
if (ErrorUtils.isErrnoException(error)) {
assert.equal(error.code, `ERR_STREAM_PREMATURE_CLOSE`);
}
else {
assert.fail(`unexpected error type`);
}
}
const downloadedItems = await fileDownloader.listDownloadedItems(MockExtensionContext);
for (const item of downloadedItems) {
assert(!item.fsPath.includes(`50MB.zip`));
}
});
});
Example #27
Source File: extension.ts From vscode-microprofile with Apache License 2.0 | 4 votes |
function connectToLS(context: ExtensionContext, api: JavaExtensionAPI) {
const microprofileContributions: MicroProfileContribution[] = collectMicroProfileJavaExtensions(extensions.all);
return requirements.resolveRequirements(api).then(requirements => {
const clientOptions: LanguageClientOptions = {
documentSelector: getDocumentSelector(microprofileContributions),
// wrap with key 'settings' so it can be handled same a DidChangeConfiguration
initializationOptions: {
settings: getVSCodeMicroProfileSettings(),
extendedClientCapabilities: {
commands: {
commandsKind: {
valueSet: [
CommandKind.COMMAND_CONFIGURATION_UPDATE,
CommandKind.COMMAND_OPEN_URI
]
}
},
completion: {
skipSendingJavaCompletionThroughLanguageServer: true
},
shouldLanguageServerExitOnShutdown: true
}
},
synchronize: {
// preferences starting with these will trigger didChangeConfiguration
configurationSection: ['microprofile', '[microprofile]']
},
middleware: {
workspace: {
didChangeConfiguration: () => {
languageClient.sendNotification(DidChangeConfigurationNotification.type, { settings: getVSCodeMicroProfileSettings() });
}
}
}
};
const serverOptions = prepareExecutable(requirements, getMicroProfileJarExtensions(microprofileContributions));
languageClient = new LanguageClient('microprofile.tools', 'Tools for MicroProfile', serverOptions, clientOptions);
context.subscriptions.push(languageClient.start());
if (extensions.onDidChange) {// Theia doesn't support this API yet
context.subscriptions.push(extensions.onDidChange(() => {
// if extensions that contribute mp java extensions change we need to reload the window
handleExtensionChange(extensions.all);
}));
}
return languageClient.onReady();
});
/**
* Returns the document selector.
*
* The returned document selector contains the microprofile-properties and java document selectors
* and all document selectors contained in `microProfileContributions`.
*
* @param microProfileContributions MicroProfile language server contributions from other VS Code extensions
*/
function getDocumentSelector(microProfileContributions: MicroProfileContribution[]): DocumentSelector {
let documentSelector: DocumentSelector = [
{ scheme: 'file', language: 'microprofile-properties' },
{ scheme: 'file', language: 'java' }
];
microProfileContributions.forEach((contribution: MicroProfileContribution) => {
documentSelector = documentSelector.concat(contribution.documentSelector);
});
return documentSelector;
}
/**
* Returns a json object with key 'microprofile' and a json object value that
* holds all microprofile settings.
*/
function getVSCodeMicroProfileSettings(): { microprofile: any } {
const defaultMicroProfileSettings = {};
const configMicroProfile = workspace.getConfiguration().get('microprofile');
const microprofileSettings = configMicroProfile ? configMicroProfile : defaultMicroProfileSettings;
return {
microprofile: microprofileSettings,
};
}
/**
* Returns an array of paths to MicroProfileLS extension jars within `microProfileContributions`
*
* @param microProfileContributions MicroProfile language server contributions from other VS Code extensions
*/
function getMicroProfileJarExtensions(microProfileContributions: MicroProfileContribution[]): string[] {
let jarPaths: string[] = [];
microProfileContributions.forEach((contribution: MicroProfileContribution) => {
if (contribution.jarExtensions && contribution.jarExtensions.length > 0) {
jarPaths = jarPaths.concat(contribution.jarExtensions);
}
});
return jarPaths;
}
}
Example #28
Source File: createTask.ts From sourcepawn-vscode with MIT License | 4 votes |
export function run(rootpath?: string) {
// Get configuration
let sm_home: string = Workspace.getConfiguration("sourcepawn").get(
"SourcemodHome"
);
if (!sm_home) {
window
.showWarningMessage(
"SourceMod API not found in the project. You should set SourceMod Home for tasks generation to work. Do you want to install it automatically?",
"Yes",
"No, open Settings"
)
.then((choice) => {
if (choice == "Yes") {
commands.executeCommand("sourcepawn-vscode.installSM");
} else if (choice === "No, open Settings") {
commands.executeCommand(
"workbench.action.openSettings",
"@ext:sarrus.sourcepawn-vscode"
);
}
});
}
let SpcompPath: string = Workspace.getConfiguration("sourcepawn").get(
"SpcompPath"
);
if (!SpcompPath) {
window
.showErrorMessage(
"SourceMod compiler not found in the project. You need to set SpcompPath for tasks generation to work.",
"Open Settings"
)
.then((choice) => {
if (choice === "Open Settings") {
commands.executeCommand(
"workbench.action.openSettings",
"@ext:sarrus.sourcepawn-vscode"
);
}
});
return 1;
}
// get workspace folder
let workspaceFolders = Workspace.workspaceFolders;
if (!workspaceFolders) {
window.showErrorMessage("No workspace are opened.");
return 2;
}
//Select the rootpath
if (rootpath === undefined) {
rootpath = workspaceFolders?.[0].uri.fsPath;
}
// create task folder if it doesn't exist
let taskFolderPath = join(rootpath, ".vscode");
if (!existsSync(taskFolderPath)) {
mkdirSync(taskFolderPath);
}
// Check if file already exists
let taskFilePath = join(rootpath, ".vscode/tasks.json");
if (existsSync(taskFilePath)) {
window.showErrorMessage("tasks.json file already exists.");
return 3;
}
let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
.extensionPath;
let tasksTemplatesPath: string = join(myExtDir, "templates/tasks.json");
copyFileSync(tasksTemplatesPath, taskFilePath);
SpcompPath = SpcompPath.replace(/\\/gm, "\\\\");
sm_home = sm_home.replace(/\\/gm, "\\\\");
// Replace placeholders
try {
let data = readFileSync(taskFilePath, "utf8");
let result = data.replace(/\${SpcompPath}/gm, SpcompPath);
result = result.replace(/\${include_path}/gm, sm_home);
writeFileSync(taskFilePath, result, "utf8");
} catch (err) {
console.log(err);
return 4;
}
return 0;
}