我正在运行playframework应用程序,并且试图在playframework运行挂钩中运行sbt
任务。该任务来自我编写的自定义sbt插件。我很难将设置键传递给任务,该任务使用默认设置,而不是我在build.sbt
文件中定义的设置。我在做什么错了?
plugins.sbt:
addSbtPlugin("com.myorg" % "sbt-twirl-renderer" % "0.0.0")
build.sbt:
lazy val root = (project in file("."))
.enablePlugins(PlayScala, SbtWeb, TwirlTemplateRendererPlugin)
....
import play.sbt.PlayRunHook
val onAppStated: State => PlayRunHook = state => PlayRunHook.makeRunHookFromOnStarted { address =>
appPath := "/myAppPath" <======= defined setting in build.sbt
appPort := address.getPort <===
outputDirectory := "./some_folder" <===
outputFileName := "auto_generated.html" <===
Project.runTask(renderTwirl, state)
}
PlayKeys.playRunHooks += onAppStated(state.value)
插件代码:
object TwirlTemplateRendererPlugin extends AutoPlugin {
object autoImport {
val appPath = settingKey[String]("Application url base path")
val appPort = settingKey[Int]("Application port")
val outputDirectory = settingKey[String]("Generated file output directory")
val outputFileName = settingKey[String]("Generated file name")
val renderTwirl = taskKey[Unit]("Renders twirl template")
}
import autoImport._
override lazy val projectSettings = Seq(
appPath := "", <======= default setting in the plugin's code
appPort := 9000, <===
outputDirectory := "", <===
outputFileName := "", <===
renderTwirl := {
doRender(appPath.value, appPort.value, outputDirectory.value, outputFileName.value)
}
)
private def doRender(path: String, port: Int, dir: String, file: String): Unit = {
val htmlContent = getHtmlContentWithHttpRequest(port, path)
createDir(dir)
createFile(htmlContent, dir, file)
}
private def getHtmlContentWithHttpRequest(port: Int, path: String): String = {
val url = s"http://localhost:$port" + (if (path.startsWith("/")) path else s"/$path")
val connection = new URL(url).openConnection.asInstanceOf[HttpURLConnection]
connection.setConnectTimeout(120000)
connection.setReadTimeout(120000)
connection.setRequestMethod("GET")
val inputStream = connection.getInputStream
val content = scala.io.Source.fromInputStream(inputStream).mkString
if (inputStream != null) inputStream.close()
content
}
private def createDir(dir: String) = {
val directory = new File(dir)
if (!directory.exists()) {
directory.mkdir()
}
}
private def createFile(content: String, dir: String, file: String) = {
Files.write(Paths.get(s"$dir/$file"), content.getBytes(StandardCharsets.UTF_8))
}
}