forked from JohnnyMorganz/StyLua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.ts
More file actions
299 lines (264 loc) · 8.76 KB
/
extension.ts
File metadata and controls
299 lines (264 loc) · 8.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import * as vscode from "vscode";
import * as path from "path";
import * as semver from "semver";
import { formatCode, checkIgnored } from "./stylua";
import { GitHub, GitHubRelease } from "./github";
import { ResolveMode, StyluaDownloader, StyluaInfo } from "./download";
import { getDesiredVersion } from "./util";
const documentSelector = ["lua", "luau"];
/**
* Convert a Position within a Document to a byte offset.
* Required as `document.offsetAt(position)` returns a char offset, causing inconsistencies when sending over to StyLua
* @param document The document to retrieve the byte offset in
* @param position The position to retrieve the byte offset for
*/
const byteOffset = (
document: vscode.TextDocument,
position: vscode.Position
) => {
// Retrieve all the text from the start of the document to the position provided
const textRange = new vscode.Range(document.positionAt(0), position);
const text = document.getText(textRange);
// Retrieve the byte length of the text range in a buffer
return Buffer.byteLength(text);
};
class StatusInfo implements vscode.Disposable {
statusItem: vscode.LanguageStatusItem;
styluaInfo: StyluaInfo | undefined;
constructor() {
this.statusItem = vscode.languages.createLanguageStatusItem(
"stylua",
documentSelector
);
this.statusItem.name = "StyLua";
this.statusItem.command = {
title: "Show Output",
command: "stylua.showOutputChannel",
};
this.updateReady();
}
setStyluaInfo(styluaInfo: StyluaInfo | undefined) {
this.styluaInfo = styluaInfo;
this.updateReady();
}
getStyluaText() {
if (this.styluaInfo && this.styluaInfo.version) {
if (this.styluaInfo.resolveMode === ResolveMode.bundled) {
return `StyLua (bundled ${this.styluaInfo.version})`;
} else {
return `StyLua (${this.styluaInfo.version})`;
}
}
return "StyLua";
}
updateReady() {
this.statusItem.text = `$(check) ${this.getStyluaText()}`;
this.statusItem.detail = "Ready";
this.statusItem.severity = vscode.LanguageStatusSeverity.Information;
}
updateFormatSuccess() {
this.statusItem.text = `$(check) ${this.getStyluaText()}`;
this.statusItem.detail = "File formatted successfully";
this.statusItem.severity = vscode.LanguageStatusSeverity.Information;
}
updateFormatFailure() {
this.statusItem.text = `${this.getStyluaText()}`;
this.statusItem.detail = "Failed to format file";
this.statusItem.severity = vscode.LanguageStatusSeverity.Error;
}
dispose() {
this.statusItem.dispose();
}
}
export async function activate(context: vscode.ExtensionContext) {
console.log("stylua activated");
const outputChannel = vscode.window.createOutputChannel("StyLua", {
log: true,
});
outputChannel.info("StyLua activated");
const statusItem = new StatusInfo();
const github = new GitHub();
context.subscriptions.push(github);
const downloader = new StyluaDownloader(
context.globalStorageUri,
github,
outputChannel
);
let cwdForVersionDetection =
vscode.workspace.workspaceFolders?.[0].uri.fsPath;
let styluaBinaryPath = await downloader.ensureStyluaExists(
cwdForVersionDetection
);
statusItem.setStyluaInfo(styluaBinaryPath);
context.subscriptions.push(
vscode.commands.registerCommand("stylua.reinstall", async () => {
await downloader.downloadStyLuaVisual(getDesiredVersion());
styluaBinaryPath = await downloader.ensureStyluaExists(
cwdForVersionDetection
);
statusItem.setStyluaInfo(styluaBinaryPath);
})
);
context.subscriptions.push(
vscode.commands.registerCommand("stylua.authenticate", async () => {
await github.authenticate();
})
);
context.subscriptions.push(
vscode.commands.registerCommand("stylua.showOutputChannel", async () => {
outputChannel.show();
})
);
context.subscriptions.push(
vscode.commands.registerCommand("stylua.selectVersion", async () => {
const versions = (await github.getAllReleases()).sort((a, b) =>
semver.rcompare(a.tagName, b.tagName)
);
if (versions.length === 0) {
return;
}
const latestVersion = versions[0];
const selectedVersion = await vscode.window.showQuickPick(
versions
.sort((a, b) => semver.rcompare(a.tagName, b.tagName))
.map((release) => {
if (release.tagName === latestVersion.tagName) {
return { label: `${release.tagName} (latest)` };
} else {
return { label: release.tagName };
}
}),
{
placeHolder: "Select the version of StyLua to install",
}
);
if (selectedVersion) {
const updateConfigValue = selectedVersion.label.includes("latest")
? "latest"
: selectedVersion.label;
await downloader.downloadStyLuaVisual(updateConfigValue);
vscode.workspace
.getConfiguration("stylua")
.update(
"targetReleaseVersion",
updateConfigValue,
vscode.ConfigurationTarget.Workspace
);
}
})
);
context.subscriptions.push(
vscode.commands.registerCommand(
"stylua.installUpdate",
async (release: GitHubRelease) => {
const result = await vscode.window.showInformationMessage(
`Are you sure you want to update StyLua to ${release.tagName}?`,
{ modal: true },
"Update",
"Release Notes",
"Do not show again"
);
switch (result) {
case "Update":
await downloader.downloadStyLuaVisual(release.tagName);
vscode.workspace
.getConfiguration("stylua")
.update("targetReleaseVersion", "latest");
break;
case "Release Notes":
vscode.env.openExternal(vscode.Uri.parse(release.htmlUrl));
break;
case "Do not show again":
vscode.workspace
.getConfiguration("stylua")
.update("disableVersionCheck", true);
break;
}
}
)
);
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration(async (change) => {
if (change.affectsConfiguration("stylua")) {
styluaBinaryPath = await downloader.ensureStyluaExists(
cwdForVersionDetection
);
statusItem.setStyluaInfo(styluaBinaryPath);
}
})
);
let disposable = vscode.languages.registerDocumentRangeFormattingEditProvider(
documentSelector,
{
async provideDocumentRangeFormattingEdits(
document: vscode.TextDocument,
range: vscode.Range,
_options: vscode.FormattingOptions,
_token: vscode.CancellationToken
) {
if (!styluaBinaryPath) {
vscode.window
.showErrorMessage(
"StyLua not found. Could not format file",
"Install"
)
.then((option) => {
if (option === "Install") {
vscode.commands.executeCommand("stylua.reinstall");
}
});
return [];
}
const currentWorkspace = vscode.workspace.getWorkspaceFolder(
document.uri
);
const workspacePath = currentWorkspace?.uri?.fsPath;
const documentPath = document.uri.fsPath;
const cwd =
workspacePath && documentPath.startsWith(workspacePath)
? workspacePath
: path.dirname(documentPath);
if (await checkIgnored(document.uri, currentWorkspace?.uri)) {
return [];
}
const text = document.getText();
try {
const formattedText = await formatCode(
styluaBinaryPath.path,
text,
cwd,
byteOffset(document, range.start),
byteOffset(document, range.end)
);
// Replace the whole document with our new formatted version
const lastLineNumber = document.lineCount - 1;
const fullDocumentRange = new vscode.Range(
0,
0,
lastLineNumber,
document.lineAt(lastLineNumber).text.length
);
const format = vscode.TextEdit.replace(
fullDocumentRange,
formattedText
);
statusItem.updateFormatSuccess();
return [format];
} catch (err) {
statusItem.updateFormatFailure();
outputChannel.error(err as string);
return [];
}
},
}
);
context.subscriptions.push(disposable);
context.subscriptions.push(statusItem);
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor((editor) => {
statusItem.updateReady();
})
);
}
// this method is called when your extension is deactivated
export function deactivate() {}