Skip to content
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

Deno Formater #10

Merged
merged 2 commits into from
May 12, 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
2 changes: 2 additions & 0 deletions client/src/commands.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

import * as vscode from "vscode";
import * as lsp from "vscode-languageclient";

Expand Down
2 changes: 2 additions & 0 deletions client/src/deno.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

import * as path from "path";
import execa from "execa";
import which from "which";
Expand Down
2 changes: 2 additions & 0 deletions client/src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

import * as vscode from "vscode";
import * as nls from "vscode-nls";
import * as lsp from "vscode-languageclient";
Expand Down
2 changes: 2 additions & 0 deletions client/src/output.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

import { OutputChannel, window as Window } from "vscode";

const outputChannel: OutputChannel = Window.createOutputChannel("Deno");
Expand Down
2 changes: 2 additions & 0 deletions client/src/protocol.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

import { NotificationType0 } from "vscode-languageclient";

export const projectLoadingNotification = {
Expand Down
2 changes: 2 additions & 0 deletions client/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

import * as fs from "fs";
import * as path from "path";
import execa from "execa";
Expand Down
2 changes: 2 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"execa": "^4.0.1",
"typescript": "3.8.3",
"vscode-languageserver": "6.1.1",
"vscode-languageserver-textdocument": "^1.0.1",
"vscode-uri": "2.1.1"
}
}
63 changes: 54 additions & 9 deletions server/src/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,14 @@

import ts from "typescript/lib/tsserverlibrary";
import * as lsp from "vscode-languageserver";
import { TextDocument } from "vscode-languageserver-textdocument";

import { Logger } from "./logger";
import { ProjectService } from "./project_service";
import { projectLoadingNotification } from "./protocol";
import { ServerHost } from "./server_host";

import {
filePathToUri,
lspPositionToTsPosition,
tsTextSpanToLspRange,
uriToFilePath,
} from "./utils";
import { isDenoProject } from "./utils/deno";
import * as deno from "./utils/deno";
import { uriToFilePath } from "./utils";

