1. 分叉 (Forking)

分叉 (Forking) 

預設情況下,run 任務與 sbt 在同一個 JVM 中執行。然而,在某些情況下需要分叉。或者,您可能想要在實作新任務時分叉 Java 程序。

預設情況下,分叉的程序會使用與建置相同的 Java 和 Scala 版本,以及目前程序的工作目錄和 JVM 選項。本頁討論如何為 runtest 任務啟用和設定分叉。每種任務都可以透過將相關的鍵範圍化 (scoping) 來單獨設定,如下所述。

啟用分叉 

fork 設定控制是否啟用分叉 (true) 或不啟用 (false)。可以在 run 範圍中設定,僅分叉 run 命令,或者在 test 範圍中設定,僅分叉 test 命令。

要分叉所有測試任務 (testtestOnlytestQuick) 和執行任務 (runrunMainTest / runTest / runMain),

fork := true

僅分叉 Compile / runCompile / runMain

Compile / run / fork := true

僅分叉 Test / runTest / runMain

Test / run / fork := true

注意: runrunMain 共用相同的組態,無法單獨設定。

要僅啟用所有 test 任務的分叉,請在 Test 範圍中將 fork 設定為 true

Test / fork := true

請參閱測試,以取得有關如何將測試分配給 JVM 以及將哪些選項傳遞給每個群組的更多控制。

變更工作目錄 

要變更分叉時的工作目錄,請設定 Compile / run / baseDirectoryTest / baseDirectory

// sets the working directory for all `run`-like tasks
run / baseDirectory := file("/path/to/working/directory/")

// sets the working directory for `run` and `runMain` only
Compile / run / baseDirectory := file("/path/to/working/directory/")

// sets the working directory for `Test / run` and `Test / runMain` only
Test / run / baseDirectory := file("/path/to/working/directory/")

// sets the working directory for `test`, `testQuick`, and `testOnly`
Test / baseDirectory := file("/path/to/working/directory/")

分叉的 JVM 選項 

要指定要提供給分叉的 JVM 的選項,請設定 javaOptions

run / javaOptions += "-Xmx8G"

或指定組態以僅影響主要或測試 run 任務

Test / run / javaOptions += "-Xmx8G"

或僅影響 test 任務

Test / javaOptions += "-Xmx8G"

Java Home 

透過設定 javaHome 目錄來選擇要使用的 Java 安裝

javaHome := Some(file("/path/to/jre/"))

請注意,如果這是全域設定,它也會設定用於編譯 Java 原始碼的 Java 安裝。您可以將其限制為僅在 run 範圍中設定來執行

run / javaHome := Some(file("/path/to/jre/"))

與其他設定一樣,您可以指定組態以僅影響主要或測試 run 任務或僅影響 test 任務。

設定輸出 

預設情況下,分叉的輸出會傳送到記錄器,標準輸出記錄在 Info 層級,標準錯誤記錄在 Error 層級。這可以使用 outputStrategy 設定來設定,其類型為 OutputStrategy

// send output to the build's standard output and error
outputStrategy := Some(StdoutOutput)

// send output to the provided OutputStream `someStream`
outputStrategy := Some(CustomOutput(someStream: OutputStream))

// send output to the provided Logger `log` (unbuffered)
outputStrategy := Some(LoggedOutput(log: Logger))

// send output to the provided Logger `log` after the process terminates
outputStrategy := Some(BufferedOutput(log: Logger))

與其他設定一樣,這可以針對主要或測試 run 任務或針對 test 任務單獨設定。

設定輸入 

預設情況下,sbt 程序的標準輸入不會轉發到分叉的程序。要啟用此功能,請設定 connectInput 設定

run / connectInput := true

直接使用 

要分叉新的 Java 程序,請使用 Fork API。感興趣的值是 Fork.javaFork.javacFork.scalaFork.scalac。這些類型為 Fork,並提供 applyfork 方法。例如,要分叉新的 Java 程序,

val options = ForkOptions(...)
val arguments: Seq[String] = ...
val mainClass: String = ...
val exitCode: Int = Fork.java(options, mainClass +: arguments)

ForkOptions 定義要使用的 Java 安裝、工作目錄、環境變數等等。例如,

val cwd: File = ...
val javaDir: File = ...
val options = ForkOptions(
   envVars = Map("KEY" -> "value"),
   workingDirectory = Some(cwd),
   javaHome = Some(javaDir)
)