Skip to content
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
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 thread
bwateratmsft marked this conversation as resolved.
}

// 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,98 @@
/*!--------------------------------------------------------------------------------------------
* 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';

const useCaseInsensitivePathComparison = process.platform === 'darwin' || process.platform === 'win32';

/**
* 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
Comment thread
bwateratmsft marked this conversation as resolved.
* @internal Exported only for tests
*/
export function isDocumentInWorkspaceFolders(documentUri: DocumentUri, folders: WorkspaceFolder[] | null | undefined): boolean {
if (!folders?.length) {
return false;
}

const document = parseUri(documentUri);
if (!document) {
return false;
}

return folders.some(folder => {
const parsedFolder = parseUri(folder.uri);
if (!parsedFolder) {
return false;
}

// The scheme and authority must match exactly, so that (for example) a `file://` document is
// never considered to be within a `vscode-vfs://` folder, or a folder on a different host
if (parsedFolder.scheme !== document.scheme || parsedFolder.authority !== document.authority) {
return false;
}

// The document is within the folder if the folder's path segments are a prefix of the document's.
// Comparing whole segments (rather than raw strings) means a folder at `/foo` is correctly seen as
// containing `/foo/compose.yaml`, but not the sibling `/foobar/compose.yaml`.
return parsedFolder.segments.every((segment, i) => {
const documentSegment = document.segments[i];

if (useCaseInsensitivePathComparison) {
return segment.toLowerCase() === documentSegment?.toLowerCase();
}

return segment === documentSegment;
});
});
}

/**
* Parses a URI into the pieces needed to compare it against another URI. LSP models URIs as plain
* strings (`DocumentUri` is just a `string` alias) and offers no URI type of its own, so the
* platform's WHATWG `URL` is used: it separates the scheme and authority from the path, and
* normalizes dot segments (e.g. `/a/b/../c` becomes `/a/c`).
* @param uri The URI to parse
* @returns The parsed pieces, or `undefined` if the URI is malformed
*/
function parseUri(uri: string): { scheme: string, authority: string, segments: string[] } | undefined {
try {
const url = new URL(uri);

return {
scheme: url.protocol,
authority: url.host,
// Decoding is done per-segment (after splitting) so that an encoded separator within a
// segment can never be mistaken for a real one. This also makes comparison insensitive
// to differences in percent-encoding between the document and folder URIs.
segments: url.pathname.split('/').filter(segment => !!segment).map(decodeURIComponent),
};
} catch {
// Malformed URI, or malformed percent-encoding within it
return undefined;
}
}
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,98 @@
/*!--------------------------------------------------------------------------------------------
* 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 };
}

const itOnCaseInsensitivePlatforms = process.platform === 'darwin' || process.platform === 'win32' ? it : it.skip;
const itOnCaseSensitivePlatforms = process.platform === 'darwin' || process.platform === 'win32' ? it.skip : it;

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;
});

it('Should return true when the document and folder differ in percent-encoding', () => {
// `%3A` and `%3a` encode the same character, as do `:` and `%3A` in a path
isDocumentInWorkspaceFolders('file:///c%3a/workspace/compose.yaml', [folder('file:///c%3A/workspace')]).should.be.true;
});

it('Should return true when the document URI contains dot segments resolving into the folder', () => {
isDocumentInWorkspaceFolders('file:///workspace/sub/../compose.yaml', [folder('file:///workspace')]).should.be.true;
});

itOnCaseInsensitivePlatforms('Should compare path segments case-insensitively on Mac and Windows', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', [folder('file:///Workspace')]).should.be.true;
});

itOnCaseSensitivePlatforms('Should compare path segments case-sensitively on Linux', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', [folder('file:///Workspace')]).should.be.false;
});

it('Should return true for any document when the workspace folder is the root', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', [folder('file:///')]).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 the document URI contains dot segments resolving out of the folder', () => {
isDocumentInWorkspaceFolders('file:///workspace/../elsewhere/compose.yaml', [folder('file:///workspace')]).should.be.false;
});

it('Should return false when the schemes differ', () => {
isDocumentInWorkspaceFolders('vscode-vfs:///workspace/compose.yaml', [folder('file:///workspace')]).should.be.false;
});

it('Should return false when the authorities differ', () => {
isDocumentInWorkspaceFolders('vscode-vfs://other/workspace/compose.yaml', [folder('vscode-vfs://github/workspace')]).should.be.false;
});

it('Should return false when the document URI is malformed', () => {
isDocumentInWorkspaceFolders('not a uri', [folder('file:///workspace')]).should.be.false;
});

it('Should return false when a workspace folder URI is malformed', () => {
isDocumentInWorkspaceFolders('file:///workspace/compose.yaml', [folder('not a uri')]).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;
});
});
});
Loading