forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevtoolsserver.ts
More file actions
568 lines (513 loc) · 17.8 KB
/
Copy pathdevtoolsserver.ts
File metadata and controls
568 lines (513 loc) · 17.8 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import {
CHANGE,
ConnectionState,
delay,
ERROR_TRANSPORT_CLOSED,
groupBy,
isCodeError,
JDEventSource,
JDService,
} from "jacdac-ts"
import * as vscode from "vscode"
import type {
BuildStatus,
SideBuildReq,
SideBuildResp,
SideKillReq,
SideKillResp,
SideSpecsReq,
SideSpecsResp,
VersionInfo,
} from "../../cli/src/sideprotocol"
import { logo } from "./assets"
import { sideRequest } from "./jacdac"
import { DeviceScriptExtensionState } from "./state"
import { Utils } from "vscode-uri"
import { TaggedQuickPickItem } from "./pickers"
import { EXIT_CODE_EADDRINUSE } from "../../cli/src/exitcodes"
import { MESSAGE_PREFIX, showInformationMessageWithHelp } from "./commands"
import { checkFileExists } from "./fs"
import { ResolvedBuildConfig } from "@devicescript/compiler"
function showTerminalError(message: string) {
showInformationMessageWithHelp(
message,
"getting-started/vscode#setting-up-the-project"
)
}
export class DeveloperToolsManager extends JDEventSource {
private _connectionState: ConnectionState = ConnectionState.Disconnected
private _projectFolder: vscode.Uri
// watch is tied to currentFilename and devicescript manager
private _watcher: vscode.FileSystemWatcher
private _currentFilename: string
private _currentDeviceScriptManager: string
private _versions: VersionInfo
private _buildConfig: ResolvedBuildConfig
private _terminalPromise: Promise<vscode.Terminal>
private _diagColl: vscode.DiagnosticCollection
constructor(readonly extensionState: DeviceScriptExtensionState) {
super()
const { context } = this.extensionState
const { subscriptions } = context
vscode.workspace.onDidChangeWorkspaceFolders(
this.handleWorkspaceFoldersChange,
this,
subscriptions
)
vscode.workspace.onDidDeleteFiles(
this.handleDidDeleteFiles,
this,
subscriptions
)
vscode.workspace.onDidRenameFiles(
this.handleDidRenameFiles,
this,
subscriptions
)
vscode.window.onDidCloseTerminal(
this.handleCloseTerminal,
this,
subscriptions
)
subscriptions.push(this)
subscriptions.push(
vscode.commands.registerCommand(
"extension.devicescript.terminal.show",
() => this.show()
)
)
// outputCh = vscode.window.createOutputChannel("DevS Build")
this._diagColl =
vscode.languages.createDiagnosticCollection("DeviceScript")
// clear errors when file edited
vscode.workspace.onDidChangeTextDocument(
ev => {
this._diagColl.set(ev.document.uri, [])
},
undefined,
subscriptions
)
}
async refreshSpecs() {
const res = await sideRequest<SideSpecsReq, SideSpecsResp>({
req: "specs",
data: {
dir: ".", // TODO
},
})
const { versions, buildConfig } = res.data
this._versions = versions
console.debug(
`devicescript devtools ${this.version}, runtime ${this.runtimeVersion}, node ${this.nodeVersion}`
)
this.updateBuildConfig(buildConfig)
}
updateBuildConfig(data: ResolvedBuildConfig) {
if (JSON.stringify(this._buildConfig) === JSON.stringify(data)) return
this._buildConfig = data
const { changed } =
this.extensionState.bus.setCustomServiceSpecifications(
this._buildConfig?.services || []
)
if (changed) this.emit(CHANGE)
}
private showBuildResults(st: BuildStatus) {
this._diagColl.clear()
const severities = [
vscode.DiagnosticSeverity.Warning,
vscode.DiagnosticSeverity.Error,
vscode.DiagnosticSeverity.Hint,
vscode.DiagnosticSeverity.Information,
]
const byFile = groupBy(st.diagnostics, s => s.filename)
for (const fn of Object.keys(byFile)) {
const diags = byFile[fn].map(d => {
const p0 = new vscode.Position(d.line - 1, d.column - 1)
const p1 = new vscode.Position(d.endLine - 1, d.endColumn - 1)
const msg =
typeof d.messageText == "string"
? d.messageText
: d.messageText.messageText
const sev =
severities[d.category] ?? vscode.DiagnosticSeverity.Error
const vd = new vscode.Diagnostic(
new vscode.Range(p0, p1),
msg,
sev
)
vd.source = "DeviceScript"
vd.code = d.code
return vd
})
this._diagColl.set(vscode.Uri.file(fn), diags)
}
this.updateBuildConfig(st.config)
}
get currentFilename() {
return this._currentFilename
}
get currentFile(): vscode.Uri {
const { projectFolder, currentFilename } = this
return projectFolder && currentFilename
? Utils.joinPath(projectFolder, currentFilename)
: undefined
}
get currentDeviceScriptManager() {
return this._currentDeviceScriptManager
}
async build(filename: string, service?: JDService): Promise<BuildStatus> {
if (
this._currentFilename === filename &&
this._currentDeviceScriptManager === service?.id
)
return
this._currentFilename = filename
this._currentDeviceScriptManager = service?.id
this._watcher?.dispose()
this._watcher = undefined
const res = await this.buildOnce()
if (res) await this.startWatch()
this.emit(CHANGE)
return res
}
private async buildOnce(): Promise<BuildStatus> {
const filename = this._currentFilename
if (!this._currentFilename) return undefined
console.debug(`build ${filename}`)
const service = this.extensionState.bus.node(
this._currentDeviceScriptManager
) as JDService
const deployTo = service?.device?.deviceId
try {
const res = await sideRequest<SideBuildReq, SideBuildResp>({
req: "build",
data: {
filename,
deployTo,
},
})
this.showBuildResults(res.data)
return res.data
} catch (err) {
console.error(err) // TODO
return undefined
}
}
private async startWatch() {
const filename = this._currentFilename
const sid = this._currentDeviceScriptManager
console.debug(`fs.watch: ${filename}`)
const handleChange = async (uri: vscode.Uri) => {
console.debug(`fs changed: ${uri.fsPath}`)
const service = this.extensionState.bus.node(sid) as JDService
await this.build(filename, service)
}
const glob = new vscode.RelativePattern(this.projectFolder, filename)
this._watcher = vscode.workspace.createFileSystemWatcher(glob)
this._watcher.onDidChange(handleChange)
this._watcher.onDidCreate(handleChange)
this._watcher.onDidDelete(handleChange)
}
private async init() {
try {
await this.refreshSpecs()
} catch (e) {
if (isCodeError(e, ERROR_TRANSPORT_CLOSED)) return false
else throw e
}
return true
}
get version() {
return this._versions?.version
}
get runtimeVersion() {
return this._versions?.runtimeVersion
}
get nodeVersion() {
return this._versions?.nodeVersion
}
get buildConfig() {
return this._buildConfig
}
get boards() {
return Object.values(this.buildConfig?.boards)
}
get projectFolder() {
return this._projectFolder
}
set projectFolder(folder: vscode.Uri) {
if (folder?.toString() !== this._projectFolder?.toString()) {
if (this._projectFolder) this.kill()
this._projectFolder = folder
this.emit(CHANGE)
}
}
get connectionState() {
return this._connectionState
}
get connected() {
return this.connectionState === ConnectionState.Connected
}
private set connectionState(state: ConnectionState) {
if (state !== this._connectionState) {
this._connectionState = state
this.emit(CHANGE)
}
}
async pickProject() {
const projects = await this.findProjects()
if (projects.length == 0) return undefined
else if (projects.length == 1) return projects[0]
else {
const items = projects.map(
project =>
<TaggedQuickPickItem<vscode.Uri>>{
data: project,
description: Utils.dirname(project).fsPath,
label: Utils.basename(project),
}
)
const res = await vscode.window.showQuickPick(items, {
title: "Choose a project",
})
return res?.data
}
}
private async createTerminal(): Promise<vscode.Terminal> {
if (!this._projectFolder) this._projectFolder = await this.pickProject()
if (!this._projectFolder) {
showTerminalError("No DeviceScript project in workspace.")
return undefined
}
try {
this.connectionState = ConnectionState.Connecting
const t = await this.createCliTerminal({
title: "DeviceScript",
progress: "Starting Development Server...",
args: ["devtools", "--vscode"],
message: "DeviceScript Development Server\n",
})
if (!t) {
this.clear()
return undefined
}
this.connectionState = ConnectionState.Connected
return t
} catch (e) {
this.clear()
return undefined
}
}
start(): Promise<void> {
return (
this._terminalPromise ||
(this._terminalPromise = this.createTerminal())
).then(() => this.startBuild())
}
private async startBuild() {
const files = await vscode.workspace.fs.readDirectory(
this.projectFolder
)
const file =
files.find(
([name, type]) =>
type == vscode.FileType.File && name === "main.ts"
) ||
files.find(
([name, type]) =>
type == vscode.FileType.File && /\.ts$/i.test(name)
)
if (file) await this.build(file[0])
}
dispose() {
this.kill()
}
private async sendKillRequest() {
try {
await sideRequest<SideKillReq, SideKillResp>({
req: "kill",
data: {},
})
// process acknoledged the message
return true
} catch {
return false
}
}
private async kill() {
this.sendKillRequest()
const p = this._terminalPromise
this.clear()
if (p) {
const t = await p
if (t) {
try {
t.sendText("\u001c")
} catch {}
}
}
}
private async handleWorkspaceFoldersChange(
e: vscode.WorkspaceFoldersChangeEvent
) {
if (e.removed && this._projectFolder) {
const projects = (await this.findProjects()).map(uri =>
uri.toString()
)
if (!projects.includes(this._projectFolder?.toString()))
this.projectFolder = undefined
}
}
private async handleDidDeleteFiles(ev: vscode.FileDeleteEvent) {
const cf = this.currentFile
if (!cf) return
const pp = cf.path
if (ev.files.find(f => f.path === pp)) await this.build(undefined)
}
private async handleDidRenameFiles(ev: vscode.FileRenameEvent) {
const cf = this.currentFile
if (!cf) return
const pp = cf.path
// TODO better than just stop everyhing
if (ev.files.find(f => f.oldUri.path === pp))
await this.build(undefined)
}
private async handleCloseTerminal(t: vscode.Terminal) {
if (this._terminalPromise && t === (await this._terminalPromise)) {
this.clear()
if (t.exitStatus.reason === vscode.TerminalExitReason.Process) {
switch (t.exitStatus.code) {
case EXIT_CODE_EADDRINUSE:
// try to send a kill command
console.debug(
`trying to shutdown other developement server`
)
const killed = await this.sendKillRequest()
if (killed) {
await delay(1000)
await this.start()
} else
showTerminalError(
`Development Server ports already in use.`
)
break
default:
showTerminalError(
`Development Server exited unexpectedly.`
)
break
}
}
}
}
private clear() {
this._terminalPromise = undefined
this._projectFolder = undefined
this._versions = undefined
this._watcher?.dispose()
this._watcher = undefined
this._currentFilename = undefined
this._currentDeviceScriptManager = undefined
this.updateBuildConfig(undefined) // TODOD
this.connectionState = ConnectionState.Disconnected
this.emit(CHANGE)
}
async findProjects() {
// find file marker
const configs = await vscode.workspace.findFiles(
"**/devsconfig.json",
"**/node_modules/**"
)
return configs
.map(cfg => Utils.dirname(cfg))
.filter(d => !/\/node_modules\//.test(d.fsPath))
}
async show() {
if (!this._terminalPromise) return
const terminal = await this._terminalPromise
terminal?.show()
}
public async createCliTerminal(options: {
title?: string
progress: string
useShell?: boolean
diagnostics?: boolean
message?: string
args: string[]
}): Promise<vscode.Terminal> {
if (!this._projectFolder) {
return undefined
}
const cwd = this._projectFolder
const devsConfig = await checkFileExists(cwd, "./devsconfig.json")
if (!devsConfig) {
showTerminalError("Could not find file `devsconfig.json`.")
return undefined // not a devicescript folder
}
const cliBin = "./node_modules/.bin/devicescript"
const cliInstalled = await checkFileExists(cwd, cliBin)
if (!cliInstalled) {
showTerminalError("Install Node.JS dependencies to enable tools.")
return undefined
}
const { title, progress, args, message } = options
return vscode.window.withProgress<vscode.Terminal>(
{
location: vscode.ProgressLocation.Notification,
title: MESSAGE_PREFIX + progress,
cancellable: false,
},
async () => {
const devToolsConfig = vscode.workspace.getConfiguration(
"devicescript.devtools"
)
const jacdacConfig = vscode.workspace.getConfiguration(
"devicescript.jacdac"
)
const isWindows = globalThis.process?.platform === "win32"
const useShell =
options.useShell ?? !!devToolsConfig.get("shell")
const nodePath = devToolsConfig.get("node") as string
const diagnostics =
options.diagnostics ?? jacdacConfig.get("diagnostics")
let cli = nodePath || "node"
if (isWindows) {
cli = "node_modules\\.bin\\devicescript.cmd"
} else args.unshift("./node_modules/.bin/devicescript")
if (diagnostics) args.push("--diagnostics")
console.debug(
`create terminal: ${useShell ? "shell:" : ""}${
cwd.fsPath
}> ${cli} ${args.join(" ")}`
)
const terminalOptions: vscode.TerminalOptions = {
name: "DeviceScript" || title,
hideFromUser: false,
message,
isTransient: true,
shellPath: useShell ? undefined : cli,
shellArgs: useShell ? undefined : args,
iconPath: logo(this.extensionState.context),
cwd: cwd.fsPath,
}
const t = vscode.window.createTerminal(terminalOptions)
if (useShell) {
t.sendText("", true)
t.sendText(`${cli} ${args.join(" ")}`, true)
}
let retry = 0
let inited = false
while (retry++ < 20) {
inited = await this.init()
if (inited) break
await delay(500)
}
if (!inited) {
this.clear()
return undefined
}
return t
}
)
}
}