summaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea89/website/ShellExecutionContext.kt
blob: cec0b9eefb90dc7a32f2862732154885339c907b (plain)
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
package moe.nea89.website

import kotlinx.browser.window
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.*
import kotlin.time.Duration
import kotlin.time.DurationUnit

class ShellExecutionContext(
    val console: KConsole,
    val name: String,
    val args: List<String>,
) {

    suspend fun wait(duration: Duration) {
        suspendCancellableCoroutine<Unit> {
            window.setTimeout({
                it.resume(Unit)
            }, timeout = duration.toInt(DurationUnit.MILLISECONDS))
        }
    }

    suspend fun exit(): Nothing {
        suspendCancellableCoroutine<Unit> {
            it.cancel()
            console.state = KConsole.ConsoleState.SHELLPROMPT
            console.rerender()
        }
        throw RuntimeException("THIs shOULDNT EXIST")
    }

    companion object {
        fun run(
            console: KConsole, command: Command, name: String, args: List<String>
        ) {
            console.state = KConsole.ConsoleState.IN_PROGRAM
            val se = ShellExecutionContext(console, name, args)
            command.runner.createCoroutine(se, object : Continuation<Unit> {
                override val context: CoroutineContext
                    get() = EmptyCoroutineContext

                override fun resumeWith(result: Result<Unit>) {
                    console.state = KConsole.ConsoleState.SHELLPROMPT
                    console.rerender()
                }
            }).resume(Unit)
        }
    }
}