Skip to content

Add external API part 1 #2799

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

Merged
merged 5 commits into from
Jul 13, 2020
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
30 changes: 8 additions & 22 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,44 +9,30 @@
"args": [ "--extensionDevelopmentPath=${workspaceRoot}" ],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": ["${workspaceRoot}/out/src/**/*.js"],
"outFiles": ["${workspaceFolder}/out/src/**/*.js"],
"preLaunchTask": "BuildAll"
},
{
"name": "Launch Extension (Build client only)",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [ "--extensionDevelopmentPath=${workspaceRoot}" ],
"args": [ "--extensionDevelopmentPath=${workspaceFolder}" ],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": ["${workspaceRoot}/out/src/**/*.js"],
"outFiles": ["${workspaceFolder}/out/src/**/*.js"],
"preLaunchTask": "Build"
},
{
"name": "Launch Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": ["${workspaceRoot}/out/test/**/*.js"],
"preLaunchTask": "Build",
"skipFiles": [
"${workspaceFolder}/node_modules/**/*",
"${workspaceFolder}/lib/**/*",
"/private/var/folders/**/*",
"<node_internals>/**/*"
]
},
{
"name": "Attach",
"type": "node",
"request": "attach",
"address": "localhost",
"port": 5858,
"sourceMaps": false
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/testRunner.js" ],
"outFiles": ["${workspaceFolder}/out/**/*.js"],
"preLaunchTask": "Build"
}
]
}
1 change: 1 addition & 0 deletions .vsts-ci/templates/ci-general.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ steps:

