52

我希望能够使用-Xfatal-warningsand -Ywarn-unused-import,问题是编译器在包含我的应用程序播放路径的文件上触发了错误:

[error] /path/to/app/conf/routes: Unused import
[error] /path/to/app/conf/routes: Unused import
[error] /path/to/app/conf/routes:1: Unused import
[error] GET        /document/:id        my.app.controllers.MyController.getById(id: Int)

其他路线也是如此。

是否有可能告诉 scalac 忽略文件?

斯卡拉版本是2.11.8.

4

5 回答 5

5

我刚刚在 Scala 2.12 和 Play 2.6(您现在可能正在使用)中遇到了同样的问题。

一个名为 Silencer 的 Scala 编译器插件对其进行了整理: https ://github.com/ghik/silencer

将以下依赖项添加到 build.sbt 中:

val silencerVersion = "1.2.1"

libraryDependencies ++= Seq(
    compilerPlugin("com.github.ghik" %% "silencer-plugin" % silencerVersion),
    "com.github.ghik" %% "silencer-lib" % silencerVersion % Provided
)

然后添加(也在 build.sbt 中):

scalacOptions += "-P:silencer:globalFilters=Unused import"

后面的文本globalFilters=是编译器警告静音的正则表达式匹配列表,可以用逗号分隔。您可能需要根据自己的情况调整正则表达式,但我发现上面的示例运行良好。

这确实意味着它会消除任何“未使用的导入”警告,但如果您习惯于自动格式化代码(ctrl+alt+L在 Intellij 中),包括整理未使用的导入,那么它应该不会造成问题。

于 2018-10-09T11:06:28.730 回答
4

一个可怕的“解决方案”可能是在生成路由之后但在编译任务运行之前删除那些未使用的导入。这是一个草图:

lazy val optimizeRoutesImports = taskKey[Unit]("Remove unused imports from generated routes sources.")

optimizeRoutesImports := {

  def removeUnusedImports(targetFiles: (File) => PathFinder, linesToRemove: Set[String], linesToReplace: Map[String, String]) = {
    val files = targetFiles(crossTarget.value).get
    files foreach { file =>
      val lines = sbt.IO.readLines(file)
      val updatedLines = lines map { line =>
        linesToReplace.getOrElse(line, line)
      } filterNot { line =>
        linesToRemove.contains(line.trim)
      }
      sbt.IO.writeLines(file, updatedLines, append = false)
    }
  }

  removeUnusedImports(
    _ / "routes" / "main" / "controllers" / "ReverseRoutes.scala",
    Set("import ReverseRouteContext.empty"),
    Map(
      "import play.api.mvc.{ QueryStringBindable, PathBindable, Call, JavascriptLiteral }" ->
        "import play.api.mvc.{ QueryStringBindable, PathBindable, Call }",
      "import play.core.routing.{ HandlerDef, ReverseRouteContext, queryString, dynamicString }" ->
        "import play.core.routing.{ ReverseRouteContext, queryString, dynamicString }"
    )
  )

  removeUnusedImports(
    _ / "routes" / "main" / "controllers" / "javascript" / "JavaScriptReverseRoutes.scala",
    Set(
      "import play.core.routing.{ HandlerDef, ReverseRouteContext, queryString, dynamicString }",
      "import ReverseRouteContext.empty"
    ),
    Map(
      "import play.api.mvc.{ QueryStringBindable, PathBindable, Call, JavascriptLiteral }" ->
        "import play.api.mvc.{ QueryStringBindable, PathBindable }"
    )
  )

  removeUnusedImports(
    _ / "routes" / "main" / "router" / "Routes.scala",
    Set("import play.core.j._"),
    Map())
}

然后,您需要整理任务依赖项:

// Our optimize routes imports task depends on the routes task.
optimizeRoutesImports := (optimizeRoutesImports dependsOn (play.sbt.routes.RoutesKeys.routes in Compile)).value

// And compilation depends on the unused routes having been removed.
compile := ((compile in Compile) dependsOn optimizeRoutesImports).value

TwirlKeys.templateImports在启用-Ywarn-unused-import. 像这样,取决于您的视图中使用的类型:

TwirlKeys.templateImports := Seq("play.api.mvc._", "play.api.i18n.Messages", "controllers.routes")

我还必须TemplateMagic从 Twirl 模板 (YMMV) 中剔除未使用的导入:

  removeUnusedImports(
    _ / "twirl" ** "*.template.scala",
    Set("import play.twirl.api.TemplateMagic._"),
    Map())

如果这样做,请确保正确设置了任务依赖项。

这对我有用。Scala 2.11.8,Play 2.5.10,两者都-Xfatal-warnings启用-Ywarn-unused-import。这很可怕,但它有效。

于 2017-01-17T00:12:11.117 回答
3

我已经为 Play 2.8.11 的 Scala 2.13.7(不需要任何插件)提出了一个可行的解决方案。查看这些示例并根据您的需要进行调整:

