Skip to content

Commit ed6ec62

Browse files
committed
Run configureIDE with sbt server
1 parent 90a4284 commit ed6ec62

File tree

4 files changed

+247
-50
lines changed

4 files changed

+247
-50
lines changed

vscode-dotty/package-lock.json

Lines changed: 10 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

vscode-dotty/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@
5959
"dependencies": {
6060
"child-process-promise": "^2.2.1",
6161
"vscode-languageclient": "^5.0.1",
62-
"vscode-languageserver": "^5.0.3"
62+
"vscode-languageserver": "^5.0.3",
63+
"vscode-jsonrpc": "4.0.0"
6364
},
6465
"devDependencies": {
6566
"@types/mocha": "^5.2.5",

vscode-dotty/src/extension.ts

Lines changed: 96 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,23 @@ import * as fs from 'fs';
44
import * as path from 'path';
55

66
import * as cpp from 'child-process-promise';
7+
import { ChildProcess } from "child_process";
78

89
import { ExtensionContext } from 'vscode';
910
import * as vscode from 'vscode';
1011
import { LanguageClient, LanguageClientOptions, RevealOutputChannelOn,
1112
ServerOptions } from 'vscode-languageclient';
1213

14+
import * as rpc from 'vscode-jsonrpc'
15+
16+
import * as sbtserver from './sbt-server'
17+
1318
let extensionContext: ExtensionContext
1419
let outputChannel: vscode.OutputChannel
1520

21+
/** The sbt process that may have been started by this extension */
22+
let sbtProcess: ChildProcess
23+
1624
const sbtVersion = "1.2.3"
1725
const sbtArtifact = `org.scala-sbt:sbt-launch:${sbtVersion}`
1826
const workspaceRoot = `${vscode.workspace.rootPath}`
@@ -54,27 +62,79 @@ export function activate(context: ExtensionContext) {
5462
})
5563

