代码之家  ›  专栏  ›  技术社区  ›  Luis Miguel Mejía Suárez

将JAR添加到SBT任务运行时

  •  1
  • Luis Miguel Mejía Suárez  · 技术社区  · 7 年前

    Im编写sbt任务以生成一些托管源,为此,Im使用 fast-classpath-scanner 提取全部 子类 scapegoat inspection class

    我首先把它作为一个普通的 scala project 它确实起到了作用,但当试图将其作为 SBT任务 我有一个问题,那就是替罪羊罐子不在 类路径 ,因此类路径扫描程序失败。

    我在 project/plugins.sbt 文件

    //adding the generation task dependencies
    libraryDependencies ++= Seq(
      "com.sksamuel.scapegoat" %% "scalac-scapegoat-plugin" % "1.3.4",
      "io.github.lukehutch" % "fast-classpath-scanner" % "2.18.1"
    )
    

    我在 build.sbt 文件:

    //source generator task (simplified)
    sourceGenerators in Compile += Def.task {
      //_root_ is needed because there is a sbt.io package in scope
      import _root_.io.github.lukehutch.fastclasspathscanner.FastClasspathScanner
      import _root_.io.github.lukehutch.fastclasspathscanner.matchprocessor.SubclassMatchProcessor
      import com.sksamuel.scapegoat.Inspection
      import scala.collection.mutable
    
      val inspectionClass = classOf[Inspection]
      val fastCPScanner = new FastClasspathScanner(inspectionClass.getPackage.getName)
      val inspections = mutable.ListBuffer.empty[Inspection]
      fastCPScanner
        .matchSubclassesOf(
          inspectionClass,
          new SubclassMatchProcessor[Inspection] {
            override def processMatch(matchingClass: Class[_ <: Inspection]): Unit = {
              inspections += matchingClass.newInstance()
              println("Hello World")
            }
          }
        ).scan()
    
      val lines = inspections.toList.zipWithIndex map {
        case (inspection, idx) => s"${inspections.text} -> ${idx}"
      }
    
      val scapegoatInspectionsFile = (sourceManaged in Compile).value / "scapegoat" / "inspections.scala"
      IO.writeLines(scapegoatInspectionsFile, lines)
      Seq(scapegoatInspectionsFile)
    }.taskValue
    

    注: 任务可以完美地编译和运行,问题是生成的文件是空的,因为扫描仪找不到任何检查。这可以确认,因为 print("Hello world") 中的语句 processMatch 方法未执行 (控制台中无输出)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Luis Miguel Mejía Suárez    7 年前

    我发现替罪羊罐子确实在 类路径 但由于某种原因(我不理解),可能与 sbt公司 类加载器机制 快速类路径扫描器 没有找到他们。

    对于任何有类似问题的人,要解决它,只需重写scanner类加载器。

     fastCPScanner
       .overrideClassLoaders(this.getClass.getClassLoader)
       (...)
       .scan()