From 4fe78e590a0f98b5ee99157e1ec828b108f6769b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=9B=BD=E6=96=8C?= Date: Sat, 7 Oct 2023 10:45:58 +0800 Subject: [PATCH] fork init --- .github/workflows/ScalaCI.yml | 76 +++++++++ .github/workflows/ci.yml | 21 --- .scalafmt.conf | 35 ++++ README.md | 6 +- build.sbt | 64 +++++--- project/plugins.sbt | 4 +- publish.sbt | 34 ---- src/main/scala/Keys.scala | 44 ----- src/main/scala/KotlinTest.scala | 35 ++-- src/main/scala/kotlin/Keys.scala | 39 +++++ .../scala/{ => kotlin}/KotlinCompile.scala | 150 +++++++++--------- .../scala/{ => kotlin}/KotlinPlugin.scala | 48 +++--- .../scala/{ => kotlin}/KotlinVersion.scala | 5 +- .../scala/{ => kotlin}/UpdateChecker.scala | 25 ++- src/main/scala/worksheet.sc | 1 - 15 files changed, 336 insertions(+), 251 deletions(-) create mode 100644 .github/workflows/ScalaCI.yml delete mode 100644 .github/workflows/ci.yml create mode 100644 .scalafmt.conf delete mode 100644 publish.sbt delete mode 100644 src/main/scala/Keys.scala create mode 100644 src/main/scala/kotlin/Keys.scala rename src/main/scala/{ => kotlin}/KotlinCompile.scala (58%) rename src/main/scala/{ => kotlin}/KotlinPlugin.scala (75%) rename src/main/scala/{ => kotlin}/KotlinVersion.scala (89%) rename src/main/scala/{ => kotlin}/UpdateChecker.scala (64%) delete mode 100644 src/main/scala/worksheet.sc diff --git a/.github/workflows/ScalaCI.yml b/.github/workflows/ScalaCI.yml new file mode 100644 index 0000000..1fa3497 --- /dev/null +++ b/.github/workflows/ScalaCI.yml @@ -0,0 +1,76 @@ +name: CI + +on: + push: + branches: + - master + tags: [ "*" ] + pull_request: + branches: + - master + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + java-version: [ 11 ] + steps: + - uses: actions/checkout@v3 + - name: Setup JDK + uses: actions/setup-java@v1 + with: + java-version: ${{ matrix.java-version }} + - name: Cache scala dependencies + uses: coursier/cache-action@v6 + + - name: Checking Code style + run: sbt check + + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Setup JDK + uses: actions/setup-java@v1 + with: + java-version: 11 + + - name: Run Test + if: success() || failure() + run: sbt coverage test + + - name: Aggregate coverage report + run: sbt coverageAggregate + + - name: Upload test coverage report + run: bash <(curl -s https://codecov.io/bash) + + publish: + runs-on: ubuntu-latest + needs: [ check ] + if: github.event_name != 'pull_request' + steps: + - name: Checkout current branch + uses: actions/checkout@v3.3.0 + with: + fetch-depth: 0 + - name: Setup JDK + uses: actions/setup-java@v1 + with: + java-version: 11 + + - name: Release artifacts + run: sbt ci-release + env: + PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} + PGP_SECRET: ${{ secrets.PGP_SECRET }} + SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} + SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} + + ci: + runs-on: ubuntu-latest + needs: [ check, test ] + steps: + - name: Aggregate outcomes + run: echo "build succeeded" \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index cba7ae8..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: CI -on: - pull_request: - push: -jobs: - build: - runs-on: ubuntu-latest - env: - JFROG_TOKEN: ${{ secrets.JFROG_TOKEN }} - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup JDK - uses: actions/setup-java@v3 - with: - distribution: temurin - java-version: 17 - - name: Build and Test - run: sbt compile scripted - - name: Publish - run: sbt publish \ No newline at end of file diff --git a/.scalafmt.conf b/.scalafmt.conf new file mode 100644 index 0000000..03e1d81 --- /dev/null +++ b/.scalafmt.conf @@ -0,0 +1,35 @@ +version = "3.7.13" +runner.dialect = scala3 +maxColumn = 120 +align.preset = more +lineEndings = preserve +align.stripMargin = false +docstrings.style = AsteriskSpace +docstrings.oneline = keep +continuationIndent.defnSite = 2 +danglingParentheses.preset = true +spaces.inImportCurlyBraces = true +indentOperator.exemptScope = aloneArgOrBody +includeCurlyBraceInSelectChains = false +align.openParenDefnSite = false +optIn.annotationNewlines = true +rewriteTokens = { + "⇒": "=>" + "→": "->" + "←": "<-" +} +rewrite.rules = [Imports] +rewrite.imports.sort = scalastyle +rewrite.imports.groups = [ + ["java\\..*", "javax\\..*"], + ["scala\\..*"] + ["bitlap\\..*"], + ["org\\..*"], + ["com\\..*"], +] +rewrite.imports.contiguousGroups = no +newlines.topLevelStatementBlankLines = [ + { + blanks {before = 1} + } +] diff --git a/README.md b/README.md index 9d8d87c..f313edb 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ # sbt-kotlin-plugin -[![Build Status](https://travis-ci.org/pfn/sbt-kotlin-plugin.svg?branch=master)](https://travis-ci.org/pfn/sbt-kotlin-plugin) +[![Build Status](https://github.com/bitlap/kotlin-plugin/actions/workflows/ScalaCI.yml/badge.svg)] Build kotlin code using sbt -Current version 2.0.0 +Current version 4.0.0 ## Install ``` -addSbtPlugin("community.flock.sbt" % "sbt-kotlin-plugin" % "3.0.1") +addSbtPlugin("org.bitlap" % "sbt-kotlin-plugin" % "4.0.0") ``` ## Usage diff --git a/build.sbt b/build.sbt index dc9de48..c5ab6bb 100644 --- a/build.sbt +++ b/build.sbt @@ -1,26 +1,42 @@ -name := "sbt-kotlin-plugin" - -organization := "community.flock.sbt" - -version := "3.0.1" - -scalacOptions ++= Seq("-deprecation","-Xlint","-feature") - -libraryDependencies ++= Seq( - "io.argonaut" %% "argonaut" % "6.2", - "org.scalaz" %% "scalaz-core" % "7.2.28" +addCommandAlias("fmt", "scalafmt") +addCommandAlias("check", "scalafmtCheckAll") + +inThisBuild( + List( + organization := "org.bitlap", + organizationName := "sbt-kotlin-plugin", + sonatypeCredentialHost := "s01.oss.sonatype.org", + sonatypeRepository := "https://s01.oss.sonatype.org/service/local", + homepage := Some(url("https://github.com/bitlap/kotlin-plugin")), + licenses := List( + "MIT" -> url("https://opensource.org/licenses/MIT") + ), + developers := List( + Developer( + id = "jxnu-liguobin", + name = "梦境迷离", + email = "dreamylost@outlook.com", + url = url("https://blog.dreamylost.cn") + ) + ) + ) ) -sbtPlugin := true - -// build info plugin - -enablePlugins(BuildInfoPlugin, SbtPlugin) - -buildInfoPackage := "kotlin" - -// scripted -scriptedLaunchOpts ++= Seq( - "-Xmx1024m", - "-Dplugin.version=" + version.value -) +lazy val `sbt-kotlin-plugin` = (project in file(".")) + .settings( + name := "sbt-kotlin-plugin", + organization := "org.bitlap", + scalacOptions ++= Seq("-deprecation", "-Xlint", "-feature"), + libraryDependencies ++= Seq( + "io.argonaut" %% "argonaut" % "6.2", + "org.scalaz" %% "scalaz-core" % "7.2.28" + ), + sbtPlugin := true, + buildInfoPackage := "kotlin", + // scripted + scriptedLaunchOpts ++= Seq( + "-Xmx1024m", + "-Dplugin.version=" + version.value + ) + ) + .enablePlugins(BuildInfoPlugin, SbtPlugin) diff --git a/project/plugins.sbt b/project/plugins.sbt index d5d7bbc..f47dcfe 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,4 +1,6 @@ libraryDependencies += "org.scala-sbt" %% "scripted-plugin" % sbtVersion.value addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.9.0") -addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2") \ No newline at end of file +addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2") +addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.12") +addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.2") \ No newline at end of file diff --git a/publish.sbt b/publish.sbt deleted file mode 100644 index a0563b4..0000000 --- a/publish.sbt +++ /dev/null @@ -1,34 +0,0 @@ -ThisBuild / organization := "community.flock.sbt" -ThisBuild / organizationName := "sbt-kotlin-plugin" -ThisBuild / organizationHomepage := Some(url("https://flock.community")) - -ThisBuild / scmInfo := Some( - ScmInfo( - url("https://github.com/flock-community/kotlin-plugin"), - "scm:git@github.com:flock-community/kotlin-plugin.git" - ) -) -ThisBuild / developers := List( - Developer( - id = "Veelenturf", - name = "Willem Veelenturf", - email = "willem.veelenturf@flock.community", - url = url("https://flock.community") - ) -) - -ThisBuild / description := "Sbt Kotlin plugin" -ThisBuild / licenses := List( - "MIT" -> url("http://opensource.org/licenses/MIT") -) - -ThisBuild / homepage := Some(url("https://github.com/flock-community/kotlin-plugin")) - -// Remove all additional repository other than Maven Central from POM -ThisBuild / pomIncludeRepository := { _ => false } -ThisBuild / publishTo := { - val nexus = "https://s01.oss.sonatype.org/" - if (isSnapshot.value) Some("snapshots" at nexus + "content/repositories/snapshots") - else Some("releases" at nexus + "service/local/staging/deploy/maven2") -} -ThisBuild / publishMavenStyle := true \ No newline at end of file diff --git a/src/main/scala/Keys.scala b/src/main/scala/Keys.scala deleted file mode 100644 index 51cfdc8..0000000 --- a/src/main/scala/Keys.scala +++ /dev/null @@ -1,44 +0,0 @@ -package kotlin - -import sbt._ - -/** - * @author pfnguyen - */ -object Keys { - sealed trait KotlinCompileOrder - - val Kotlin = config("kotlin") - val KotlinInternal = config("kotlin-internal").hide - - val updateCheck = TaskKey[Unit]("update-check", "check for a new version of the plugin") - val kotlinCompile = TaskKey[Unit]("kotlin-compile", - "runs kotlin compilation, occurs before normal compilation") - val kotlincPluginOptions = TaskKey[Seq[String]]("kotlinc-plugin-options", - "kotlin compiler plugin options") - val kotlinSource = SettingKey[File]("kotlin-source", "kotlin source directory") - val kotlinVersion = SettingKey[String]("kotlin-version", - "version of kotlin to use for building") - val kotlincOptions = SettingKey[Seq[String]]("kotlinc-options", - "options to pass to the kotlin compiler") - val kotlincJvmTarget = SettingKey[String]("kotlinc-jvm-target", - "jvm target to use for building") - - def kotlinLib(name: String) = sbt.Keys.libraryDependencies += - "org.jetbrains.kotlin" % ("kotlin-" + name) % kotlinVersion.value - - def kotlinPlugin(name: String) = sbt.Keys.libraryDependencies += - "org.jetbrains.kotlin" % ("kotlin-" + name) % kotlinVersion.value % "compile-internal" - - def kotlinClasspath(config: Configuration, classpathKey: Def.Initialize[sbt.Keys.Classpath]): Setting[_] = - config / kotlincOptions ++= { - "-cp" :: classpathKey.value.map(_.data.getAbsolutePath).mkString( - java.io.File.pathSeparator) :: - Nil - } - - case class KotlinPluginOptions(pluginId: String) { - def option(key: String, value: String) = - s"plugin:$pluginId:$key=$value" - } -} diff --git a/src/main/scala/KotlinTest.scala b/src/main/scala/KotlinTest.scala index 51d683c..f8e947b 100644 --- a/src/main/scala/KotlinTest.scala +++ b/src/main/scala/KotlinTest.scala @@ -1,30 +1,37 @@ package sbt import sbt.Keys.* +import sbt.internal.inc.* import sbt.internal.inc.classfile.JavaAnalyze import sbt.internal.inc.classpath.ClasspathUtil -import sbt.internal.inc.* -import xsbti.{VirtualFile, VirtualFileRef} +import xsbti.{ VirtualFile, VirtualFileRef } import xsbti.compile.* object KotlinTest { + private object EmptyLookup extends Lookup { def changedClasspathHash: Option[Vector[FileHash]] = None - def analyses: Vector[CompileAnalysis] = Vector.empty - def lookupOnClasspath(binaryClassName: String): Option[VirtualFileRef] = None - def lookupAnalysis(binaryClassName: String): Option[CompileAnalysis] = None + def analyses: Vector[CompileAnalysis] = Vector.empty + def lookupOnClasspath(binaryClassName: String): Option[VirtualFileRef] = None + def lookupAnalysis(binaryClassName: String): Option[CompileAnalysis] = None def changedBinaries(previousAnalysis: xsbti.compile.CompileAnalysis): Option[Set[VirtualFileRef]] = None - def changedSources(previousAnalysis: xsbti.compile.CompileAnalysis): Option[xsbti.compile.Changes[VirtualFileRef]] = None + + def changedSources(previousAnalysis: xsbti.compile.CompileAnalysis): Option[xsbti.compile.Changes[VirtualFileRef]] = + None def removedProducts(previousAnalysis: xsbti.compile.CompileAnalysis): Option[Set[VirtualFileRef]] = None - def shouldDoIncrementalCompilation(changedClasses: Set[String],analysis: xsbti.compile.CompileAnalysis): Boolean = true - override def hashClasspath(classpath: Array[VirtualFile]): java.util.Optional[Array[FileHash]] = java.util.Optional.empty() + + def shouldDoIncrementalCompilation(changedClasses: Set[String], analysis: xsbti.compile.CompileAnalysis): Boolean = + true + + override def hashClasspath(classpath: Array[VirtualFile]): java.util.Optional[Array[FileHash]] = + java.util.Optional.empty() } val kotlinTests = Def.task { - val out = ((Test / target).value ** "scala-*").get.head / "test-classes" + val out = ((Test / target).value ** "scala-*").get.head / "test-classes" val srcs = ((Test / sourceDirectory).value ** "*.kt").get.map(f => PlainVirtualFile(f.toPath())).toList - val xs = (out ** "*.class").get.toList + val xs = (out ** "*.class").get.toList val loader = ClasspathUtil.toLoader((Test / fullClasspath).value map { _.data @@ -37,7 +44,7 @@ object KotlinTest { val so = (Test / scalacOptions).value val jo = (Test / javacOptions).value - val c = (Test / compile).value + val c = (Test / compile).value val incremental = Incremental( srcs.toSet, @@ -59,14 +66,14 @@ object KotlinTest { None, None, None, - log, + log )((_, _, callback, _) => { def readAPI(source: VirtualFileRef, classes: Seq[Class[_]]): Set[(String, String)] = { val (apis, mainClasses, inherits) = ClassToAPI.process(classes) apis.foreach(callback.api(source, _)) mainClasses.foreach(callback.mainClass(source, _)) - inherits.map { - case (from, to) => (from.getName, to.getName) + inherits.map { case (from, to) => + (from.getName, to.getName) } } JavaAnalyze( diff --git a/src/main/scala/kotlin/Keys.scala b/src/main/scala/kotlin/Keys.scala new file mode 100644 index 0000000..b1fad75 --- /dev/null +++ b/src/main/scala/kotlin/Keys.scala @@ -0,0 +1,39 @@ +package kotlin + +import sbt._ + +/** @author + * pfnguyen + */ +object Keys { + sealed trait KotlinCompileOrder + + val Kotlin = config("kotlin") + val KotlinInternal = config("kotlin-internal").hide + + val updateCheck = TaskKey[Unit]("update-check", "check for a new version of the plugin") + val kotlinCompile = TaskKey[Unit]("kotlin-compile", "runs kotlin compilation, occurs before normal compilation") + val kotlincPluginOptions = TaskKey[Seq[String]]("kotlinc-plugin-options", "kotlin compiler plugin options") + val kotlinSource = SettingKey[File]("kotlin-source", "kotlin source directory") + val kotlinVersion = SettingKey[String]("kotlin-version", "version of kotlin to use for building") + val kotlincOptions = SettingKey[Seq[String]]("kotlinc-options", "options to pass to the kotlin compiler") + val kotlincJvmTarget = SettingKey[String]("kotlinc-jvm-target", "jvm target to use for building") + + def kotlinLib(name: String) = sbt.Keys.libraryDependencies += + "org.jetbrains.kotlin" % ("kotlin-" + name) % kotlinVersion.value + + def kotlinPlugin(name: String) = sbt.Keys.libraryDependencies += + "org.jetbrains.kotlin" % ("kotlin-" + name) % kotlinVersion.value % "compile-internal" + + def kotlinClasspath(config: Configuration, classpathKey: Def.Initialize[sbt.Keys.Classpath]): Setting[_] = + config / kotlincOptions ++= { + "-cp" :: classpathKey.value.map(_.data.getAbsolutePath).mkString(java.io.File.pathSeparator) :: + Nil + } + + case class KotlinPluginOptions(pluginId: String) { + + def option(key: String, value: String) = + s"plugin:$pluginId:$key=$value" + } +} diff --git a/src/main/scala/KotlinCompile.scala b/src/main/scala/kotlin/KotlinCompile.scala similarity index 58% rename from src/main/scala/KotlinCompile.scala rename to src/main/scala/kotlin/KotlinCompile.scala index 4195531..9590978 100644 --- a/src/main/scala/KotlinCompile.scala +++ b/src/main/scala/kotlin/KotlinCompile.scala @@ -1,20 +1,20 @@ package kotlin import java.io.File -import java.lang.reflect.{Field, Method} +import java.lang.reflect.{ Field, Method } import java.util.jar.JarEntry -import sbt.Keys.{Classpath, TaskStreams} -import sbt._ -import sbt.io._ -import sbt.internal.inc.classpath.ClasspathUtil - -import collection.JavaConverters._ +import scala.collection.JavaConverters.* import scala.math.Ordered.orderingToOrdered import scala.util.Try -/** - * @author pfnguyen +import sbt._ +import sbt.Keys.{ Classpath, TaskStreams } +import sbt.internal.inc.classpath.ClasspathUtil +import sbt.io.* + +/** @author + * pfnguyen */ object KotlinCompile { @@ -23,28 +23,32 @@ object KotlinCompile { in.entries.asScala exists pred } - lazy val kotlinMemo = scalaz.Memo.immutableHashMapMemo[Classpath, KotlinReflection](cp => - KotlinReflection.fromClasspath(cp)) - - def compile(options: Seq[String], - jvmTarget: String, - kotlinVersion: String, - sourceDirs: Seq[File], - kotlinPluginOptions: Seq[String], - classpath: Classpath, - compilerClasspath: Classpath, - output: File, s: TaskStreams): Unit = { + lazy val kotlinMemo = + scalaz.Memo.immutableHashMapMemo[Classpath, KotlinReflection](cp => KotlinReflection.fromClasspath(cp)) + + def compile( + options: Seq[String], + jvmTarget: String, + kotlinVersion: String, + sourceDirs: Seq[File], + kotlinPluginOptions: Seq[String], + classpath: Classpath, + compilerClasspath: Classpath, + output: File, + s: TaskStreams + ): Unit = { import language.reflectiveCalls val stub = KotlinStub(s, kotlinMemo(compilerClasspath)) val args = stub.compilerArgs stub.parse(kotlinVersion, args.instance, options.toList) val kotlinFiles = "*.kt" || "*.kts" - val javaFiles = "*.java" + val javaFiles = "*.java" val kotlinSources = sourceDirs.flatMap(d => (d ** kotlinFiles).get).distinct - val javaSources = sourceDirs.filterNot(f => sourceDirs.exists(f0 => - f0.relativeTo(f).isDefined && f != f0)) map (d => - (d, (d ** javaFiles).get)) filter (_._2.nonEmpty) + val javaSources = + sourceDirs.filterNot(f => sourceDirs.exists(f0 => f0.relativeTo(f).isDefined && f != f0)) map (d => + (d, (d ** javaFiles).get) + ) filter (_._2.nonEmpty) if (kotlinSources.isEmpty) { s.log.debug("No sources found, skipping kotlin compile") } else { @@ -59,15 +63,14 @@ object KotlinCompile { args.jvmTarget = jvmTarget val fcpjars = classpath.map(_.data.getAbsoluteFile) val (pluginjars, cpjars) = fcpjars.partition { - grepjar(_)(_.getName.startsWith( - "META-INF/services/org.jetbrains.kotlin.compiler.plugin")) + grepjar(_)(_.getName.startsWith("META-INF/services/org.jetbrains.kotlin.compiler.plugin")) } - val cp = cpjars.mkString(File.pathSeparator) + val cp = cpjars.mkString(File.pathSeparator) val pcp = pluginjars.map(_.getAbsolutePath).toArray args.classpath = Option(args.classpath[String]).fold(cp)(_ + File.pathSeparator + cp) args.pluginClasspaths = Option(args.pluginClasspaths[Array[String]]).fold(pcp)(_ ++ pcp) - args.pluginOptions = Option(args.pluginOptions[Array[String]]).fold( - kotlinPluginOptions.toArray)(_ ++ kotlinPluginOptions.toArray[String]) + args.pluginOptions = Option(args.pluginOptions[Array[String]]) + .fold(kotlinPluginOptions.toArray)(_ ++ kotlinPluginOptions.toArray[String]) output.mkdirs() args.destination = output.getAbsolutePath stub.compile(args.instance) @@ -76,25 +79,22 @@ object KotlinCompile { } object KotlinReflection { + def fromClasspath(cp: Classpath): KotlinReflection = { - val cl = ClasspathUtil.toLoader(cp.map(_.data)) - val compilerClass = cl.loadClass("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler") - val servicesClass = cl.loadClass("org.jetbrains.kotlin.config.Services") - val messageCollectorClass = cl.loadClass("org.jetbrains.kotlin.cli.common.messages.MessageCollector") + val cl = ClasspathUtil.toLoader(cp.map(_.data)) + val compilerClass = cl.loadClass("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler") + val servicesClass = cl.loadClass("org.jetbrains.kotlin.config.Services") + val messageCollectorClass = cl.loadClass("org.jetbrains.kotlin.cli.common.messages.MessageCollector") val commonCompilerArgsClass = cl.loadClass("org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments") val compilerExec = Try( - compilerClass.getMethod("exec", - messageCollectorClass, servicesClass, commonCompilerArgsClass) - ).toOption.getOrElse { - - val commonToolArguments = cl.loadClass( - "org.jetbrains.kotlin.cli.common.arguments.CommonToolArguments") - val clitool = cl.loadClass( - "org.jetbrains.kotlin.cli.common.CLITool") - clitool.getMethod("exec", - messageCollectorClass, servicesClass, commonToolArguments) - } + compilerClass.getMethod("exec", messageCollectorClass, servicesClass, commonCompilerArgsClass) + ).toOption.getOrElse { + + val commonToolArguments = cl.loadClass("org.jetbrains.kotlin.cli.common.arguments.CommonToolArguments") + val clitool = cl.loadClass("org.jetbrains.kotlin.cli.common.CLITool") + clitool.getMethod("exec", messageCollectorClass, servicesClass, commonToolArguments) + } KotlinReflection( cl, @@ -104,20 +104,26 @@ object KotlinReflection { messageCollectorClass, commonCompilerArgsClass, compilerExec, - servicesClass.getDeclaredField("EMPTY")) + servicesClass.getDeclaredField("EMPTY") + ) } } -case class KotlinReflection(cl: ClassLoader, - servicesClass: Class[_], - compilerClass: Class[_], - compilerArgsClass: Class[_], - messageCollectorClass: Class[_], - commonCompilerArgsClass: Class[_], - compilerExec: Method, - servicesEmptyField: Field) + +case class KotlinReflection( + cl: ClassLoader, + servicesClass: Class[_], + compilerClass: Class[_], + compilerArgsClass: Class[_], + messageCollectorClass: Class[_], + commonCompilerArgsClass: Class[_], + compilerExec: Method, + servicesEmptyField: Field +) + case class KotlinStub(s: TaskStreams, kref: KotlinReflection) { + + import kref.* import language.reflectiveCalls - import kref._ def messageCollector: AnyRef = { type CompilerMessageLocation = { @@ -126,20 +132,21 @@ case class KotlinStub(s: TaskStreams, kref: KotlinReflection) { def getColumn: Int } - import java.lang.reflect.{Proxy, InvocationHandler} + import java.lang.reflect.{ InvocationHandler, Proxy } val messageCollectorInvocationHandler = new InvocationHandler { override def invoke(proxy: scala.Any, method: Method, args: Array[AnyRef]) = { if (method.getName == "report") { val Array(severity, message, location) = args - val l = location.asInstanceOf[CompilerMessageLocation] - val msg = Option(l).map(x => x.getPath).fold(message.toString)(loc => - loc + ": " + l.getLine + ", " + l.getColumn + ": " + message) + val l = location.asInstanceOf[CompilerMessageLocation] + val msg = Option(l) + .map(x => x.getPath) + .fold(message.toString)(loc => loc + ": " + l.getLine + ", " + l.getColumn + ": " + message) severity.toString match { - case "INFO" => s.log.info(msg) - case "WARNING" => s.log.warn(msg) - case "STRONG_WARNING" => s.log.warn(msg) - case "ERROR" | "EXCEPTION" => s.log.error(msg) - case "OUTPUT" | "LOGGING" => s.log.debug(msg) + case "INFO" => s.log.info(msg) + case "WARNING" => s.log.warn(msg) + case "STRONG_WARNING" => s.log.warn(msg) + case "ERROR" | "EXCEPTION" => s.log.error(msg) + case "OUTPUT" | "LOGGING" => s.log.debug(msg) } } null @@ -158,7 +165,7 @@ case class KotlinStub(s: TaskStreams, kref: KotlinReflection) { val commonToolArguments = cl.loadClass( "org.jetbrains.kotlin.cli.common.arguments.CommonToolArguments" ) - import collection.JavaConverters._ + import collection.JavaConverters.* if (KotlinVersion(kotlinVersion) < KotlinVersion("1.7.0")) { val parserMethod = parser.getMethod( "parseCommandLineArguments", @@ -181,24 +188,24 @@ case class KotlinStub(s: TaskStreams, kref: KotlinReflection) { import language.dynamics new Dynamic { def withFirstUpper(string: String): String = string.head.toUpper + string.tail - def getterName(field: String) = s"get${withFirstUpper(field)}" - def setterName(field: String) = s"set${withFirstUpper(field)}" + def getterName(field: String) = s"get${withFirstUpper(field)}" + def setterName(field: String) = s"set${withFirstUpper(field)}" def selectDynamic[A](field: String): A = { val methodName = getterName(field) - val getterOpt = compilerArgsClass.getMethods.find(_.getName == methodName) + val getterOpt = compilerArgsClass.getMethods.find(_.getName == methodName) getterOpt match { case Some(getter) => getter.invoke(instance).asInstanceOf[A] - case None => compilerArgsClass.getField(field).get(instance).asInstanceOf[A] + case None => compilerArgsClass.getField(field).get(instance).asInstanceOf[A] } } def updateDynamic(field: String)(value: Any): Unit = { val methodName = setterName(field) - val setterOpt = compilerArgsClass.getMethods.find(_.getName == methodName) + val setterOpt = compilerArgsClass.getMethods.find(_.getName == methodName) setterOpt match { case Some(setter) => setter.invoke(instance, value.asInstanceOf[Object]) - case None => compilerArgsClass.getField(field).set(instance, value) + case None => compilerArgsClass.getField(field).set(instance, value) } } @@ -208,8 +215,7 @@ case class KotlinStub(s: TaskStreams, kref: KotlinReflection) { def compile(args: AnyRef): Unit = { val compiler = compilerClass.getDeclaredConstructor().newInstance() - val result = compilerExec.invoke(compiler, - messageCollector, servicesEmptyField.get(null), args: java.lang.Object) + val result = compilerExec.invoke(compiler, messageCollector, servicesEmptyField.get(null), args: java.lang.Object) result.toString match { case "COMPILATION_ERROR" | "INTERNAL_ERROR" => throw new MessageOnlyException("Compilation failed. See log for more details") diff --git a/src/main/scala/KotlinPlugin.scala b/src/main/scala/kotlin/KotlinPlugin.scala similarity index 75% rename from src/main/scala/KotlinPlugin.scala rename to src/main/scala/kotlin/KotlinPlugin.scala index 7254fba..777db61 100644 --- a/src/main/scala/KotlinPlugin.scala +++ b/src/main/scala/kotlin/KotlinPlugin.scala @@ -1,15 +1,15 @@ package kotlin -import Keys._ -import sbt._ -import sbt.Keys._ +import kotlin.Keys.* +import sbt.{ Keys => _, _ } +import sbt.Keys.* import sbt.plugins.JvmPlugin -/** - * @author pfnguyen +/** @author + * pfnguyen */ object KotlinPlugin extends AutoPlugin { - override def trigger = allRequirements + override def trigger = allRequirements override def requires = JvmPlugin override def projectConfigurations = KotlinInternal :: Nil @@ -51,16 +51,17 @@ object KotlinPlugin extends AutoPlugin { if (BuildInfo.version != current) { log.warn( s"UPDATE: A newer sbt-kotlin-plugin is available:" + - s" $current, currently running: ${BuildInfo.version}") + s" $current, currently running: ${BuildInfo.version}" + ) } } } }, - kotlinVersion := "1.3.50", - kotlincJvmTarget := "1.8", - kotlincOptions := Nil, + kotlinVersion := "1.3.50", + kotlincJvmTarget := "1.8", + kotlincOptions := Nil, kotlincPluginOptions := Nil, - watchSources ++= { + watchSources ++= { import language.postfixOps val kotlinSources = "*.kt" || "*.kts" (Compile / sourceDirectories).value.flatMap(_ ** kotlinSources get) ++ @@ -74,18 +75,23 @@ object KotlinPlugin extends AutoPlugin { // public to allow kotlin compile in other configs beyond Compile and Test val kotlinCompileSettings = List( unmanagedSourceDirectories += kotlinSource.value, - kotlincOptions := kotlincOptions.value, - kotlincJvmTarget := kotlincJvmTarget.value, + kotlincOptions := kotlincOptions.value, + kotlincJvmTarget := kotlincJvmTarget.value, kotlincPluginOptions := kotlincPluginOptions.value, kotlinCompile := Def.task { - KotlinCompile.compile(kotlincOptions.value, - kotlincJvmTarget.value, - kotlinVersion.value, - sourceDirectories.value, kotlincPluginOptions.value, - dependencyClasspath.value, (KotlinInternal / managedClasspath).value, - classDirectory.value, streams.value) - }.dependsOn (Compile / compile / compileInputs).value, - compile := (compile dependsOn kotlinCompile).value, + KotlinCompile.compile( + kotlincOptions.value, + kotlincJvmTarget.value, + kotlinVersion.value, + sourceDirectories.value, + kotlincPluginOptions.value, + dependencyClasspath.value, + (KotlinInternal / managedClasspath).value, + classDirectory.value, + streams.value + ) + }.dependsOn(Compile / compile / compileInputs).value, + compile := (compile dependsOn kotlinCompile).value, kotlinSource := sourceDirectory.value / "kotlin", Test / definedTests ++= KotlinTest.kotlinTests.value ) diff --git a/src/main/scala/KotlinVersion.scala b/src/main/scala/kotlin/KotlinVersion.scala similarity index 89% rename from src/main/scala/KotlinVersion.scala rename to src/main/scala/kotlin/KotlinVersion.scala index 9786030..2db2c32 100644 --- a/src/main/scala/KotlinVersion.scala +++ b/src/main/scala/kotlin/KotlinVersion.scala @@ -1,10 +1,9 @@ package kotlin -import scala.math.Ordering - case class KotlinVersion(versionString: String) extends AnyVal object KotlinVersion { + implicit val versionOrdering: Ordering[KotlinVersion] = Ordering.by { _.versionString.split("[.-]").map(_.toInt).toIterable } -} \ No newline at end of file +} diff --git a/src/main/scala/UpdateChecker.scala b/src/main/scala/kotlin/UpdateChecker.scala similarity index 64% rename from src/main/scala/UpdateChecker.scala rename to src/main/scala/kotlin/UpdateChecker.scala index 532196f..6f76ab6 100644 --- a/src/main/scala/UpdateChecker.scala +++ b/src/main/scala/kotlin/UpdateChecker.scala @@ -1,28 +1,27 @@ package kotlin -import java.io.{InputStreamReader, BufferedReader, StringWriter} - -import argonaut._, Argonaut._ +import java.io.* import scala.concurrent.Future -import scala.util.{Failure, Success} +import scala.util.{ Failure, Success } + +import argonaut.* +import argonaut.Argonaut.* object UpdateChecker { import scala.concurrent.ExecutionContext.Implicits.global - type Result = (Set[String],String) - type Callback[A] = Either[Throwable,Result] => A + type Result = (Set[String], String) + type Callback[A] = Either[Throwable, Result] => A def apply[A](user: String, repo: String, name: String)(result: Callback[A]): Unit = { - val bintray = new java.net.URL( - s"https://api.bintray.com/packages/$user/$repo/$name") + val bintray = new java.net.URL(s"https://api.bintray.com/packages/$user/$repo/$name") Future { val uc = bintray.openConnection() val in = new BufferedReader(new InputStreamReader(uc.getInputStream, "utf-8")) try { - val sw = new StringWriter + val sw = new StringWriter val buf = Array.ofDim[Char](8192) - Stream.continually(in.read(buf, 0, 8192)) takeWhile ( - _ != -1) foreach (sw.write(buf, 0, _)) + Stream.continually(in.read(buf, 0, 8192)) takeWhile (_ != -1) foreach (sw.write(buf, 0, _)) sw.toString } finally { in.close() @@ -43,8 +42,8 @@ object UpdateChecker { } } - implicit def PackageInfoCodecJson: CodecJson[PackageInfo] = casecodec3( - PackageInfo.apply, PackageInfo.unapply)("name", "latest_version", "versions") + implicit def PackageInfoCodecJson: CodecJson[PackageInfo] = + casecodec3(PackageInfo.apply, PackageInfo.unapply)("name", "latest_version", "versions") case class PackageInfo(name: String, version: String, versions: List[String]) } diff --git a/src/main/scala/worksheet.sc b/src/main/scala/worksheet.sc deleted file mode 100644 index e7b9b3c..0000000 --- a/src/main/scala/worksheet.sc +++ /dev/null @@ -1 +0,0 @@ -/Users/willemveelenturf/projects/sbt/sbt-kotlin-plugin/src/main/scala \ No newline at end of file