export interface ConnectionOptions {
host: ServerHost;
Expand All @@ -42,12 +37,14 @@ const EMPTY_RANGE = lsp.Range.create(0, 0, 0, 0);
export class Connection {
private readonly connection: lsp.IConnection;
private readonly projectService: ProjectService;
private readonly documents: lsp.TextDocuments<TextDocument>;
private diagnosticsTimeout: NodeJS.Timeout | null = null;
private isProjectLoading = false;

constructor(options: ConnectionOptions) {
// Create a connection for the server. The connection uses Node's IPC as a transport.
this.connection = lsp.createConnection();
this.documents = new lsp.TextDocuments(TextDocument);
this.addProtocolHandlers(this.connection);
this.projectService = new ProjectService({
host: options.host,
Expand All @@ -70,9 +67,12 @@ export class Connection {
}

private addProtocolHandlers(conn: lsp.IConnection) {
conn.onInitialize((p) => this.onInitialize(p));
conn.onDidOpenTextDocument((p) => this.onDidOpenTextDocument(p));
conn.onDidCloseTextDocument((p) => this.onDidCloseTextDocument(p));
conn.onDidSaveTextDocument((p) => this.onDidSaveTextDocument(p));
conn.onDocumentFormatting((p) => this.onDocumentFormatting(p));
conn.onDocumentRangeFormatting((p) => this.onDocumentRangeFormatting(p));
}

/**
Expand Down Expand Up @@ -106,6 +106,16 @@ export class Connection {
}
}

private onInitialize(params: lsp.InitializeParams): lsp.InitializeResult {
return {
capabilities: {
documentFormattingProvider: true,
documentRangeFormattingProvider: true,
textDocumentSync: lsp.TextDocumentSyncKind.Full,
},
};
}

private onDidOpenTextDocument(params: lsp.DidOpenTextDocumentParams) {
const { uri, languageId, text } = params.textDocument;
this.connection.console.log(`open ${uri}`);
Expand Down Expand Up @@ -177,6 +187,40 @@ export class Connection {
}
}

private async onDocumentFormatting(params: lsp.DocumentFormattingParams) {
const { textDocument } = params;
const doc = this.documents.get(textDocument.uri);
if (!doc) {
return;
}

const text = doc.getText();
const formatted = await deno.format(text);

const start = doc.positionAt(0);
const end = doc.positionAt(text.length);
const range = lsp.Range.create(start, end);

return [lsp.TextEdit.replace(range, formatted)];
}

private async onDocumentRangeFormatting(
params: lsp.DocumentRangeFormattingParams,
) {
const { range, textDocument } = params;
const doc = this.documents.get(textDocument.uri);
if (!doc) {
return;
}

const text = doc.getText(range);
const formatted = await deno.format(text);

// why trim it?
// Because we are just formatting some of them, we don't need to keep the trailing \n
return [lsp.TextEdit.replace(range, formatted.trim())];
}

/**
* Show an error message.
*
Expand Down Expand Up @@ -217,6 +261,7 @@ export class Connection {
* Start listening on the input stream for messages to process.
*/
listen() {
this.documents.listen(this.connection);
this.connection.listen();
}

Expand All @@ -239,7 +284,7 @@ export class Connection {
return;
}

if (!isDenoProject(project, DENO_MOD)) {
if (!deno.isDenoProject(project, DENO_MOD)) {
project.disableLanguageService();
const msg =
`Disabling language service for ${projectName} because it is not an Deno project ` +
Expand Down
30 changes: 29 additions & 1 deletion server/src/project_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,41 @@ export class ProjectService {
options.logger.info("ProjectService");
this.tsProjSvc = new ts.server.ProjectService(options);

this.tsProjSvc.setHostConfiguration({
hostInfo: "Deno Service",
formatOptions: this.tsProjSvc.getHostFormatCodeOptions(),
preferences: this.tsProjSvc.getHostPreferences(),
extraFileExtensions: [
{
extension: ".js",
isMixedContent: false,
scriptKind: ts.ScriptKind.JS,
},
{
extension: ".jsx",
isMixedContent: false,
scriptKind: ts.ScriptKind.JSX,
},
{
extension: ".ts",
isMixedContent: false,
scriptKind: ts.ScriptKind.TS,
},
{
extension: ".tsx",
isMixedContent: false,
scriptKind: ts.ScriptKind.TSX,
},
],
});

this.tsProjSvc.configurePlugin({
pluginName: "typescript-deno-plugin",
configuration: {},
});

const plugins = this.tsProjSvc.globalPlugins;
options.logger.info(plugins.join(", "));
options.logger.info("enable plugins: " + plugins.join(", "));
}

/**
Expand Down
2 changes: 2 additions & 0 deletions server/src/protocol.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

import { NotificationType0 } from "vscode-languageserver";

export const projectLoadingNotification = {
Expand Down
2 changes: 2 additions & 0 deletions server/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

import ts from "typescript/lib/tsserverlibrary";
import denoPkg from "typescript-deno-plugin/package.json";

Expand Down
2 changes: 2 additions & 0 deletions server/src/utils/args.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.

function parseString(args: string[], argName: string): string | undefined {
const index = args.indexOf(argName);
if (index < 0 || index === args.length - 1) {
Expand Down
49 changes: 49 additions & 0 deletions server/src/utils/deno.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
// Copyright 2019-2020 the Deno authors. All rights reserved. MIT license.
// Copyright axetroy(铁手). All rights reserved. MIT license.

import { Readable } from "stream";
import execa from "execa";

/**
* Return true if the specified `project` contains mod.ts file.
* @param project
Expand All @@ -20,3 +26,46 @@ export function isDenoProject(
// }
// return false;
}

/**
* format code using `deno fmt`
*
* ```shell
* cat file.ts | deno fmt -
* ```
* @param code
* @param cwd
*/
export async function format(code: string): Promise<string> {
const reader = Readable.from([code]);

const subprocess = execa("deno", ["fmt", "-"], {
stdout: "pipe",
stderr: "pipe",
stdin: "pipe",
});

return new Promise((resolve, reject) => {
let stdout = "";
let stderr = "";
subprocess.on("exit", (exitCode: number) => {
if (exitCode !== 0) {
reject(new Error(stderr));
} else {
resolve(stdout);
}
});
subprocess.on("error", (err: Error) => {
reject(err);
});
subprocess.stdout.on("data", (data: Buffer) => {
stdout += data;
});

subprocess.stderr.on("data", (data: Buffer) => {
stderr += data;
});

subprocess.stdin && reader.pipe(subprocess.stdin);
});
}
Loading