Skip to content
Draft
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
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,28 @@ import type { ExtendedParams } from '../ExtendedParams';
import { getCurrentContext } from '../utils/ActionContext';
import { isMap, isPair, isScalar } from 'yaml';
import { yamlRangeToLspRange } from '../utils/yamlRangeToLspRange';
import { isDocumentInWorkspace } from '../utils/isDocumentInWorkspace';

export class ServiceStartupCodeLensProvider extends ProviderBase<CodeLensParams & ExtendedParams, CodeLens[] | undefined, never, never> {
public on(params: CodeLensParams & ExtendedParams, token: CancellationToken): Promise<CodeLens[] | undefined> {
public async on(params: CodeLensParams & ExtendedParams, token: CancellationToken): Promise<CodeLens[] | undefined> {
const ctx = getCurrentContext();
ctx.telemetry.properties.isActivationEvent = 'true'; // This happens automatically so we'll treat it as isActivationEvent === true

const results: CodeLens[] = [];

if (!params.document.yamlDocument.value.has('services')) {
return Promise.resolve(undefined);
return undefined;
}

if (token.isCancellationRequested) {
return undefined;
}

// The code lens commands (compose up, etc.) require the document to be within an open workspace folder.
// If it is not, running them results in an error, so the code lenses should not be shown.
// See https://github.com/microsoft/vscode-containers/issues/535
if (!await isDocumentInWorkspace(ctx, params.document.uri)) {
return undefined;
Comment on lines +29 to +33

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in af77fe0 by reordering the early exits to check for missing services first and cancellation before awaiting the workspace-folder check.

}

// First add the run-all from the main "services" node
Expand Down Expand Up @@ -47,7 +59,7 @@ export class ServiceStartupCodeLensProvider extends ProviderBase<CodeLensParams

// Check for cancellation
if (token.isCancellationRequested) {
return Promise.resolve(undefined);
return undefined;
}

// Then add the run-single for each service
Expand All @@ -56,7 +68,7 @@ export class ServiceStartupCodeLensProvider extends ProviderBase<CodeLensParams
for (const service of serviceMap.items) {
// Within each loop we'll check for cancellation (though this is expected to be very fast)
if (token.isCancellationRequested) {
return Promise.resolve(undefined);
return undefined;
}

if (isScalar(service.key) && typeof service.key.value === 'string' && service.key.range) {
Expand All @@ -75,6 +87,6 @@ export class ServiceStartupCodeLensProvider extends ProviderBase<CodeLensParams
}
}

return Promise.resolve(results);
return results;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*!--------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import type { WorkspaceFolder } from 'vscode-languageserver';
import type { DocumentUri } from 'vscode-languageserver-textdocument';
import type { ActionContext } from './ActionContext';

/**
* Determines whether a document is located within one of the workspace folders open in the client.
* If the client does not support the `workspace/workspaceFolders` request, the document is
* optimistically treated as being within the workspace (so behavior is unchanged for such clients).
* @param ctx The current action context (used to access client capabilities and the connection)
* @param documentUri The URI of the document
* @returns True if the document is within a workspace folder (or the capability is unsupported), false otherwise
*/
export async function isDocumentInWorkspace(ctx: ActionContext, documentUri: DocumentUri): Promise<boolean> {
// If the client doesn't support workspace folders, we can't verify, so optimistically show code lenses
if (!ctx.clientCapabilities?.workspace?.workspaceFolders) {
return true;
}

const folders = await ctx.connection.workspace.getWorkspaceFolders();
return isDocumentInWorkspaceFolders(documentUri, folders);
}

/**
* Determines whether a document is located within one of the given workspace folders.
* @param documentUri The URI of the document
* @param folders The workspace folders reported by the client (may be `null`/`undefined` if none are open)
* @returns True if the document is within one of the workspace folders, false otherwise
*/
export function isDocumentInWorkspaceFolders(documentUri: DocumentUri, folders: WorkspaceFolder[] | null | undefined): boolean {
if (!folders?.length) {
return false;
}

return folders.some(folder => uriIsWithinFolder(documentUri, folder.uri));
}

function uriIsWithinFolder(documentUri: string, folderUri: string): boolean {
// Ensure the folder URI ends with a slash so that a folder like `file:///foo` does not match `file:///foobar`
const normalizedFolderUri = folderUri.endsWith('/') ? folderUri : `${folderUri}/`;
return documentUri === folderUri || documentUri.startsWith(normalizedFolderUri);
}
11 changes: 10 additions & 1 deletion packages/compose-language-service/src/test/TestConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import { PassThrough } from 'stream';
import { type Connection, DidOpenTextDocumentNotification, type DidOpenTextDocumentParams, type Disposable, type InitializeParams, TextDocumentItem } from 'vscode-languageserver';
import { type Connection, DidOpenTextDocumentNotification, type DidOpenTextDocumentParams, type Disposable, type InitializeParams, TextDocumentItem, type WorkspaceFolder, WorkspaceFoldersRequest } from 'vscode-languageserver';
import type { DocumentUri } from 'vscode-languageserver-textdocument';
import { createConnection } from 'vscode-languageserver/node';
import { Document } from 'yaml';
Expand All @@ -23,6 +23,12 @@ export class TestConnection implements Disposable {
public readonly server: Connection;
public readonly client: Connection;
public readonly languageService: ComposeLanguageService;

/**
* The workspace folders that the (mock) client will report when the server issues a
* `workspace/workspaceFolders` request. Assign to this to simulate open workspace folders.
*/
public workspaceFolders: WorkspaceFolder[] | null = null;
private counter = 0;

public constructor(public readonly initParams: InitializeParams = DefaultInitializeParams) {
Expand All @@ -34,6 +40,9 @@ export class TestConnection implements Disposable {

this.languageService = new ComposeLanguageService(this.server, initParams);

// Respond to the server's workspace folder requests with the configured folders
this.client.onRequest(WorkspaceFoldersRequest.type, () => this.workspaceFolders);

this.server.listen();
this.client.listen();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,55 @@ describe('ServiceStartupCodeLensProvider', () => {
});
});

describe('Workspace folder scenarios', () => {
let workspaceAwareConnection: TestConnection;

before('Prepare a workspace-folder-aware language server for testing', () => {
workspaceAwareConnection = new TestConnection({
capabilities: {
workspace: {
workspaceFolders: true,
},
},
processId: 1,
rootUri: null,
workspaceFolders: null,
});
});

it('Should provide code lenses when the document is within a workspace folder', async () => {
const uri = workspaceAwareConnection.sendObjectAsYamlDocument({ services: {} });
workspaceAwareConnection.workspaceFolders = [{ uri: 'file:///', name: 'root' }];

await requestServiceStartupCodeLensesAndCompare(workspaceAwareConnection, uri, [
{
range: Range.create(0, 0, 0, 8),
command: {
command: 'vscode-containers.compose.up'
}
},
]);
});

it('Should NOT provide code lenses when the document is outside all workspace folders', async () => {
const uri = workspaceAwareConnection.sendObjectAsYamlDocument({ services: {} });
workspaceAwareConnection.workspaceFolders = [{ uri: 'file:///some/other/folder', name: 'other' }];

await requestServiceStartupCodeLensesAndCompare(workspaceAwareConnection, uri, undefined);
});

it('Should NOT provide code lenses when there are no open workspace folders', async () => {
const uri = workspaceAwareConnection.sendObjectAsYamlDocument({ services: {} });
workspaceAwareConnection.workspaceFolders = null;

await requestServiceStartupCodeLensesAndCompare(workspaceAwareConnection, uri, undefined);
});

after('Cleanup', () => {
workspaceAwareConnection.dispose();
});
});

after('Cleanup', () => {
testConnection.dispose();
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*!--------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import type { WorkspaceFolder } from 'vscode-languageserver';
import { isDocumentInWorkspaceFolders } from '../../service/utils/isDocumentInWorkspace';

function folder(uri: string): WorkspaceFolder {
return { uri, name: uri };
}

describe('(Unit) isDocumentInWorkspaceFolders', () => {
describe('Common scenarios', () => {
it('Should return true when the document is directly within a workspace folder', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', [folder('file:///workspace')]).should.be.true;
});

it('Should return true when the document is nested within a workspace folder', () => {
isDocumentInWorkspaceFolders('file:///workspace/sub/dir/compose.yaml', [folder('file:///workspace')]).should.be.true;
});

it('Should return true when the folder URI has a trailing slash', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', [folder('file:///workspace/')]).should.be.true;
});

it('Should return true when the document is within one of several workspace folders', () => {
isDocumentInWorkspaceFolders('file:///second/compose.yaml', [folder('file:///first'), folder('file:///second')]).should.be.true;
});
});

describe('Negative scenarios', () => {
it('Should return false when the document is outside all workspace folders', () => {
isDocumentInWorkspaceFolders('file:///elsewhere/compose.yaml', [folder('file:///workspace')]).should.be.false;
});

it('Should return false for a sibling folder with a matching prefix', () => {
// `file:///workspace` should not match `file:///workspace-other`
isDocumentInWorkspaceFolders('file:///workspace-other/compose.yaml', [folder('file:///workspace')]).should.be.false;
});

it('Should return false when there are no workspace folders', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', []).should.be.false;
});

it('Should return false when the folders are null', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', null).should.be.false;
});

it('Should return false when the folders are undefined', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', undefined).should.be.false;
});
});
});