Skip to content

Commit 726992a

Browse files
authoredDec 30, 2016
Merge pull request #7 from apatrida/master
Fix the output for stdout, stderr, errors in general, and Unit return types
2 parents 24f7a60 + df29b7d commit 726992a

File tree

10 files changed

+240
-216
lines changed

10 files changed

+240
-216
lines changed
 

‎build.gradle

+6-6
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ buildscript {
33
ext.shadowJarVersion = "1.2.3"
44
ext.kotlinVersion = '1.1-M04'
55
repositories {
6-
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
7-
maven { url 'https://repo.gradle.org/gradle/repo' }
6+
maven { url 'http://dl.bintray.com/kotlin/kotlin-eap-1.1' }
7+
// only when using Kotlin DEV releases ...
8+
// maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
89
jcenter()
910
mavenCentral()
1011
}
@@ -18,10 +19,11 @@ allprojects {
1819
apply plugin: 'kotlin'
1920

2021
repositories {
21-
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
22-
maven { url 'https://repo.gradle.org/gradle/repo' }
2322
jcenter()
2423
mavenCentral()
24+
maven { url 'http://dl.bintray.com/kotlin/kotlin-eap-1.1' }
25+
// only when using Kotlin DEV releases ...
26+
// maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
2527
}
2628

2729
dependencies {
@@ -41,7 +43,6 @@ configurations {
4143
}
4244

4345
dependencies {
44-
compile project(':jupyter-lib')
4546
compile "org.jetbrains.kotlin:kotlin-compiler-embeddable:$kotlinVersion"
4647
compile "org.jetbrains.kotlin:kotlin-script-util:$kotlinVersion"
4748
compile 'org.slf4j:slf4j-api:1.7.21'
@@ -52,7 +53,6 @@ dependencies {
5253
runtime 'org.apache.maven:maven-core:3.0.3'
5354
runtime 'org.slf4j:slf4j-simple:1.7.21'
5455
deploy "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
55-
deploy project(':jupyter-lib')
5656
}
5757

5858
jar.manifest.attributes(

‎jupyter-lib/build.gradle

-6
This file was deleted.

‎jupyter-lib/src/main/kotlin/jupyter/kotlin/results.kt

-9
This file was deleted.

‎settings.gradle

-1
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
include 'jupyter-lib'
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,23 @@
11
package org.jetbrains.kotlin.jupyter
22

3-
import jupyter.kotlin.Result
4-
import jupyter.kotlin.textResult
5-
63
enum class ReplCommands(val desc: String) {
74
help("display help"),
85
classpath("show current classpath")
96
}
107

118
fun isCommand(code: String): Boolean = code.startsWith(":")
129

13-
fun runCommand(code: String, repl: ReplForJupyter?): Result {
10+
fun runCommand(code: String, repl: ReplForJupyter?): ResponseWithMessage {
1411
val args = code.trim().substring(1).split(" ")
1512
val cmd =
1613
try {
1714
ReplCommands.valueOf(args[0])
1815
}
1916
catch (e: IllegalArgumentException) {
20-
return textResult("unknown command: $code\nto see available commands, enter :help")
17+
return ResponseWithMessage(ResponseState.Error, textResult("Failed!"), null, "unknown command: $code\nto see available commands, enter :help")
2118
}
2219
return when (cmd) {
23-
ReplCommands.classpath -> textResult("current classpath:\n${repl?.classpath?.joinToString("\n ", prefix = " ")}")
24-
ReplCommands.help -> textResult("Available commands:\n${ReplCommands.values().joinToString("\n ", prefix = " ") { ":${it.name} - ${it.desc}" }}")
20+
ReplCommands.classpath -> ResponseWithMessage(ResponseState.Ok, textResult("current classpath:\n${repl?.classpath?.joinToString("\n ", prefix = " ")}"), null, null)
21+
ReplCommands.help -> ResponseWithMessage(ResponseState.Ok, textResult("Available commands:\n${ReplCommands.values().joinToString("\n ", prefix = " ") { ":${it.name} - ${it.desc}" }}"), null, null)
2522
}
2623
}

‎src/main/kotlin/org/jetbrains/kotlin/jupyter/connection.kt

-24
Original file line numberDiff line numberDiff line change
@@ -47,28 +47,6 @@ class JupyterConnection(val config: KernelConfig): Closeable {
4747
val connection: JupyterConnection = this@JupyterConnection
4848
}
4949

50-
private inner class IopubOutputStream(val streamName: String) : java.io.OutputStream() {
51-
fun sendToSocket(text: String) {
52-
iopub.send(Message(
53-
header = makeHeader("stream", contextMessage),
54-
content = jsonObject(
55-
"name" to streamName,
56-
"text" to text)))
57-
}
58-
59-
override fun write(b: ByteArray, off: Int, len: Int) {
60-
val buf = ByteArrayOutputStream()
61-
buf.write(b, off, len)
62-
sendToSocket(buf.toString())
63-
}
64-
65-
override fun write(b: Int) {
66-
val buf = ByteArrayOutputStream()
67-
buf.write(b)
68-
sendToSocket(buf.toString())
69-
}
70-
}
71-
7250
inner class StdinInputStream : java.io.InputStream() {
7351
private var currentBuf: ByteArray? = null
7452
private var currentBufPos = 0
@@ -128,8 +106,6 @@ class JupyterConnection(val config: KernelConfig): Closeable {
128106
val stdin = Socket(JupyterSockets.stdin, ZMQ.ROUTER)
129107
val iopub = Socket(JupyterSockets.iopub, ZMQ.PUB)
130108

131-
val iopubOut = PrintStream(IopubOutputStream("stdout"))
132-
val iopubErr = PrintStream(IopubOutputStream("stderr"))
133109
val stdinIn = StdinInputStream()
134110

135111
var contextMessage: Message? = null

‎src/main/kotlin/org/jetbrains/kotlin/jupyter/display.kt

-66
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
1-
21
package org.jetbrains.kotlin.jupyter
32

43
import com.beust.klaxon.JsonObject
54
import com.beust.klaxon.Parser
65
import com.beust.klaxon.int
76
import com.beust.klaxon.string
8-
import org.jetbrains.kotlin.cli.common.repl.ReplCheckResult
9-
import org.jetbrains.kotlin.cli.common.repl.ReplEvalResult
10-
import org.jetbrains.kotlin.config.KotlinCompilerVersion
117
import java.io.File
128
import java.util.concurrent.atomic.AtomicLong
139
import kotlin.concurrent.thread
@@ -18,18 +14,20 @@ data class KernelArgs(val cfgFile: File,
1814
private fun parseCommandLine(vararg args: String): KernelArgs {
1915
var cfgFile: File? = null
2016
var classpath: List<File>? = null
21-
args.forEach { when {
22-
it.startsWith("-cp=") || it.startsWith("-classpath=") -> {
23-
if (classpath != null) throw IllegalArgumentException("classpath already set to ${classpath!!.joinToString(File.pathSeparator)}")
24-
classpath = it.substringAfter('=').split(File.pathSeparator).map { File(it) }
25-
}
26-
else -> {
27-
if (cfgFile != null) throw IllegalArgumentException("config file already set to $cfgFile")
28-
cfgFile = File(it)
17+
args.forEach {
18+
when {
19+
it.startsWith("-cp=") || it.startsWith("-classpath=") -> {
20+
if (classpath != null) throw IllegalArgumentException("classpath already set to ${classpath!!.joinToString(File.pathSeparator)}")
21+
classpath = it.substringAfter('=').split(File.pathSeparator).map { File(it) }
22+
}
23+
else -> {
24+
if (cfgFile != null) throw IllegalArgumentException("config file already set to $cfgFile")
25+
cfgFile = File(it)
26+
}
2927
}
30-
} }
28+
}
3129
if (cfgFile == null) throw IllegalArgumentException("config file is not provided")
32-
if (!cfgFile!!.exists() || !cfgFile!!.isFile ) throw IllegalArgumentException("invalid config file $cfgFile")
30+
if (!cfgFile!!.exists() || !cfgFile!!.isFile) throw IllegalArgumentException("invalid config file $cfgFile")
3331
return KernelArgs(cfgFile!!, classpath ?: emptyList())
3432
}
3533

@@ -49,8 +47,7 @@ fun main(vararg args: String) {
4947
signatureKey = if (sigScheme == null || key == null) "" else key,
5048
classpath = classpath
5149
))
52-
}
53-
catch (e: Exception) {
50+
} catch (e: Exception) {
5451
log.error("exception running kernel with args: \"${args.joinToString()}\"", e)
5552
}
5653
}
@@ -75,8 +72,7 @@ fun kernelServer(config: KernelConfig) {
7572
conn.control.onMessage { shellMessagesHandler(it, null, executionCount) }
7673

7774
Thread.sleep(config.pollingIntervalMillis)
78-
}
79-
catch (e: InterruptedException) {
75+
} catch (e: InterruptedException) {
8076
log.debug("Control: Interrupted")
8177
mainThread.interrupt()
8278
break
@@ -89,8 +85,7 @@ fun kernelServer(config: KernelConfig) {
8985
conn.shell.onMessage { shellMessagesHandler(it, repl, executionCount) }
9086

9187
Thread.sleep(config.pollingIntervalMillis)
92-
}
93-
catch (e: InterruptedException) {
88+
} catch (e: InterruptedException) {
9489
log.debug("Main: Interrupted")
9590
controlThread.interrupt()
9691
break
@@ -99,84 +94,9 @@ fun kernelServer(config: KernelConfig) {
9994

10095
try {
10196
controlThread.join()
97+
} catch (e: InterruptedException) {
10298
}
103-
catch (e: InterruptedException) {}
10499

105100
log.info("Shutdown server")
106101
}
107102
}
108-
109-
fun JupyterConnection.Socket.shellMessagesHandler(msg: Message, repl: ReplForJupyter?, executionCount: AtomicLong) {
110-
when (msg.header!!["msg_type"]) {
111-
"kernel_info_request" ->
112-
send(makeReplyMessage(msg, "kernel_info_reply",
113-
content = jsonObject(
114-
"protocol_version" to protocolVersion,
115-
"language" to "Kotlin",
116-
"language_version" to KotlinCompilerVersion.VERSION,
117-
"language_info" to jsonObject("name" to "kotlin", "file_extension" to "kt")
118-
)))
119-
"history_request" ->
120-
send(makeReplyMessage(msg, "history_reply",
121-
content = jsonObject(
122-
"history" to listOf<String>() // not implemented
123-
)))
124-
"shutdown_request" -> {
125-
send(makeReplyMessage(msg, "shutdown_reply", content = msg.content))
126-
Thread.currentThread().interrupt()
127-
}
128-
"connect_request" ->
129-
send(makeReplyMessage(msg, "connection_reply",
130-
content = jsonObject(JupyterSockets.values()
131-
.map { Pair("${it.name}_port", connection.config.ports[it.ordinal]) })))
132-
"execute_request" -> {
133-
connection.contextMessage = msg
134-
val count = executionCount.getAndIncrement()
135-
val startedTime = ISO8601DateNow
136-
with (connection.iopub) {
137-
send(makeReplyMessage(msg, "status", content = jsonObject("execution_state" to "busy")))
138-
val code = msg.content["code"]
139-
send(makeReplyMessage(msg, "execute_input", content = jsonObject(
140-
"execution_count" to count,
141-
"code" to code)))
142-
val res = if (isCommand(code.toString())) runCommand(code.toString(), repl)
143-
else (connection.evalWithIO { repl?.eval(count, code.toString()) ?: ReplEvalResult.Error.Runtime(emptyList(), "no repl!") }).asResult
144-
send(makeReplyMessage(msg, "execute_result", content = jsonObject(
145-
"execution_count" to count,
146-
"data" to res,
147-
"metadata" to emptyJsonObject)))
148-
send(makeReplyMessage(msg, "status", content = jsonObject("execution_state" to "idle")))
149-
}
150-
send(makeReplyMessage(msg, "execute_reply",
151-
metadata = jsonObject(
152-
"dependencies_met" to true,
153-
"engine" to msg.header["session"],
154-
"status" to "ok",
155-
"started" to startedTime),
156-
content = jsonObject(
157-
"status" to "ok",
158-
"execution_count" to count,
159-
"user_variables" to JsonObject(),
160-
"payload" to listOf<String>(),
161-
"user_expressions" to JsonObject())
162-
))
163-
connection.contextMessage = null
164-
}
165-
"is_complete_request" -> {
166-
val code = msg.content["code"].toString()
167-
val resStr = if (isCommand(code)) "complete" else {
168-
val res = repl?.checkComplete(executionCount.get(), code)
169-
when (res) {
170-
is ReplCheckResult.Error -> "invalid"
171-
is ReplCheckResult.Incomplete -> "incomplete"
172-
is ReplCheckResult.Ok -> "complete"
173-
null -> "error: no repl"
174-
else -> throw Exception("unexpected result from checkComplete call: $res")
175-
}
176-
}
177-
send(makeReplyMessage(msg, "is_complete_reply", content = jsonObject("status" to resStr)))
178-
}
179-
else -> send(makeReplyMessage(msg, "unsupported_message_reply"))
180-
}
181-
}
182-

0 commit comments

Comments
 (0)