scalacOptions ++= Seq(
    "-Wconf:cat=unused-imports&site=.*views.html.*:s", // Silence import warnings in Play html files
    "-Wconf:cat=unused-imports&site=<empty>:s", // Silence import warnings on Play `routes` files
    "-Wconf:cat=unused-imports&site=router:s", // Silence import warnings on Play `routes` files
    "-Wconf:cat=unused-imports&site=v1:s", // Silence import warnings on Play `v1.routes` files
    "-Wconf:cat=unused-imports&site=v2:s", // Silence import warnings on Play `v2.routes` files
    "-Wconf:cat=unused-imports&site=views.v1:s", // Silence import warnings on Play `views.v1.routes` files
    "-Wconf:cat=deprecation&site=controllers\\.v1.*&origin=scala.util.Either.right:s", // Silence deprecations in generated Controller classes
    "-Wconf:cat=deprecation&site=.*v1.Routes.*&origin=scala.util.Either.right:s"
  ) // Silence deprecations in generated Controller classes

如果您想了解更多信息,请查看此文档并在编译器消息输出中添加详细信息

scalacOptions += "-Wconf:any:wv",

专业提示:仅在 CI 中未使用的编译失败

scalacOptions ++= {
  // Mark unused errors as info for local development (due to -Werror usage)
  if (insideCI.value) Seq.empty else Seq("-Wconf:cat=unused:i")
},
于 2021-12-20T06:49:15.117 回答
0

也有这个问题。基本上 Scala 2.12.13 或 2.13.x 将 Silencer 代码合并到它们的 -Wconf 编译器标志中,请参见此处

例子:

scalacOptions += "-Wconf:cat=unused-imports:s"

可以将此规则限制为某些源文件,例如路由(请参阅 doc),但我尝试时没有运气。

对于以前版本的 Scala,您应该使用 Silencer 插件:

scalacOptions += "-P:silencer:pathFilters=views;routes",
于 2021-10-19T15:27:44.390 回答
0

这是另一种选择(可能不如丹尼尔尼克松)

我将以下内容添加到build.sbt

import CustomGenerator._

import play.sbt.routes.RoutesKeys
RoutesKeys.routesImport := Seq.empty
routesGenerator := ModifiedInjectedRoutesGenerator

然后将此添加到project/CustomGenerator.scala(始终是顶级project/):

object CustomGenerator {
  object ModifiedInjectedRoutesGenerator extends play.routes.compiler.RoutesGenerator {
    import play.routes.compiler._
    import play.routes.compiler.RoutesCompiler.RoutesCompilerTask

    def generate(task: RoutesCompilerTask, namespace: Option[String], rules: List[Rule]): Seq[(String, String)] = {
      play.routes.compiler.InjectedRoutesGenerator.generate(task, namespace, rules) map { case(key, value) =>
        var v = value
        if(key.endsWith("/ReverseRoutes.scala")) {
          v = v.replace("import ReverseRouteContext.empty", "implicit val empty = ReverseRouteContext(Map())")
          v = v.replace("import play.core.routing.{ HandlerDef, ReverseRouteContext, queryString, dynamicString }", "import play.core.routing.{ ReverseRouteContext, queryString }")
          v = v.replace("import play.api.mvc.{ QueryStringBindable, PathBindable, Call, JavascriptLiteral }", "import play.api.mvc.{ QueryStringBindable, Call }")
        }
        if(key.endsWith("migrations/ReverseRoutes.scala")) {
          v = v.replace("import play.api.mvc.{ QueryStringBindable, Call }", "import play.api.mvc.{ Call }")
          v = v.replace("import play.core.routing.{ ReverseRouteContext, queryString }", "import play.core.routing.{ ReverseRouteContext }")
        }
        if(key.endsWith("/JavaScriptReverseRoutes.scala")) {
          v = v.replace("import ReverseRouteContext.empty", "")
          v = v.replace("import play.api.mvc.{ QueryStringBindable, PathBindable, Call, JavascriptLiteral }", "import play.api.mvc.{ QueryStringBindable, JavascriptLiteral }")
          v = v.replace("import play.core.routing.{ HandlerDef, ReverseRouteContext, queryString, dynamicString }", "")
        }
        if(key.endsWith("migrations/javascript/JavaScriptReverseRoutes.scala")) {
          v = v.replace("import play.api.mvc.{ QueryStringBindable, JavascriptLiteral }", "")
        }
        if(key.endsWith("/Routes.scala")) {
          v = v.replace("import play.core.routing.HandlerInvokerFactory._", "")
          v = v.replace("import play.core.j._", "")
          v = v.replace("import ReverseRouteContext.empty", "implicit val empty = ReverseRouteContext(Map())")
        }
        (key, v)
      }
    }

    def id: String = "injected+"
  }
}

Play sbt 插件生成路由代码(见下target/scala-2.11/routes)。此代码片段删除或内联所有未使用的导入。您可能需要为您的路线定制它。

于 2018-10-31T21:01:21.827 回答