# Using `prependpath` to update the PATH just for this build.
Write-Host "##vso[task.prependpath]$powerShellPath"
continueOnError: true
displayName: Install PowerShell Daily
- pwsh: '$PSVersionTable'
displayName: Display PowerShell version information
Expand Down
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,15 @@
"onCommand:PowerShell.RestartSession",
"onCommand:PowerShell.EnableISEMode",
"onCommand:PowerShell.DisableISEMode",
"onCommand:PowerShell.RegisterExternalExtension",
"onCommand:PowerShell.UnregisterExternalExtension",
"onCommand:PowerShell.GetPowerShellVersionDetails",
"onView:PowerShellCommands"
],
"dependencies": {
"node-fetch": "^2.6.0",
"semver": "^7.3.2",
"uuid": "^8.2.0",
"vscode-extension-telemetry": "~0.1.6",
"vscode-languageclient": "~6.1.3"
},
Expand All @@ -57,6 +61,7 @@
"@types/rewire": "~2.5.28",
"@types/semver": "~7.2.0",
"@types/sinon": "~9.0.4",
"@types/uuid": "^8.0.0",
"@types/vscode": "1.43.0",
"mocha": "~5.2.0",
"mocha-junit-reporter": "~2.0.0",
Expand Down Expand Up @@ -292,6 +297,21 @@
"light": "resources/light/MovePanelBottom.svg",
"dark": "resources/dark/MovePanelBottom.svg"
}
},
{
"command": "PowerShell.RegisterExternalExtension",
"title": "Register an external extension",
"category": "PowerShell"
},
{
"command": "PowerShell.UnregisterExternalExtension",
"title": "Unregister an external extension",
"category": "PowerShell"
},
{
"command": "PowerShell.GetPowerShellVersionDetails",
"title": "Get details about the PowerShell version that the PowerShell extension is using",
"category": "PowerShell"
}
],
"menus": {
Expand Down
153 changes: 153 additions & 0 deletions src/features/ExternalApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from "vscode";
import { v4 as uuidv4 } from 'uuid';
import { LanguageClient } from "vscode-languageclient";
import { IFeature } from "../feature";
import { Logger } from "../logging";
import { SessionManager } from "../session";

export interface IExternalPowerShellDetails {
exePath: string;
version: string;
displayName: string;
architecture: string;
}

export class ExternalApiFeature implements IFeature {
private commands: vscode.Disposable[];
private languageClient: LanguageClient;
private static readonly registeredExternalExtension: Map<string, IExternalExtension> = new Map<string, IExternalExtension>();

constructor(private sessionManager: SessionManager, private log: Logger) {
this.commands = [
/*
DESCRIPTION:
Registers your extension to allow usage of the external API. The returns
a session UUID that will need to be passed in to subsequent API calls.

USAGE:
vscode.commands.executeCommand(
"PowerShell.RegisterExternalExtension",
"ms-vscode.PesterTestExplorer" // the name of the extension using us
"v1"); // API Version.

RETURNS:
string session uuid
*/
vscode.commands.registerCommand("PowerShell.RegisterExternalExtension", (id: string, apiVersion: string = 'v1'): string =>
this.registerExternalExtension(id, apiVersion)),

/*
DESCRIPTION:
Unregisters a session that an extension has. This returns
true if it succeeds or throws if it fails.

USAGE:
vscode.commands.executeCommand(
"PowerShell.UnregisterExternalExtension",
"uuid"); // the uuid from above for tracking purposes

RETURNS:
true if it worked, otherwise throws an error.
*/
vscode.commands.registerCommand("PowerShell.UnregisterExternalExtension", (uuid: string = ""): boolean =>
this.unregisterExternalExtension(uuid)),

/*
DESCRIPTION:
This will fetch the version details of the PowerShell used to start
PowerShell Editor Services in the PowerShell extension.

USAGE:
vscode.commands.executeCommand(
"PowerShell.GetPowerShellVersionDetails",
"uuid"); // the uuid from above for tracking purposes

RETURNS:
An IPowerShellVersionDetails which consists of:
{
version: string;
displayVersion: string;
edition: string;
architecture: string;
}
*/
vscode.commands.registerCommand("PowerShell.GetPowerShellVersionDetails", (uuid: string = ""): Promise<IExternalPowerShellDetails> =>
this.getPowerShellVersionDetails(uuid)),
]
}

private registerExternalExtension(id: string, apiVersion: string = 'v1'): string {
this.log.writeDiagnostic(`Registering extension '${id}' for use with API version '${apiVersion}'.`);

for (const [_, externalExtension] of ExternalApiFeature.registeredExternalExtension) {
if (externalExtension.id === id) {
const message = `The extension '${id}' is already registered.`;
this.log.writeWarning(message);
throw new Error(message);
}
}

if (!vscode.extensions.all.some(ext => ext.id === id)) {
throw new Error(`No extension installed with id '${id}'. You must use a valid extension id.`);
}

// If we're in development mode, we allow these to be used for testing purposes.
if (!this.sessionManager.InDevelopmentMode && (id === "ms-vscode.PowerShell" || id === "ms-vscode.PowerShell-Preview")) {
throw new Error("You can't use the PowerShell extension's id in this registration.");
}

const uuid = uuidv4();
ExternalApiFeature.registeredExternalExtension.set(uuid, {
id,
apiVersion
});
return uuid;
}

private unregisterExternalExtension(uuid: string = ""): boolean {
this.log.writeDiagnostic(`Unregistering extension with session UUID: ${uuid}`);
if (!ExternalApiFeature.registeredExternalExtension.delete(uuid)) {
throw new Error(`No extension registered with session UUID: ${uuid}`);
}
return true;
}

private async getPowerShellVersionDetails(uuid: string = ""): Promise<IExternalPowerShellDetails> {
if (!ExternalApiFeature.registeredExternalExtension.has(uuid)) {
throw new Error(
"UUID provided was invalid, make sure you execute the 'PowerShell.GetPowerShellVersionDetails' command and pass in the UUID that it returns to subsequent command executions.");
}

// TODO: When we have more than one API version, make sure to include a check here.
const extension = ExternalApiFeature.registeredExternalExtension.get(uuid);
this.log.writeDiagnostic(`Extension '${extension.id}' used command 'PowerShell.GetPowerShellVersionDetails'.`);

await this.sessionManager.waitUntilStarted();
const versionDetails = this.sessionManager.getPowerShellVersionDetails();

return {
exePath: this.sessionManager.PowerShellExeDetails.exePath,
version: versionDetails.version,
displayName: this.sessionManager.PowerShellExeDetails.displayName, // comes from the Session Menu
architecture: versionDetails.architecture
};
}

public dispose() {
for (const command of this.commands) {
command.dispose();
}
}

public setLanguageClient(languageclient: LanguageClient) {
this.languageClient = languageclient;
}
}

interface IExternalExtension {
readonly id: string;
readonly apiVersion: string;
}
8 changes: 4 additions & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@ import { CodeActionsFeature } from "./features/CodeActions";
import { ConsoleFeature } from "./features/Console";
import { CustomViewsFeature } from "./features/CustomViews";
import { DebugSessionFeature } from "./features/DebugSession";
import { PickPSHostProcessFeature } from "./features/DebugSession";
import { PickRunspaceFeature } from "./features/DebugSession";
import { SpecifyScriptArgsFeature } from "./features/DebugSession";
import { ExamplesFeature } from "./features/Examples";
import { ExpandAliasFeature } from "./features/ExpandAlias";
import { ExtensionCommandsFeature } from "./features/ExtensionCommands";
import { ExternalApiFeature } from "./features/ExternalApi";
import { FindModuleFeature } from "./features/FindModule";
import { GenerateBugReportFeature } from "./features/GenerateBugReport";
import { GetCommandsFeature } from "./features/GetCommands";
Expand All @@ -27,14 +25,15 @@ import { ISECompatibilityFeature } from "./features/ISECompatibility";
import { NewFileOrProjectFeature } from "./features/NewFileOrProject";
import { OpenInISEFeature } from "./features/OpenInISE";
import { PesterTestsFeature } from "./features/PesterTests";
import { PickPSHostProcessFeature, PickRunspaceFeature } from "./features/DebugSession";
import { RemoteFilesFeature } from "./features/RemoteFiles";
import { RunCodeFeature } from "./features/RunCode";
import { ShowHelpFeature } from "./features/ShowHelp";
import { SpecifyScriptArgsFeature } from "./features/DebugSession";
import { Logger, LogLevel } from "./logging";
import { SessionManager } from "./session";
import Settings = require("./settings");
import { PowerShellLanguageId } from "./utils";
import utils = require("./utils");

// The most reliable way to get the name and version of the current extension.
// tslint:disable-next-line: no-var-requires
Expand Down Expand Up @@ -157,6 +156,7 @@ export function activate(context: vscode.ExtensionContext): void {
new HelpCompletionFeature(logger),
new CustomViewsFeature(),
new PickRunspaceFeature(),
new ExternalApiFeature(sessionManager, logger)
];

sessionManager.setExtensionFeatures(extensionFeatures);
Expand Down
6 changes: 1 addition & 5 deletions src/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,6 @@ export class PowerShellProcess {
return true;
}

private sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}

