diff --git a/.scalafmt b/.scalafmt index 8b4d2ecb6..0c9e4395a 100644 --- a/.scalafmt +++ b/.scalafmt @@ -1 +1,3 @@ --assumeStandardLibraryStripMargin true +--alignTokens %;Infix,%%;Infix,%%%;Infix + diff --git a/build.sbt b/build.sbt index 47993616f..8fe856c0b 100644 --- a/build.sbt +++ b/build.sbt @@ -2,12 +2,14 @@ import sbt.ScriptedPlugin import sbt.ScriptedPlugin._ import scoverage.ScoverageSbtPlugin.ScoverageKeys._ +scalafmtConfig in ThisBuild := Some(file(".scalafmt")) + lazy val buildSettings = Seq( organization := "ch.epfl.scala", assemblyJarName in assembly := "scalafix.jar", // See core/src/main/scala/ch/epfl/scala/Versions.scala - version := scalafix.Versions.nightly, - scalaVersion := scalafix.Versions.scala, + version := scalafix.Versions.nightly, + scalaVersion := scalafix.Versions.scala, updateOptions := updateOptions.value.withCachedResolution(true) ) @@ -17,7 +19,8 @@ lazy val jvmOptions = Seq( lazy val compilerOptions = Seq( "-deprecation", - "-encoding", "UTF-8", + "-encoding", + "UTF-8", "-feature", "-language:existentials", "-language:higherKinds", @@ -32,7 +35,7 @@ lazy val compilerOptions = Seq( lazy val commonSettings = Seq( ScoverageSbtPlugin.ScoverageKeys.coverageExcludedPackages := - ".*Versions;scalafix\\.(sbt|util)", + ".*Versions;scalafix\\.(sbt|util)", triggeredMessage in ThisBuild := Watched.clearWhenTriggered, scalacOptions in (Compile, console) := compilerOptions :+ "-Yrepl-class-based", testOptions in Test += Tests.Argument("-oD") @@ -47,10 +50,11 @@ lazy val publishSettings = Seq( if (isSnapshot.value) Some("snapshots" at nexus + "content/repositories/snapshots") else - Some("releases" at nexus + "service/local/staging/deploy/maven2") + Some("releases" at nexus + "service/local/staging/deploy/maven2") }, publishArtifact in Test := false, - licenses := Seq("Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")), + licenses := Seq( + "Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")), homepage := Some(url("https://github.com/scalacenter/scalafix")), autoAPIMappings := true, apiURL := Some(url("https://scalacenter.github.io/scalafix/docs/")), @@ -77,8 +81,8 @@ lazy val noPublish = Seq( lazy val allSettings = commonSettings ++ buildSettings ++ publishSettings - -lazy val root = project.in(file(".")) +lazy val root = project + .in(file(".")) .settings(moduleName := "scalafix") .settings(allSettings) .settings(noPublish) @@ -102,71 +106,69 @@ lazy val core = project .settings( moduleName := "scalafix-core", libraryDependencies ++= Seq( - "com.lihaoyi" %% "sourcecode" % "0.1.2", - "org.scalameta" %% "scalameta" % "1.0.0", + "com.lihaoyi" %% "sourcecode" % "0.1.2", + "org.scalameta" %% "scalameta" % "1.0.0", "org.scala-lang" % "scala-reflect" % scalaVersion.value, - // Test dependencies - "org.scalatest" %% "scalatest" % "3.0.0" % "test", - "com.googlecode.java-diff-utils" % "diffutils" % "1.3.0" % "test" + "org.scalatest" %% "scalatest" % "3.0.0" % "test", + "com.googlecode.java-diff-utils" % "diffutils" % "1.3.0" % "test" ) ) lazy val cli = project - .settings(allSettings) - .settings(packSettings) - .settings( - moduleName := "scalafix-cli", - packJvmOpts := Map( - "scalafix" -> jvmOptions, - "scalafix_ng" -> jvmOptions - ), - mainClass in assembly := Some("scalafix.cli.Cli"), - packMain := Map( - "scalafix" -> "scalafix.cli.Cli", - "scalafix_ng" -> "com.martiansoftware.nailgun.NGServer" - ), - libraryDependencies ++= Seq( - "com.github.scopt" %% "scopt" % "3.5.0", - "com.github.alexarchambault" %% "case-app" % "1.0.0-RC3", - "com.martiansoftware" % "nailgun-server" % "0.9.1" - ) + .settings(allSettings) + .settings(packSettings) + .settings( + moduleName := "scalafix-cli", + packJvmOpts := Map( + "scalafix" -> jvmOptions, + "scalafix_ng" -> jvmOptions + ), + mainClass in assembly := Some("scalafix.cli.Cli"), + packMain := Map( + "scalafix" -> "scalafix.cli.Cli", + "scalafix_ng" -> "com.martiansoftware.nailgun.NGServer" + ), + libraryDependencies ++= Seq( + "com.github.scopt" %% "scopt" % "3.5.0", + "com.github.alexarchambault" %% "case-app" % "1.1.0-RC3", + "com.martiansoftware" % "nailgun-server" % "0.9.1" ) - .dependsOn(core % "compile->compile;test->test") + ) + .dependsOn(core % "compile->compile;test->test") lazy val sbtScalafix = project - .settings(allSettings) - .settings(ScriptedPlugin.scriptedSettings) - .settings( - sbtPlugin := true, - coverageHighlighting := false, - scalaVersion := "2.10.5", - moduleName := "sbt-scalafix", - sources in Compile += - baseDirectory.value / "../core/src/main/scala/scalafix/Versions.scala", - scriptedLaunchOpts := Seq( - "-Dplugin.version=" + version.value, - // .jvmopts is ignored, simulate here - "-XX:MaxPermSize=256m", "-Xmx2g", "-Xss2m" - ), - scriptedBufferLog := false - ) - + .settings(allSettings) + .settings(ScriptedPlugin.scriptedSettings) + .settings( + sbtPlugin := true, + coverageHighlighting := false, + scalaVersion := "2.10.5", + moduleName := "sbt-scalafix", + sources in Compile += + baseDirectory.value / "../core/src/main/scala/scalafix/Versions.scala", + scriptedLaunchOpts := Seq( + "-Dplugin.version=" + version.value, + // .jvmopts is ignored, simulate here + "-XX:MaxPermSize=256m", + "-Xmx2g", + "-Xss2m" + ), + scriptedBufferLog := false + ) lazy val readme = scalatex - .ScalatexReadme( - projectId = "readme", - wd = file(""), - url = "https://github.com/scalacenter/scalafix/tree/master", - source = "Readme") - .settings(allSettings) - .settings(noPublish) - .dependsOn(core) - .dependsOn(cli) - .settings( - libraryDependencies ++= Seq( - "com.twitter" %% "util-eval" % "6.34.0" - ), - dependencyOverrides += "com.lihaoyi" %% "scalaparse" % "0.3.1" - ) - + .ScalatexReadme(projectId = "readme", + wd = file(""), + url = "https://github.com/scalacenter/scalafix/tree/master", + source = "Readme") + .settings(allSettings) + .settings(noPublish) + .dependsOn(core) + .dependsOn(cli) + .settings( + libraryDependencies ++= Seq( + "com.twitter" %% "util-eval" % "6.34.0" + ), + dependencyOverrides += "com.lihaoyi" %% "scalaparse" % "0.3.1" + ) diff --git a/cli/src/main/scala/scalafix/cli/ArgParserImplicits.scala b/cli/src/main/scala/scalafix/cli/ArgParserImplicits.scala new file mode 100644 index 000000000..7c053249b --- /dev/null +++ b/cli/src/main/scala/scalafix/cli/ArgParserImplicits.scala @@ -0,0 +1,35 @@ +package scalafix.cli + +import scalafix.rewrite.ProcedureSyntax +import scalafix.rewrite.Rewrite + +import java.io.InputStream +import java.io.PrintStream + +import caseapp.core.ArgParser + +object ArgParserImplicits { + def nameMap[T](t: sourcecode.Text[T]*): Map[String, T] = { + t.map(x => x.source -> x.value).toMap + } + + val rewriteMap: Map[String, Rewrite] = nameMap( + ProcedureSyntax + ) + implicit val rewriteRead: ArgParser[Rewrite] = ArgParser.instance[Rewrite] { + str => + rewriteMap.get(str) match { + case Some(x) => Right(x) + case _ => + Left( + s"invalid input $str, must be one of ${rewriteMap.keys.mkString(", ")}") + } + } + + implicit val inputStreamRead: ArgParser[InputStream] = + ArgParser.instance[InputStream](x => Right(System.in)) + + implicit val printStreamRead: ArgParser[PrintStream] = + ArgParser.instance[PrintStream](x => Right(System.out)) + +} diff --git a/cli/src/main/scala/scalafix/cli/Cli.scala b/cli/src/main/scala/scalafix/cli/Cli.scala index 608a1d934..aad815dd5 100644 --- a/cli/src/main/scala/scalafix/cli/Cli.scala +++ b/cli/src/main/scala/scalafix/cli/Cli.scala @@ -3,10 +3,9 @@ package scalafix.cli import scala.collection.GenSeq import scalafix.FixResult import scalafix.Scalafix -import scalafix.rewrite.ProcedureSyntax +import scalafix.cli.ArgParserImplicits._ import scalafix.rewrite.Rewrite import scalafix.util.FileOps -import scalafix.util.LoggerOps._ import java.io.File import java.io.InputStream @@ -14,30 +13,28 @@ import java.io.OutputStreamWriter import java.io.PrintStream import java.util.concurrent.atomic.AtomicInteger -import caseapp.core.ArgParser +import caseapp._ import caseapp.core.Messages import com.martiansoftware.nailgun.NGContext -import caseapp._ -import ScalafixOptions._ @AppName("scalafix") @AppVersion(scalafix.Versions.nightly) @ProgName("scalafix") case class ScalafixOptions( @HelpMessage( - s"Rules to run, one of: ${Rewrite.default.mkString(", ")}" + s"Rules to run, one of: ${Rewrite.default.mkString(", ")}" ) rewrites: List[Rewrite] = Rewrite.default, @Hidden @HelpMessage( - "Files to fix. Runs on all *.scala files if given a directory." + "Files to fix. Runs on all *.scala files if given a directory." ) @ExtraName("f") files: List[String] = List.empty[String], @HelpMessage( - "If true, writes changes to files instead of printing to stdout." + "If true, writes changes to files instead of printing to stdout." ) @ExtraName("i") inPlace: Boolean = false, @HelpMessage( - "If true, uses all available CPUs. If false, runs in single thread." + "If true, uses all available CPUs. If false, runs in single thread." ) parallel: Boolean = true, @HelpMessage( - "If true, prints out debug information." + "If true, prints out debug information." ) debug: Boolean = false, @Hidden workingDirectory: String = System.getProperty("user.dir"), @Hidden out: PrintStream = System.out, @@ -47,31 +44,7 @@ case class ScalafixOptions( Cli.runOn(this) } -object ScalafixOptions { - def nameMap[T](t: sourcecode.Text[T]*): Map[String, T] = { - t.map(x => x.source -> x.value).toMap - } - - val rewriteMap: Map[String, Rewrite] = nameMap( - ProcedureSyntax - ) - implicit val rewriteRead: ArgParser[Rewrite] = ArgParser.instance[Rewrite] { - str => - rewriteMap.get(str) match { - case Some(x) => Right(x) - case _ => - Left( - s"invalid input $str, must be one of ${rewriteMap.keys.mkString(", ")}") - } - } - - implicit val inputStreamRead: ArgParser[InputStream] = - ArgParser.instance[InputStream](x => Right(System.in)) - - implicit val printStreamRead: ArgParser[PrintStream] = - ArgParser.instance[PrintStream](x => Right(System.out)) - -} +object ScalafixOptions {} object Cli extends AppOf[ScalafixOptions] { val helpMessage: String = Messages[ScalafixOptions].withHelp.helpMessage @@ -141,13 +114,13 @@ object Cli extends AppOf[ScalafixOptions] { def nailMain(nGContext: NGContext): Unit = { runMain( - nGContext.getArgs, - ScalafixOptions( - workingDirectory = nGContext.getWorkingDirectory, - out = nGContext.out, - in = nGContext.in, - err = nGContext.err - ) + nGContext.getArgs, + ScalafixOptions( + workingDirectory = nGContext.getWorkingDirectory, + out = nGContext.out, + in = nGContext.in, + err = nGContext.err + ) ) } diff --git a/cli/src/main/scala/scalafix/cli/Scalafix210.scala b/cli/src/main/scala/scalafix/cli/Scalafix210.scala index f7893c119..8b5e5843b 100644 --- a/cli/src/main/scala/scalafix/cli/Scalafix210.scala +++ b/cli/src/main/scala/scalafix/cli/Scalafix210.scala @@ -3,13 +3,13 @@ package scalafix.cli import scalafix.FixResult import scalafix.Scalafix import scalafix.rewrite.Rewrite +import scalafix.util.logger class Scalafix210 { def fix(originalContents: String, filename: String): String = { Scalafix.fix(originalContents, Rewrite.default) match { case FixResult.Success(fixedCode) => fixedCode case FixResult.Error(e) => - import scalafix.util.LoggerOps._ logger.warn(s"Failed to fix $filename. Cause ${e.getMessage}") originalContents } diff --git a/cli/src/main/scala/scalafix/cli/TermDisplay.scala b/cli/src/main/scala/scalafix/cli/TermDisplay.scala index dc83744c0..c4f0a126c 100644 --- a/cli/src/main/scala/scalafix/cli/TermDisplay.scala +++ b/cli/src/main/scala/scalafix/cli/TermDisplay.scala @@ -7,14 +7,15 @@ */ package scalafix.cli -import java.io.{File, Writer} -import java.sql.Timestamp -import java.util.concurrent._ - import scala.annotation.tailrec import scala.collection.mutable.ArrayBuffer import scala.util.Try +import java.io.File +import java.io.Writer +import java.sql.Timestamp +import java.util.concurrent._ + object Terminal { private lazy val pathedTput = @@ -29,10 +30,10 @@ object Terminal { def buffer[T](f: => T): T = f } Try( - Process(Seq("bash", "-c", s"$pathedTput $s 2> /dev/tty")) - .!!(nullLog) - .trim - .toInt).toOption + Process(Seq("bash", "-c", s"$pathedTput $s 2> /dev/tty")) + .!!(nullLog) + .trim + .toInt).toOption } else None @@ -105,8 +106,8 @@ object TermDisplay { val currentTime = System.currentTimeMillis() if (currentTime > startTime) Some( - (downloaded - previouslyDownloaded).toDouble / - (System.currentTimeMillis() - startTime) * 1000.0) + (downloaded - previouslyDownloaded).toDouble / + (System.currentTimeMillis() - startTime) * 1000.0) else None } @@ -133,8 +134,8 @@ object TermDisplay { assert(decile <= 10) fraction.fold(" " * 6)(p => f"${100.0 * p}%5.1f%%") + - " [" + ("#" * decile) + (" " * (10 - decile)) + "] " + - downloaded + " source files fixed" + " [" + ("#" * decile) + (" " * (10 - decile)) + "] " + + downloaded + " source files fixed" } } @@ -158,7 +159,7 @@ object TermDisplay { s"No new update since ${formatTimestamp(current)}" else s"Warning: local copy newer than remote one (${formatTimestamp( - current)} > ${formatTimestamp(remote)})" + current)} > ${formatTimestamp(remote)})" case (Some(_), None) => // FIXME Likely a 404 Not found, that should be taken into account by the cache "No modified time in response" @@ -284,8 +285,7 @@ object TermDisplay { val extra0 = if (extra.length > baseExtraWidth) - extra - .take((baseExtraWidth max (extra.length - overflow)) - 1) + "…" + extra.take((baseExtraWidth max (extra.length - overflow)) - 1) + "…" else extra @@ -294,7 +294,7 @@ object TermDisplay { val url0 = if (total0 >= width) url.take( - ((width - baseExtraWidth - 1) max (url.length - overflow0)) - 1) + "…" + ((width - baseExtraWidth - 1) max (url.length - overflow0)) - 1) + "…" else url @@ -471,13 +471,13 @@ class TermDisplay( override def downloadingArtifact(url: String, file: File): Unit = updateThread.newEntry( - url, - DownloadInfo(0L, - 0L, - None, - System.currentTimeMillis(), - updateCheck = false), - s"Downloading $url\n" + url, + DownloadInfo(0L, + 0L, + None, + System.currentTimeMillis(), + updateCheck = false), + s"Downloading $url\n" ) override def downloadLength(url: String, @@ -516,9 +516,9 @@ class TermDisplay( override def checkingUpdates(url: String, currentTimeOpt: Option[Long]): Unit = updateThread.newEntry( - url, - CheckUpdateInfo(currentTimeOpt, None, isDone = false), - s"Checking $url\n" + url, + CheckUpdateInfo(currentTimeOpt, None, isDone = false), + s"Checking $url\n" ) override def checkingUpdatesResult( diff --git a/cli/src/test/scala/scalafix/cli/CliSuite.scala b/cli/src/test/scala/scalafix/cli/CliSuite.scala index f9c818e8a..72cf1af07 100644 --- a/cli/src/test/scala/scalafix/cli/CliSuite.scala +++ b/cli/src/test/scala/scalafix/cli/CliSuite.scala @@ -15,33 +15,31 @@ class CliSuite extends FunSuite with DiffAssertions { test("testMain") { val expected = ScalafixOptions( - files = List("foo", "bar"), - inPlace = true + files = List("foo", "bar"), + inPlace = true ) val Right(obtained) = Cli.parse(Seq("-i", "foo", "bar")) assertEqual(obtained, expected) } - val original = """ - |object Main { - | def foo() { - | println(1) - | } - |} + val original = """|object Main { + | def foo() { + | println(1) + | } + |} """.stripMargin - val expected = """ - |object Main { - | def foo(): Unit = { - | println(1) - | } - |} + val expected = """|object Main { + | def foo(): Unit = { + | println(1) + | } + |} """.stripMargin test("write fix to file") { val file = File.createTempFile("prefix", ".scala") FileOps.writeFile(file, original) Cli.runOn( - ScalafixOptions(files = List(file.getAbsolutePath), inPlace = true)) + ScalafixOptions(files = List(file.getAbsolutePath), inPlace = true)) assertNoDiff(FileOps.readFile(file), expected) } @@ -50,10 +48,10 @@ class CliSuite extends FunSuite with DiffAssertions { FileOps.writeFile(file, original) val baos = new ByteArrayOutputStream() Cli.runOn( - ScalafixOptions( - out = new PrintStream(baos), - files = List(file.getAbsolutePath) - )) + ScalafixOptions( + out = new PrintStream(baos), + files = List(file.getAbsolutePath) + )) assertNoDiff(FileOps.readFile(file), original) assertNoDiff(new String(baos.toByteArray), expected) } @@ -72,7 +70,7 @@ class CliSuite extends FunSuite with DiffAssertions { val file1, file2 = createFile() Cli.runOn( - ScalafixOptions(files = List(dir.getAbsolutePath), inPlace = true)) + ScalafixOptions(files = List(dir.getAbsolutePath), inPlace = true)) assertNoDiff(FileOps.readFile(file1), expected) assertNoDiff(FileOps.readFile(file2), expected) } diff --git a/core/src/main/scala/scalafix/Scalafix.scala b/core/src/main/scala/scalafix/Scalafix.scala index 9e2245f21..fbf0c3903 100644 --- a/core/src/main/scala/scalafix/Scalafix.scala +++ b/core/src/main/scala/scalafix/Scalafix.scala @@ -11,7 +11,7 @@ object Scalafix { def fix(code: Input, rewriters: Seq[Rewrite]): FixResult = { rewriters.foldLeft[FixResult]( - FixResult.Success(String.copyValueOf(code.chars))) { + FixResult.Success(String.copyValueOf(code.chars))) { case (newCode: FixResult.Success, rewriter) => try rewriter.rewrite(Input.String(newCode.code)) catch { diff --git a/core/src/main/scala/scalafix/rewrite/Rewrite.scala b/core/src/main/scala/scalafix/rewrite/Rewrite.scala index a71519707..274e79eb1 100644 --- a/core/src/main/scala/scalafix/rewrite/Rewrite.scala +++ b/core/src/main/scala/scalafix/rewrite/Rewrite.scala @@ -18,6 +18,6 @@ abstract class Rewrite { object Rewrite { val default: List[Rewrite] = List( - ProcedureSyntax + ProcedureSyntax ) } diff --git a/core/src/main/scala/scalafix/util/LoggerOps.scala b/core/src/main/scala/scalafix/util/LoggerOps.scala deleted file mode 100644 index f7e1ab469..000000000 --- a/core/src/main/scala/scalafix/util/LoggerOps.scala +++ /dev/null @@ -1,36 +0,0 @@ -package scalafix.util - -import scala.meta.Tree -import scala.meta.prettyprinters.Structure -import scala.meta.tokens.Token -import scala.meta.tokens.Token.Interpolation -import scala.meta.tokens.Tokens - -/** - * Debugging utility. - */ -object LoggerOps { - val logger = PrintlnLogger - - def log(t: Tree, tokensOnly: Boolean = false): String = { - val tokens = - s"TOKENS: ${t.tokens.map(x => reveal(x.syntax)).mkString(",")}" - if (tokensOnly) tokens - else s"""TYPE: ${t.getClass.getName.stripPrefix("scala.meta.")} - |SOURCE: $t - |STRUCTURE: ${t.show[Structure]} - |$tokens - |""".stripMargin - } - - def reveal(s: String): String = s.map { - case '\n' => '¶' - case ' ' => '∙' - case ch => ch - } - - def header[T](t: T): String = { - val line = s"=" * (t.toString.length + 3) - s"$line\n=> $t\n$line" - } -} diff --git a/core/src/main/scala/scalafix/util/PrintlnLogger.scala b/core/src/main/scala/scalafix/util/logger.scala similarity index 75% rename from core/src/main/scala/scalafix/util/PrintlnLogger.scala rename to core/src/main/scala/scalafix/util/logger.scala index ec1e8658c..e2ea7ca54 100644 --- a/core/src/main/scala/scalafix/util/PrintlnLogger.scala +++ b/core/src/main/scala/scalafix/util/logger.scala @@ -1,14 +1,14 @@ package scalafix.util +import scala.meta.Tree +import scala.meta.prettyprinters.Structure + import java.io.File /** - * Yet Another Logger. - * - * I rely heavily on logging for debugging and the standard Java logging - * doesn't work on Scala.js, which I hope to support one day. + * Debugging utility. */ -object PrintlnLogger { +object logger { private def log[T](t: sourcecode.Text[T], logLevel: LogLevel, @@ -57,4 +57,26 @@ object PrintlnLogger { file: sourcecode.File, enclosing: sourcecode.Enclosing): Unit = log(t, LogLevel.error, line, file, enclosing, showSource = false) + + def log(t: Tree, tokensOnly: Boolean = false): String = { + val tokens = + s"TOKENS: ${t.tokens.map(x => reveal(x.syntax)).mkString(",")}" + if (tokensOnly) tokens + else s"""TYPE: ${t.getClass.getName.stripPrefix("scala.meta.")} + |SOURCE: $t + |STRUCTURE: ${t.show[Structure]} + |$tokens + |""".stripMargin + } + + def reveal(s: String): String = s.map { + case '\n' => '¶' + case ' ' => '∙' + case ch => ch + } + + def header[T](t: T): String = { + val line = s"=" * (t.toString.length + 3) + s"$line\n=> $t\n$line" + } } diff --git a/core/src/test/scala/scalafix/ScalafixSuite.scala b/core/src/test/scala/scalafix/ScalafixSuite.scala index 26635d54c..c0bf35b1f 100644 --- a/core/src/test/scala/scalafix/ScalafixSuite.scala +++ b/core/src/test/scala/scalafix/ScalafixSuite.scala @@ -16,37 +16,37 @@ class ScalafixSuite extends FunSuite with DiffAssertions { } testInput( - "nested function", - """ - |import /* a */ a.b.c - |import a.b.c - |// This is a comment - |@annotation - |object Main { - | def main(args: Seq[String]) { - | var number = 2 - | def increment(n: Int) { - | number += n - | } - | increment(3) - | args.foreach(println(number)) - | } - |}""".stripMargin, - """ - |import /* a */ a.b.c - |import a.b.c - |// This is a comment - |@annotation - |object Main { - | def main(args: Seq[String]): Unit = { - | var number = 2 - | def increment(n: Int): Unit = { - | number += n - | } - | increment(3) - | args.foreach(println(number)) - | } - |}""".stripMargin + "nested function", + """ + |import /* a */ a.b.c + |import a.b.c + |// This is a comment + |@annotation + |object Main { + | def main(args: Seq[String]) { + | var number = 2 + | def increment(n: Int) { + | number += n + | } + | increment(3) + | args.foreach(println(number)) + | } + |}""".stripMargin, + """ + |import /* a */ a.b.c + |import a.b.c + |// This is a comment + |@annotation + |object Main { + | def main(args: Seq[String]): Unit = { + | var number = 2 + | def increment(n: Int): Unit = { + | number += n + | } + | increment(3) + | args.foreach(println(number)) + | } + |}""".stripMargin ) test("on parse error") { diff --git a/core/src/test/scala/scalafix/util/DiffAssertions.scala b/core/src/test/scala/scalafix/util/DiffAssertions.scala index cb0438773..49ea796de 100644 --- a/core/src/test/scala/scalafix/util/DiffAssertions.scala +++ b/core/src/test/scala/scalafix/util/DiffAssertions.scala @@ -5,13 +5,10 @@ import java.text.SimpleDateFormat import java.util.Date import java.util.TimeZone -import scalafix.util.LoggerOps._ import org.scalatest.FunSuiteLike -import org.scalatest.events.TestFailed import org.scalatest.exceptions.TestFailedException trait DiffAssertions extends FunSuiteLike { - import LoggerOps._ def assertEqual[A](a: A, b: A): Unit = { assert(a === b) @@ -22,19 +19,19 @@ trait DiffAssertions extends FunSuiteLike { obtained: String, diff: String) extends TestFailedException( - title + "\n" + error2message(obtained, expected), - 1) + title + "\n" + error2message(obtained, expected), + 1) def error2message(obtained: String, expected: String): String = { val sb = new StringBuilder if (obtained.length < 1000) { sb.append(s""" - #${header("Obtained")} + #${logger.header("Obtained")} #${trailingSpace(obtained)} """.stripMargin('#')) } sb.append(s""" - #${header("Diff")} + #${logger.header("Diff")} #${trailingSpace(compareContents(obtained, expected))} """.stripMargin('#')) sb.toString() @@ -63,11 +60,11 @@ trait DiffAssertions extends FunSuiteLike { else difflib.DiffUtils .generateUnifiedDiff( - "original", - "revised", - original.asJava, - diff, - 1 + "original", + "revised", + original.asJava, + diff, + 1 ) .asScala .drop(3) diff --git a/project/plugins.sbt b/project/plugins.sbt index decb463e3..b982b6d3f 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,9 +1,9 @@ -libraryDependencies += "org.scala-sbt" % "scripted-plugin" % sbtVersion.value - -addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.0-M13") -addSbtPlugin("com.lihaoyi" % "scalatex-sbt-plugin" % "0.3.5") -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") -addSbtPlugin("org.xerial.sbt" % "sbt-pack" % "0.8.0") -addSbtPlugin("org.brianmckenna" % "sbt-wartremover" % "0.14") -addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.0.1") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") +addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "0.3.0") +addSbtPlugin("com.lihaoyi" % "scalatex-sbt-plugin" % "0.3.5") +addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.0-M13") +addSbtPlugin("org.brianmckenna" % "sbt-wartremover" % "0.14") +addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.0.1") +addSbtPlugin("org.xerial.sbt" % "sbt-pack" % "0.8.0") +libraryDependencies += "org.scala-sbt" % "scripted-plugin" % sbtVersion.value diff --git a/readme/Readme.scala b/readme/Readme.scala index 37f83f6d4..6d662e027 100644 --- a/readme/Readme.scala +++ b/readme/Readme.scala @@ -1,6 +1,5 @@ package scalafix -import scalatags.Text.TypedTag import scalatags.Text.all._ object Readme { diff --git a/sbtScalafix/src/main/scala/scalafix/sbt/HasScalafix.scala b/sbtScalafix/src/main/scala/scalafix/sbt/HasScalafix.scala index 968693edf..5fba5515a 100644 --- a/sbtScalafix/src/main/scala/scalafix/sbt/HasScalafix.scala +++ b/sbtScalafix/src/main/scala/scalafix/sbt/HasScalafix.scala @@ -21,13 +21,13 @@ package scalafix.sbt import scala.language.reflectiveCalls +import scala.collection.immutable.Seq + import sbt.File import sbt.FileFilter import sbt.Keys.TaskStreams import sbt.ProjectRef -import scala.collection.immutable.Seq - case class HasScalafix(reflective: ScalafixLike, configFile: Option[File], streams: TaskStreams, @@ -35,7 +35,8 @@ case class HasScalafix(reflective: ScalafixLike, includeFilter: FileFilter, excludeFilter: FileFilter, ref: ProjectRef) { - import sbt.{Future => _, _} + import sbt.{Future => _} + import sbt._ def log(label: String, logger: Logger)(message: String)(count: String) = logger.info(message.format(count, label)) @@ -46,7 +47,9 @@ case class HasScalafix(reflective: ScalafixLike, sourceDirectories.descendantsExcept(includeFilter, excludeFilter).get.toSet def writeFormattedContentsToFiles(): Unit = { - inc.Analysis.counted("Scala source", "", "s", files.size).foreach(logFun("Fixed %s %s ...")) + inc.Analysis + .counted("Scala source", "", "s", files.size) + .foreach(logFun("Fixed %s %s ...")) files.foreach(handleFile(writeFixed)) } diff --git a/sbtScalafix/src/main/scala/scalafix/sbt/ReflectiveDynamicAccess.scala b/sbtScalafix/src/main/scala/scalafix/sbt/ReflectiveDynamicAccess.scala index e0642824d..fdc0e6f69 100644 --- a/sbtScalafix/src/main/scala/scalafix/sbt/ReflectiveDynamicAccess.scala +++ b/sbtScalafix/src/main/scala/scalafix/sbt/ReflectiveDynamicAccess.scala @@ -19,12 +19,12 @@ limitations under the License. */ package scalafix.sbt -import java.lang.reflect.InvocationTargetException - import scala.collection.immutable import scala.reflect.ClassTag import scala.util.Try +import java.lang.reflect.InvocationTargetException + /** * Original: * https://github.com/akka/akka/blob/master/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala @@ -54,7 +54,7 @@ class ReflectiveDynamicAccess(val classLoader: ClassLoader) { if (t.isInstance(obj)) obj.asInstanceOf[T] else throw new ClassCastException( - s"${clazz.getName} is not a subtype of $t") + s"${clazz.getName} is not a subtype of $t") } recover { case i: InvocationTargetException if i.getTargetException ne null ⇒ throw i.getTargetException diff --git a/sbtScalafix/src/main/scala/scalafix/sbt/ScalafixPlugin.scala b/sbtScalafix/src/main/scala/scalafix/sbt/ScalafixPlugin.scala index 3be45dc68..9a4b34522 100644 --- a/sbtScalafix/src/main/scala/scalafix/sbt/ScalafixPlugin.scala +++ b/sbtScalafix/src/main/scala/scalafix/sbt/ScalafixPlugin.scala @@ -19,6 +19,10 @@ limitations under the License. */ package scalafix.sbt +import scala.collection.immutable.Seq +import scala.util.Failure +import scala.util.Success + import java.net.URLClassLoader import sbt.Keys._ @@ -26,10 +30,6 @@ import sbt._ import sbt.plugins.JvmPlugin import sbt.{IntegrationTest => It} -import scala.collection.immutable.Seq -import scala.util.Failure -import scala.util.Success - object ScalafixPlugin extends AutoPlugin { object autoImport { @@ -40,7 +40,7 @@ object ScalafixPlugin extends AutoPlugin { taskKey[Option[File]]("Configuration file for scalafix.") lazy val hasScalafix: TaskKey[HasScalafix] = taskKey[HasScalafix]( - "Classloaded Scalafix210 instance to overcome 2.10 incompatibility issues.") + "Classloaded Scalafix210 instance to overcome 2.10 incompatibility issues.") def scalafixSettings: Seq[Setting[_]] = noConfigScalafixSettings ++ @@ -62,54 +62,53 @@ object ScalafixPlugin extends AutoPlugin { def noConfigScalafixSettings: Seq[Setting[_]] = List( - ivyConfigurations += config("scalafix").hide, - libraryDependencies ++= Seq( - "org.scala-lang" % "scala-library" % _root_.scalafix.Versions.scala % "scalafix", - "ch.epfl.scala" % "scalafix-cli_2.11" % _root_.scalafix.Versions.nightly % "scalafix" - ) + ivyConfigurations += config("scalafix").hide, + libraryDependencies ++= Seq( + "org.scala-lang" % "scala-library" % _root_.scalafix.Versions.scala % "scalafix", + "ch.epfl.scala" % "scalafix-cli_2.11" % _root_.scalafix.Versions.nightly % "scalafix" + ) ) def configScalafixSettings: Seq[Setting[_]] = List( - (sourceDirectories in hasScalafix) := unmanagedSourceDirectories.value, - includeFilter in Global in hasScalafix := "*.scala", - scalafixConfig in Global := None, - hasScalafix := { - val report = update.value - val jars = report.select(configurationFilter("scalafix")) - HasScalafix(getScalafixLike( - new URLClassLoader(jars.map(_.toURI.toURL).toArray, + (sourceDirectories in hasScalafix) := unmanagedSourceDirectories.value, + includeFilter in Global in hasScalafix := "*.scala", + scalafixConfig in Global := None, + hasScalafix := { + val report = update.value + val jars = report.select(configurationFilter("scalafix")) + HasScalafix( + getScalafixLike(new URLClassLoader(jars.map(_.toURI.toURL).toArray, null), streams.value), - scalafixConfig.value, - streams.value, - (sourceDirectories in hasScalafix).value.toList, - (includeFilter in hasScalafix).value, - (excludeFilter in hasScalafix).value, - thisProjectRef.value) - }, - scalafix := hasScalafix.value.writeFormattedContentsToFiles() + scalafixConfig.value, + streams.value, + (sourceDirectories in hasScalafix).value.toList, + (includeFilter in hasScalafix).value, + (excludeFilter in hasScalafix).value, + thisProjectRef.value) + }, + scalafix := hasScalafix.value.writeFormattedContentsToFiles() ) private def getScalafixLike(classLoader: URLClassLoader, streams: TaskStreams): ScalafixLike = { val loadedClass = - new ReflectiveDynamicAccess(classLoader).createInstanceFor[ScalafixLike]( - "scalafix.cli.Scalafix210", - Seq.empty) + new ReflectiveDynamicAccess(classLoader) + .createInstanceFor[ScalafixLike]("scalafix.cli.Scalafix210", Seq.empty) loadedClass match { case Success(x) => x case Failure(e) => streams.log.error( - s"""Unable to classload Scalafix, please file an issue: - |https://github.com/scalacenter/scalafix/issues - | - |URLs: ${classLoader.getURLs.mkString("\n")} - |Version: ${_root_.scalafix.Versions.nightly} - |Error: ${e.getClass} - |Message: ${e.getMessage} - |${e.getStackTrace.mkString("\n")}""".stripMargin) + s"""Unable to classload Scalafix, please file an issue: + |https://github.com/scalacenter/scalafix/issues + | + |URLs: ${classLoader.getURLs.mkString("\n")} + |Version: ${_root_.scalafix.Versions.nightly} + |Error: ${e.getClass} + |Message: ${e.getMessage} + |${e.getStackTrace.mkString("\n")}""".stripMargin) throw e } } diff --git a/sbtScalafix/src/main/scala/scalafix/sbt/package.scala b/sbtScalafix/src/main/scala/scalafix/sbt/package.scala index 379c07e3f..c5d16a557 100644 --- a/sbtScalafix/src/main/scala/scalafix/sbt/package.scala +++ b/sbtScalafix/src/main/scala/scalafix/sbt/package.scala @@ -5,4 +5,3 @@ package object sbt { def fix(code: String, filename: String): String } } - diff --git a/sbtScalafix/src/sbt-test/scalafix-sbt/basic/build.sbt b/sbtScalafix/src/sbt-test/scalafix-sbt/basic/build.sbt index 566124822..d90056098 100644 --- a/sbtScalafix/src/sbt-test/scalafix-sbt/basic/build.sbt +++ b/sbtScalafix/src/sbt-test/scalafix-sbt/basic/build.sbt @@ -1,12 +1,11 @@ sbtPlugin := true - TaskKey[Unit]("check") := { val obtained = scala.io.Source .fromFile("src/main/scala/Test.scala") - .getLines() - .mkString("\n") + .getLines() + .mkString("\n") val expected = """ |object Main { diff --git a/sbtScalafix/src/sbt-test/scalafix-sbt/basic/project/plugins.sbt b/sbtScalafix/src/sbt-test/scalafix-sbt/basic/project/plugins.sbt index ebed0c76e..a78bdb3b8 100644 --- a/sbtScalafix/src/sbt-test/scalafix-sbt/basic/project/plugins.sbt +++ b/sbtScalafix/src/sbt-test/scalafix-sbt/basic/project/plugins.sbt @@ -1,2 +1,2 @@ -addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % System.getProperty("plugin.version")) - +addSbtPlugin( + "ch.epfl.scala" % "sbt-scalafix" % System.getProperty("plugin.version"))