5664
} else {
57-
// Check whether `.dotty-ide-artifact` exists. If it does, start the language server,
58-
// otherwise, try propose to start it if there's no build.sbt
59-
if (fs.existsSync(languageServerArtifactFile)) {
60-
runLanguageServer(coursierPath, languageServerArtifactFile)
61-
} else if (isUnconfiguredProject()) {
62-
vscode.window.showInformationMessage(
63-
"This looks like an unconfigured Scala project. Would you like to start the Dotty IDE?",
64-
"Yes", "No"
65+
let configuredProject: Thenable<void> = Promise.resolve()
66+
if (isUnconfiguredProject()) {
67+
configuredProject = vscode.window.showInformationMessage(
68+
"This looks like an unconfigured Scala project. Would you like to start the Dotty IDE?",
69+
"Yes", "No"
6570
).then(choice => {
66-
if (choice == "Yes") {
67-
fetchAndConfigure(coursierPath, sbtArtifact, buildSbtFileSource, dottyPluginSbtFileSource).then(() => {
68-
runLanguageServer(coursierPath, languageServerArtifactFile)
69-
})
70-
} else {
71+
if (choice === "Yes") {
72+
bootstrapSbtProject(buildSbtFileSource, dottyPluginSbtFileSource)
73+
return Promise.resolve()
74+
} else if (choice === "No") {
7175
fs.appendFile(disableDottyIDEFile, "", _ => {})
76+
return Promise.reject()
7277
}
7378
})
7479
}
80+
81+
configuredProject
82+
.then(_ => withProgress("Configuring Dotty IDE...", configureIDE(coursierPath)))
83+
.then(_ => runLanguageServer(coursierPath, languageServerArtifactFile))
7584
}
7685
}
7786

87+
export function deactivate() {
88+
// If sbt was started by this extension, kill the process.
89+
// FIXME: This will be a problem for other clients of this server.
90+
if (sbtProcess) {
91+
sbtProcess.kill()
92+
}
93+
}
94+
95+
/**
96+
* Display a progress bar with title `title` while `op` completes.
97+
*
98+
* @param title The title of the progress bar
99+
* @param op The thenable that is monitored by the progress bar.
100+
*/
101+
function withProgress<T>(title: string, op: Thenable<T>): Thenable<T> {
102+
return vscode.window.withProgress({
103+
location: vscode.ProgressLocation.Window,
104+
title: title
105+
}, _ => op)
106+
}
107+
108+
/** Connect to an sbt server and run `configureIDE`. */
109+
function configureIDE(coursierPath: string): Thenable<sbtserver.ExecResult> {
110+
111+
function offeringToRetry(client: rpc.MessageConnection, command: string): Thenable<sbtserver.ExecResult> {
112+
return sbtserver.tellSbt(outputChannel, client, command)
113+
.then(success => Promise.resolve(success),
114+
_ => {
115+
outputChannel.show()
116+
return vscode.window.showErrorMessage("IDE configuration failed (see logs for details)", "Retry?")
117+
.then(retry => {
118+
if (retry) return offeringToRetry(client, command)
119+
else return Promise.reject()
120+
})
121+
})
122+
}
123+
124+
return withSbtInstance(outputChannel, coursierPath)
125+
.then(client => {
126+
// `configureIDE` is a command, which means that upon failure, sbt won't tell us anything
127+
// until sbt/sbt#4370 is fixed.
128+
// We run `compile` and `test:compile` first because they're tasks (so we get feedback from sbt
129+
// in case of failure), and we're pretty sure configureIDE will pass if they passed.
130+
return offeringToRetry(client, "compile").then(_ => {
131+
return offeringToRetry(client, "test:compile").then(_ => {
132+
return offeringToRetry(client, "configureIDE")
133+
})
134+
})
135+
})
136+
}
137+
78138
function runLanguageServer(coursierPath: string, languageServerArtifactFile: string) {
79139
fs.readFile(languageServerArtifactFile, (err, data) => {
80140
if (err) throw err
@@ -90,10 +150,28 @@ function runLanguageServer(coursierPath: string, languageServerArtifactFile: str
90150
})
91151
}
92152

93-
function fetchAndConfigure(coursierPath: string, sbtArtifact: string, buildSbtFileSource: string, dottyPluginSbtFileSource: string) {
94-
return fetchWithCoursier(coursierPath, sbtArtifact).then((sbtClasspath) => {
95-
return configureIDE(sbtClasspath, buildSbtFileSource, dottyPluginSbtFileSource)
153+
/**
154+
* Connects to an existing sbt server, or boots up one instance and connects to it.
155+
*/
156+
function withSbtInstance(log: vscode.OutputChannel, coursierPath: string): Thenable<rpc.MessageConnection> {
157+
const serverSocketInfo = path.join(workspaceRoot, "project", "target", "active.json")
158+
159+
if (!fs.existsSync(serverSocketInfo)) {
160+
fetchWithCoursier(coursierPath, sbtArtifact).then((sbtClasspath) => {
161+
sbtProcess = cpp.spawn("java", [
162+
"-classpath", sbtClasspath,
163+
"xsbt.boot.Boot"
164+
]).childProcess
165+
sbtProcess.stdout.on('data', data => {
166+
log.append(data.toString())
167+
})
168+
sbtProcess.stderr.on('data', data => {
169+
log.append(data.toString())
170+
})
96171
})
172+
}
173+
174+
return sbtserver.connectToSbtServer(log)
97175
}
98176

99177
function fetchWithCoursier(coursierPath: string, artifact: string, extra: string[] = []) {
@@ -127,40 +205,12 @@ function fetchWithCoursier(coursierPath: string, artifact: string, extra: string
127205
})
128206
}
129207

130-
function configureIDE(sbtClasspath: string,
131-
buildSbtFileSource: string,
132-
dottyPluginSbtFileSource: string) {
133-
134-
return vscode.window.withProgress({
135-
location: vscode.ProgressLocation.Window,
136-
title: 'Configuring the IDE for Dotty...'
137-
}, _ => {
138-
139-
// Bootstrap an sbt build
208+
function bootstrapSbtProject(buildSbtFileSource: string,
209+
dottyPluginSbtFileSource: string) {
140210
fs.mkdirSync(sbtProjectDir)
141211
fs.appendFileSync(sbtBuildPropertiesFile, `sbt.version=${sbtVersion}`)
142212
fs.copyFileSync(buildSbtFileSource, sbtBuildSbtFile)
143213
fs.copyFileSync(dottyPluginSbtFileSource, path.join(sbtProjectDir, "plugins.sbt"))
144-
145-
// Run sbt to configure the IDE.
146-
const sbtPromise =
147-
cpp.spawn("java", [
148-
"-classpath", sbtClasspath,
149-
"xsbt.boot.Boot",
150-
"configureIDE"
151-
])
152-
153-
const sbtProc = sbtPromise.childProcess
154-
sbtProc.on('close', (code: number) => {
155-
if (code != 0) {
156-
const msg = "Configuring the IDE failed."
157-
outputChannel.append(msg)
158-
throw new Error(msg)
159-
}
160-
})
161-
162-
return sbtPromise
163-
})
164214
}
165215

166216
function run(serverOptions: ServerOptions) {

vscode-dotty/src/sbt-server.ts

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
/*
2+
* sbt
3+
* Copyright 2011 - 2018, Lightbend, Inc.
4+
* Copyright 2008 - 2010, Mark Harrah
5+
* Licensed under Apache License 2.0 (see LICENSE)
6+
*/
7+
// Copy pasted from vscode-sbt-scala
8+
9+
'use strict'
10+
11+
import * as fs from 'fs'
12+
import * as net from 'net'
13+
import * as os from 'os'
14+
import * as path from 'path'
15+
import * as url from 'url'
16+
17+
import * as rpc from 'vscode-jsonrpc'
18+
19+
import * as vscode from 'vscode'
20+
21+
/** The result of successful `sbt/exec` call. */
22+
export interface ExecResult {
23+
status: string
24+
channelName: string
25+
execId: number
26+
commandQueue: string[]
27+
exitCode: number
28+
}
29+
30+
class CommandLine {
31+
commandLine: string
32+
constructor(commandLine: string) {
33+
this.commandLine = commandLine
34+
}
35+
}
36+
37+
/**
38+
* Sends `command` to sbt with `sbt/exec`.
39+
*
40+
* @param log Where to log messages between this client and sbt server
41+
* @param connection The connection to sbt server to use
42+
* @param command The command to send to sbt
43+
*
44+
* @return The result of executing `command`.
45+
*/
46+
export function tellSbt(log: vscode.OutputChannel,
47+
connection: rpc.MessageConnection,
48+
command: string): Thenable<ExecResult> {
49+
log.appendLine(`>>> ${command}`)
50+
let req = new rpc.RequestType<CommandLine, ExecResult, any, any>("sbt/exec")
51+
return connection.sendRequest(req, new CommandLine(command))
52+
}
53+
54+
/**
55+
* Attempts to connect to an sbt server running in this workspace.
56+
*
57+
* If connection fails, shows an error message and ask the user to retry.
58+
*
59+
* @param log Where to log messages between VSCode and sbt server.
60+
*/
61+
export function connectToSbtServer(log: vscode.OutputChannel): Promise<rpc.MessageConnection> {
62+
return waitForServer().then(socket => {
63+
if (socket) {
64+
let connection = rpc.createMessageConnection(
65+
new rpc.StreamMessageReader(socket),
66+
new rpc.StreamMessageWriter(socket))
67+
68+
connection.listen()
69+
70+
connection.onNotification("window/logMessage", (params) => {
71+
log.appendLine(`<<< [${messageTypeToString(params.type)}] ${params.message}`)
72+
})
73+
74+
return connection
75+
} else {
76+
return vscode.window.showErrorMessage("Couldn't connect to sbt server.", "Retry?").then(answer => {
77+
if (answer) {
78+
return connectToSbtServer(log)
79+
} else {
80+
log.show()
81+
return Promise.reject()
82+
}
83+
})
84+
}
85+
})
86+
}
87+
88+
function connectSocket(socket: net.Socket): net.Socket {
89+
let u = discoverUrl();
90+
if (u.protocol == 'tcp:' && u.port) {
91+
socket.connect(+u.port, '127.0.0.1');
92+
} else if (u.protocol == 'local:' && u.hostname && os.platform() == 'win32') {
93+
let pipePath = '\\\\.\\pipe\\' + u.hostname;
94+
socket.connect(pipePath);
95+
} else if (u.protocol == 'local:' && u.path) {
96+
socket.connect(u.path);
97+
} else {
98+
throw 'Unknown protocol ' + u.protocol;
99+
}
100+
return socket;
101+
}
102+
103+
// the port file is hardcoded to a particular location relative to the build.
104+
function discoverUrl(): url.Url {
105+
let pf = path.join(process.cwd(), 'project', 'target', 'active.json');
106+
let portfile = JSON.parse(fs.readFileSync(pf).toString());
107+
return url.parse(portfile.uri);
108+
}
109+
110+
function delay(ms: number) {
111+
return new Promise(resolve => setTimeout(resolve, ms));
112+
}
113+
114+
async function waitForServer(): Promise<net.Socket | null> {
115+
let socket: net.Socket | null = null
116+
return vscode.window.withProgress({
117+
location: vscode.ProgressLocation.Window,
118+
title: "Connecting to sbt server..."
119+
}, async _ => {
120+
let retries = 60;
121+
while (!socket && retries > 0) {
122+
try { socket = connectSocket(new net.Socket()) }
123+
catch (e) {
124+
retries--;
125+
await delay(1000);
126+
}
127+
}
128+
return socket
129+
}).then(_ => socket)
130+
}
131+
132+
function messageTypeToString(messageType: number): string {
133+
if (messageType == 1) return "error"
134+
else if (messageType == 2) return "warn"
135+
else if (messageType == 3) return "info"
136+
else if (messageType == 4) return "log"
137+
else return "???"
138+
}
139+

0 commit comments

Comments
 (0)