private async waitForSessionFile(): Promise<utils.IEditorServicesSessionDetails> {
// Determine how many tries by dividing by 2000 thus checking every 2 seconds.
const numOfTries = this.sessionSettings.developer.waitForSessionFileTimeoutSeconds / 2;
Expand All @@ -203,7 +199,7 @@ export class PowerShellProcess {
}

// Wait a bit and try again
await this.sleep(2000);
await utils.sleep(2000);
}

const err = "Timed out waiting for session file to appear.";
Expand Down
14 changes: 11 additions & 3 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,15 @@ export class SessionManager implements Middleware {
private sessionSettings: Settings.ISettings = undefined;
private sessionDetails: utils.IEditorServicesSessionDetails;
private bundledModulesPath: string;
private started: boolean = false;

// Initialized by the start() method, since this requires settings
private powershellExeFinder: PowerShellExeFinder;

// When in development mode, VS Code's session ID is a fake
// value of "someValue.machineId". Use that to detect dev
// mode for now until Microsoft/vscode#10272 gets implemented.
private readonly inDevelopmentMode =
public readonly InDevelopmentMode =
vscode.env.sessionId === "someValue.sessionId";

constructor(
Expand Down Expand Up @@ -167,7 +168,7 @@ export class SessionManager implements Middleware {

this.bundledModulesPath = path.resolve(__dirname, this.sessionSettings.bundledModulesPath);

if (this.inDevelopmentMode) {
if (this.InDevelopmentMode) {
const devBundledModulesPath =
path.resolve(
__dirname,
Expand Down Expand Up @@ -274,6 +275,12 @@ export class SessionManager implements Middleware {
return this.debugSessionProcess;
}

public async waitUntilStarted(): Promise<void> {
while(!this.started) {
await utils.sleep(300);
}
}

// ----- LanguageClient middleware methods -----

public resolveCodeLens(
Expand Down Expand Up @@ -549,8 +556,9 @@ export class SessionManager implements Middleware {
.then(
async (versionDetails) => {
this.versionDetails = versionDetails;
this.started = true;

if (!this.inDevelopmentMode) {
if (!this.InDevelopmentMode) {
this.telemetryReporter.sendTelemetryEvent("powershellVersionCheck",
{ powershellVersion: versionDetails.version });
}
Expand Down
Loading