[html] clean up request service: add CustomDataRequestService #135459

This commit is contained in:
Martin Aeschlimann
2021-11-29 11:25:04 +01:00
parent 414c15079b
commit 3d8b5674c7
19 changed files with 95 additions and 178 deletions

View File

@@ -4,10 +4,11 @@
*--------------------------------------------------------------------------------------------*/
import { workspace, extensions, Uri, EventEmitter, Disposable } from 'vscode';
import { resolvePath, joinPath } from './requests';
import { Runtime } from './htmlClient';
import { Utils } from 'vscode-uri';
export function getCustomDataSource(toDispose: Disposable[]) {
export function getCustomDataSource(runtime: Runtime, toDispose: Disposable[]) {
let pathsInWorkspace = getCustomDataPathsInAllWorkspaces();
let pathsInExtensions = getCustomDataPathsFromAllExtensions();
@@ -40,6 +41,17 @@ export function getCustomDataSource(toDispose: Disposable[]) {
},
get onDidChange() {
return onChange.event;
},
getContent(uriString: string): Thenable<string> {
const uri = Uri.parse(uriString);
if (pathsInExtensions.has(uriString)) {
return workspace.fs.readFile(uri).then(buffer => {
return new runtime.TextDecoder().decode(buffer);
});
}
return workspace.openTextDocument(uri).then(doc => {
return doc.getText();
});
}
};
}
@@ -64,7 +76,7 @@ function getCustomDataPathsInAllWorkspaces(): Set<string> {
if (typeof uriOrPath === 'string') {
if (!isURI(uriOrPath)) {
// path in the workspace
dataPaths.add(resolvePath(rootFolder, uriOrPath).toString());
dataPaths.add(Utils.resolvePath(rootFolder, uriOrPath).toString());
} else {
// external uri
dataPaths.add(uriOrPath);
@@ -100,7 +112,7 @@ function getCustomDataPathsFromAllExtensions(): Set<string> {
for (const uriOrPath of customData) {
if (!isURI(uriOrPath)) {
// relative path in an extension
dataPaths.add(joinPath(extension.extensionUri, uriOrPath).toString());
dataPaths.add(Uri.joinPath(extension.extensionUri, uriOrPath).toString());
} else {
// external uri
dataPaths.add(uriOrPath);

View File

@@ -16,13 +16,17 @@ import {
DocumentRangeFormattingRequest, ProvideCompletionItemsSignature, TextDocumentIdentifier, RequestType0, Range as LspRange, NotificationType, CommonLanguageClient
} from 'vscode-languageclient';
import { activateTagClosing } from './tagClosing';
import { RequestService, serveFileSystemRequests } from './requests';
import { FileSystemProvider, serveFileSystemRequests } from './requests';
import { getCustomDataSource } from './customData';
namespace CustomDataChangedNotification {
export const type: NotificationType<string[]> = new NotificationType('html/customDataChanged');
}
namespace CustomDataContent {
export const type: RequestType<string, string, any> = new RequestType('html/customDataContent');
}
namespace TagCloseRequest {
export const type: RequestType<TextDocumentPositionParams, string, any> = new RequestType('html/tag');
}
@@ -56,7 +60,7 @@ export type LanguageClientConstructor = (name: string, description: string, clie
export interface Runtime {
TextDecoder: { new(encoding?: string): { decode(buffer: ArrayBuffer): string; } };
fs?: RequestService;
fileFs?: FileSystemProvider;
telemetry?: TelemetryReporter;
readonly timer: {
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable;
@@ -73,8 +77,6 @@ export function startClient(context: ExtensionContext, newLanguageClient: Langua
let rangeFormatting: Disposable | undefined = undefined;
const customDataSource = getCustomDataSource(context.subscriptions);
// Options to control the language client
let clientOptions: LanguageClientOptions = {
documentSelector,
@@ -122,10 +124,14 @@ export function startClient(context: ExtensionContext, newLanguageClient: Langua
toDispose.push(serveFileSystemRequests(client, runtime));
const customDataSource = getCustomDataSource(runtime, context.subscriptions);
client.sendNotification(CustomDataChangedNotification.type, customDataSource.uris);
customDataSource.onDidChange(() => {
client.sendNotification(CustomDataChangedNotification.type, customDataSource.uris);
});
client.onRequest(CustomDataContent.type, customDataSource.getContent);
let tagRequestor = (document: TextDocument, position: Position) => {
let param = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position);

View File

@@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { getNodeFSRequestService } from './nodeFs';
import { getNodeFileFS } from './nodeFs';
import { Disposable, ExtensionContext } from 'vscode';
import { startClient, LanguageClientConstructor } from '../htmlClient';
import { ServerOptions, TransportKind, LanguageClientOptions, LanguageClient } from 'vscode-languageclient/node';
@@ -44,7 +44,7 @@ export function activate(context: ExtensionContext) {
}
};
startClient(context, newLanguageClient, { fs: getNodeFSRequestService(), TextDecoder, telemetry, timer });
startClient(context, newLanguageClient, { fileFs: getNodeFileFS(), TextDecoder, telemetry, timer });
}
interface IPackageInfo {

View File

@@ -5,28 +5,15 @@
import * as fs from 'fs';
import { Uri } from 'vscode';
import { getScheme, RequestService, FileType } from '../requests';
import { FileSystemProvider, FileType } from '../requests';
export function getNodeFSRequestService(): RequestService {
export function getNodeFileFS(): FileSystemProvider {
function ensureFileUri(location: string) {
if (getScheme(location) !== 'file') {
if (!location.startsWith('file:')) {
throw new Error('fileRequestService can only handle file URLs');
}
}
return {
getContent(location: string, encoding?: string) {
ensureFileUri(location);
return new Promise((c, e) => {
const uri = Uri.parse(location);
fs.readFile(uri.fsPath, encoding, (err, buf) => {
if (err) {
return e(err);
}
c(buf.toString());
});
});
},
stat(location: string) {
ensureFileUri(location);
return new Promise((c, e) => {

View File

@@ -7,9 +7,6 @@ import { Uri, workspace, Disposable } from 'vscode';
import { RequestType, CommonLanguageClient } from 'vscode-languageclient';
import { Runtime } from './htmlClient';
export namespace FsContentRequest {
export const type: RequestType<{ uri: string; encoding?: string; }, string, any> = new RequestType('fs/content');
}
export namespace FsStatRequest {
export const type: RequestType<string, FileStat, any> = new RequestType('fs/stat');
}
@@ -20,26 +17,17 @@ export namespace FsReadDirRequest {
export function serveFileSystemRequests(client: CommonLanguageClient, runtime: Runtime): Disposable {
const disposables = [];
disposables.push(client.onRequest(FsContentRequest.type, (param: { uri: string; encoding?: string; }) => {
const uri = Uri.parse(param.uri);
if (uri.scheme === 'file' && runtime.fs) {
return runtime.fs.getContent(param.uri);
}
return workspace.fs.readFile(uri).then(buffer => {
return new runtime.TextDecoder(param.encoding).decode(buffer);
});
}));
disposables.push(client.onRequest(FsReadDirRequest.type, (uriString: string) => {
const uri = Uri.parse(uriString);
if (uri.scheme === 'file' && runtime.fs) {
return runtime.fs.readDirectory(uriString);
if (uri.scheme === 'file' && runtime.fileFs) {
return runtime.fileFs.readDirectory(uriString);
}
return workspace.fs.readDirectory(uri);
}));
disposables.push(client.onRequest(FsStatRequest.type, (uriString: string) => {
const uri = Uri.parse(uriString);
if (uri.scheme === 'file' && runtime.fs) {
return runtime.fs.stat(uriString);
if (uri.scheme === 'file' && runtime.fileFs) {
return runtime.fileFs.stat(uriString);
}
return workspace.fs.stat(uri);
}));
@@ -84,67 +72,7 @@ export interface FileStat {
size: number;
}
export interface RequestService {
getContent(uri: string, encoding?: string): Promise<string>;
export interface FileSystemProvider {
stat(uri: string): Promise<FileStat>;
readDirectory(uri: string): Promise<[string, FileType][]>;
}
export function getScheme(uri: string) {
return uri.substr(0, uri.indexOf(':'));
}
export function dirname(uri: string) {
const lastIndexOfSlash = uri.lastIndexOf('/');
return lastIndexOfSlash !== -1 ? uri.substr(0, lastIndexOfSlash) : '';
}
export function basename(uri: string) {
const lastIndexOfSlash = uri.lastIndexOf('/');
return uri.substr(lastIndexOfSlash + 1);
}
const Slash = '/'.charCodeAt(0);
const Dot = '.'.charCodeAt(0);
export function isAbsolutePath(path: string) {
return path.charCodeAt(0) === Slash;
}
export function resolvePath(uri: Uri, path: string): Uri {
if (isAbsolutePath(path)) {
return uri.with({ path: normalizePath(path.split('/')) });
}
return joinPath(uri, path);
}
export function normalizePath(parts: string[]): string {
const newParts: string[] = [];
for (const part of parts) {
if (part.length === 0 || part.length === 1 && part.charCodeAt(0) === Dot) {
// ignore
} else if (part.length === 2 && part.charCodeAt(0) === Dot && part.charCodeAt(1) === Dot) {
newParts.pop();
} else {
newParts.push(part);
}
}
if (parts.length > 1 && parts[parts.length - 1].length === 0) {
newParts.push('');
}
let res = newParts.join('/');
if (parts[0].length === 0) {
res = '/' + res;
}
return res;
}
export function joinPath(uri: Uri, ...paths: string[]): Uri {
const parts = uri.path.split('/');
for (let path of paths) {
parts.push(...path.split('/'));
}
return uri.with({ path: normalizePath(parts) });
}