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

feat: Use toolchain's swift-format as a formatting provider #1193

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 3 additions & 0 deletions src/WorkspaceContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { DebugAdapter, LaunchConfigType } from "./debugger/debugAdapter";
import { SwiftBuildStatus } from "./ui/SwiftBuildStatus";
import { SwiftToolchain } from "./toolchain/toolchain";
import { DiagnosticsManager } from "./DiagnosticsManager";
import { FormattingProvider } from "./editor/Formatting";

/**
* Context for whole workspace. Holds array of contexts for each workspace folder
Expand All @@ -49,6 +50,7 @@ export class WorkspaceContext implements vscode.Disposable {
public diagnostics: DiagnosticsManager;
public subscriptions: vscode.Disposable[];
public commentCompletionProvider: CommentCompletionProviders;
public formattingProvider: FormattingProvider;
private lastFocusUri: vscode.Uri | undefined;
private initialisationFinished = false;

Expand All @@ -64,6 +66,7 @@ export class WorkspaceContext implements vscode.Disposable {
this.diagnostics = new DiagnosticsManager(this);
this.currentDocument = null;
this.commentCompletionProvider = new CommentCompletionProviders();
this.formattingProvider = new FormattingProvider();

const onChangeConfig = vscode.workspace.onDidChangeConfiguration(async event => {
// on runtime path config change, regenerate launch.json
Expand Down
105 changes: 105 additions & 0 deletions src/editor/Formatting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VSCode Swift open source project
//
// Copyright (c) 2021 the VSCode Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VSCode Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import * as vscode from "vscode";
import { execSwift } from "../utilities/utilities";

const wholeDocumentRange = new vscode.Range(0, 0, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);

function format(request: {
document: vscode.TextDocument;
parameters?: string[];
range?: vscode.Range;
formatting: vscode.FormattingOptions;
}): Promise<never[] | vscode.TextEdit[]> {
const input = request.document.getText(request.range);
if (input.trim() === "") {
return Promise.resolve([]);
}
const formatProc = execSwift(
["format", ...(request.parameters || [])],
"default",
{},
undefined,
input
);
return formatProc
.then(result => {
if (result.stderr) {
// FIXME: handle stderr
return [];
}
const newContents = result.stdout;
return newContents !== request.document.getText(request.range)
? [
vscode.TextEdit.replace(
request.document.validateRange(request.range || wholeDocumentRange),
newContents
),
]
: [];
})
.catch((/* error */) => {
// FIXME: handle error
return [];
});
}

export class FormattingProvider
implements
vscode.DocumentRangeFormattingEditProvider,
vscode.DocumentFormattingEditProvider,
vscode.OnTypeFormattingEditProvider
{
constructor() {
const provider = new FormattingProvider();
const swiftSelector: vscode.DocumentSelector = {
scheme: "file",
language: "swift",
};
vscode.languages.registerDocumentRangeFormattingEditProvider(swiftSelector, provider);
vscode.languages.registerDocumentFormattingEditProvider(swiftSelector, provider);
vscode.languages.registerOnTypeFormattingEditProvider(swiftSelector, provider, "\n");
}
async provideDocumentRangeFormattingEdits(
document: vscode.TextDocument,
range: vscode.Range,
formatting: vscode.FormattingOptions
) {
return await format({
document,
parameters: [],
range,
formatting,
});
}
async provideDocumentFormattingEdits(
document: vscode.TextDocument,
formatting: vscode.FormattingOptions
) {
return await format({ document, formatting });
}
async provideOnTypeFormattingEdits(
document: vscode.TextDocument,
position: vscode.Position,
_: string,
formatting: vscode.FormattingOptions
) {
// Don't format if user has inserted an empty line
if (document.lineAt(position.line).text.trim() === "") {
return [];
}
return await format({ document, formatting });
}
}
19 changes: 13 additions & 6 deletions src/utilities/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export async function execFile(
executable: string,
args: string[],
options: cp.ExecFileOptions = {},
input?: string,
folderContext?: FolderContext,
customSwiftRuntime = true
): Promise<{ stdout: string; stderr: string }> {
Expand All @@ -109,14 +110,19 @@ export async function execFile(
options.env = { ...(options.env ?? process.env), ...runtimeEnv };
}
}
return new Promise<{ stdout: string; stderr: string }>((resolve, reject) =>
cp.execFile(executable, args, options, (error, stdout, stderr) => {
return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
const proc = cp.execFile(executable, args, options, (error, stdout, stderr) => {
if (error) {
reject(new ExecFileError(error, stdout, stderr));
}
resolve({ stdout, stderr });
})
);
});

if (input && proc.stdin) {
proc.stdin.write(input);
proc.stdin.end();
}
});
}

export async function execFileStreamOutput(
Expand Down Expand Up @@ -178,7 +184,8 @@ export async function execSwift(
args: string[],
toolchain: SwiftToolchain | "default",
options: cp.ExecFileOptions = {},
folderContext?: FolderContext
folderContext?: FolderContext,
input?: string
): Promise<{ stdout: string; stderr: string }> {
let swift: string;
if (toolchain === "default") {
Expand All @@ -197,7 +204,7 @@ export async function execSwift(
...configuration.swiftEnvironmentVariables,
};
}
return await execFile(swift, args, options, folderContext);
return await execFile(swift, args, options, input, folderContext);
}

/**
Expand Down