From 540e36200e1097aab1374e7c348338ab030a395b Mon Sep 17 00:00:00 2001 From: Brice Jaglin Date: Wed, 4 Nov 2020 19:07:09 +0100 Subject: [PATCH] scalafmt-core 2.7.5 --- .scalafmt.conf | 6 +- build.sbt | 6 +- project/ScalafixBuild.scala | 32 +- project/project/plugins.sbt | 4 +- .../interfaces/ScalafixErrorImpl.scala | 11 +- .../scala/scalafix/internal/v1/Args.scala | 85 +++--- .../scalafix/internal/v1/CompletionsOps.scala | 4 +- .../scala/scalafix/internal/v1/MainOps.scala | 12 +- .../scala/scalafix/config/CustomMessage.scala | 25 +- .../main/scala/scalafix/config/Regex.scala | 11 +- .../scalafix/internal/config/LogContext.scala | 4 +- .../internal/config/MetaconfigOps.scala | 4 +- .../scalafix/internal/config/ReaderUtil.scala | 23 +- .../config/ScalafixMetaconfigReaders.scala | 102 ++++--- .../scalafix/internal/diff/DiffDisable.scala | 12 +- .../scalafix/internal/patch/EscapeHatch.scala | 116 ++++---- .../internal/patch/ImportPatchOps.scala | 46 ++- .../internal/patch/LegacyPatchOps.scala | 4 +- .../internal/patch/PatchInternals.scala | 3 +- .../internal/patch/ReplaceSymbolOps.scala | 57 ++-- .../scalafix/internal/rule/RuleCtxImpl.scala | 6 +- .../internal/util/ClassloadRule.scala | 8 +- .../util/EagerInMemorySemanticdbIndex.scala | 13 +- .../scalafix/internal/util/Failure.scala | 6 +- .../scalafix/internal/util/IntervalSet.scala | 5 +- .../scalafix/internal/util/PrettyType.scala | 38 ++- .../internal/util/ProductStructure.scala | 6 +- .../internal/util/QualifyStrategy.scala | 3 +- .../scalafix/internal/util/SymbolOps.scala | 4 +- .../scalafix/internal/v0/LegacyRuleCtx.scala | 4 +- .../internal/v1/DocumentFromProtobuf.scala | 4 +- .../scalafix/internal/v1/FingerprintOps.scala | 4 +- .../internal/v1/InternalSemanticDoc.scala | 4 +- .../scala/scalafix/internal/v1/TreePos.scala | 6 +- .../src/main/scala/scalafix/patch/Patch.scala | 13 +- .../main/scala/scalafix/patch/PatchOps.scala | 12 +- .../main/scala/scalafix/syntax/package.scala | 8 +- .../main/scala/scalafix/util/TokenList.scala | 11 +- .../main/scala/scalafix/util/TokenOps.scala | 6 +- .../main/scala/scalafix/util/TreeOps.scala | 4 +- .../main/scala/scalafix/v0/LintCategory.scala | 3 +- .../main/scala/scalafix/v0/LintMessage.scala | 9 +- .../src/main/scala/scalafix/v0/Rule.scala | 6 +- .../src/main/scala/scalafix/v0/RuleCtx.scala | 16 +- .../scala/scalafix/v0/SemanticdbIndex.scala | 9 +- .../main/scala/scalafix/v0/Signature.scala | 4 +- .../src/main/scala/scalafix/v0/Symbol.scala | 8 +- .../scala/scalafix/v1/SemanticContext.scala | 3 +- .../scala/scalafix/v1/SymbolInformation.scala | 2 - .../src/main/scala/scalafix/v1/package.scala | 8 +- .../src/main/scala/docs/website.scala | 19 +- .../main/scala/scalafix/docs/PatchDocs.scala | 4 +- .../internal/reflect/ClasspathOps.scala | 6 +- .../internal/reflect/GitHubUrlRule.scala | 6 +- .../internal/reflect/ScalafixToolbox.scala | 18 +- .../v0/LegacyInMemorySemanticdbIndex.scala | 5 +- .../main/scala/scalafix/v1/RuleDecoder.scala | 3 +- .../scala/meta/internal/pc/Identifier.scala | 15 +- .../meta/internal/pc/ScalafixGlobal.scala | 36 ++- .../interactive/ScalafixGlobalThread.scala | 11 +- .../internal/rule/CompilerTypePrinter.scala | 29 +- .../internal/rule/DisableSyntax.scala | 16 +- .../internal/rule/DisableSyntaxConfig.scala | 12 +- .../internal/rule/ExplicitResultTypes.scala | 10 +- .../rule/ExplicitResultTypesConfig.scala | 4 +- .../rule/LeakingImplicitClassVal.scala | 10 +- .../rule/NoValInForComprehension.scala | 9 +- .../scalafix/internal/rule/RemoveUnused.scala | 16 +- .../internal/testkit/AssertDelta.scala | 5 +- .../internal/testkit/AssertDiff.scala | 12 +- .../testkit/AbstractSemanticRuleSuite.scala | 3 +- .../testkit/AbstractSyntacticRuleSuite.scala | 3 +- .../scalafix/testkit/DiffAssertions.scala | 8 +- .../main/scala/scalafix/test/FqnRule.scala | 9 +- .../main/scala/scalafix/test/StringFS.scala | 5 +- .../scalafix/tests/cli/BaseCliSuite.scala | 16 +- .../scalafix/tests/cli/CliGitDiffSuite.scala | 127 ++++---- .../scalafix/tests/cli/CliSuppressSuite.scala | 32 +- .../tests/cli/CliSyntacticSuite.scala | 279 +++++++++--------- .../tests/cli/ScalafixImplSuite.scala | 60 ++-- .../config/DisableSyntaxConfigSuite.scala | 32 +- .../tests/config/ScalafixConfigSuite.scala | 4 +- .../scalafix/tests/core/DialectSuite.scala | 11 +- .../tests/core/EscapeHatchSuite.scala | 21 +- .../scalafix/tests/core/PatchSuite.scala | 14 +- .../scalafix/tests/core/PrettyTypeSuite.scala | 35 ++- .../tests/core/SemanticdbIndexSuite.scala | 9 +- .../tests/core/util/TokenListSuite.scala | 4 +- .../interfaces/ScalafixArgumentsSuite.scala | 56 ++-- .../tests/interfaces/ScalafixSuite.scala | 17 +- .../tests/reflect/ToolClasspathSuite.scala | 5 +- .../tests/testkit/AssertDeltaSuite.scala | 172 +++++------ .../tests/util/PrettyExpectSuite.scala | 9 +- .../tests/util/ScalametaStructureSuite.scala | 52 ++-- .../tests/v0/LegacyDenotationSuite.scala | 29 +- .../tests/v0/SymbolMatcherSuite.scala | 11 +- .../tests/v1/SymbolMatcherSuite.scala | 9 +- .../scala/scalafix/tests/v1/SymbolSuite.scala | 4 +- 98 files changed, 1076 insertions(+), 1006 deletions(-) diff --git a/.scalafmt.conf b/.scalafmt.conf index 9b66f251b..04e5c0036 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,9 +1,9 @@ -version = 2.3.1 +version = 2.7.5 project.git = true -docstrings = Javadoc +docstrings.style = Asterisk optIn.blankLineBeforeDocstring = true assumeStandardLibraryStripMargin = true -align = none +align.preset = none onTestFailure = "To fix this, run `./scalafmt` from the project base directory" optIn.annotationNewlines = true project.excludeFilters = [ diff --git a/build.sbt b/build.sbt index 48da24663..f3a21ae08 100644 --- a/build.sbt +++ b/build.sbt @@ -192,7 +192,9 @@ lazy val unit = project libraryDependencies ++= testsDeps, libraryDependencies ++= List( jgit, - scalatest.withRevision("3.2.0"), // make sure testkit clients can use recent 3.x versions + scalatest.withRevision( + "3.2.0" + ), // make sure testkit clients can use recent 3.x versions "org.scalameta" %% "testkit" % scalametaV ), compileInputs.in(Compile, compile) := { @@ -257,7 +259,7 @@ lazy val unit = project semanticdbTargetRoot.in(testsShared, Compile).value, "sharedSourceroot" -> baseDirectory.in(ThisBuild).value / - "scalafix-tests" / "shared" / "src" / "main", + "scalafix-tests" / "shared" / "src" / "main", "sharedClasspath" -> classDirectory.in(testsShared, Compile).value ), diff --git a/project/ScalafixBuild.scala b/project/ScalafixBuild.scala index 73fce343b..3af2403ff 100644 --- a/project/ScalafixBuild.scala +++ b/project/ScalafixBuild.scala @@ -158,7 +158,8 @@ object ScalafixBuild extends AutoPlugin with GhpagesKeys { // Custom settings to publish scalafix forks to alternative maven repo. lazy val adhocRepoUri = sys.props("scalafix.repository.uri") lazy val adhocRepoCredentials = sys.props("scalafix.repository.credentials") - lazy val isCustomRepository = adhocRepoUri != null && adhocRepoCredentials != null + lazy val isCustomRepository = + adhocRepoUri != null && adhocRepoCredentials != null override def globalSettings: Seq[Def.Setting[_]] = List( stableVersion := version.in(ThisBuild).value.replaceFirst("\\+.*", ""), @@ -308,21 +309,20 @@ object ScalafixBuild extends AutoPlugin with GhpagesKeys { val currentState = state.value val ref = thisProjectRef.value val versions = crossScalaVersions.value - versions.map { - version => - val withScalaVersion = Project - .extract(currentState) - .appendWithoutSession( - Seq( - scalaVersion.in(ThisBuild) := version, - publishArtifact.in(ThisBuild, packageDoc) := false, - publishArtifact.in(ThisBuild, packageSrc) := false - ), - currentState - ) - Project - .extract(withScalaVersion) - .runTask(publishLocalTransitive.in(ref), withScalaVersion) + versions.map { version => + val withScalaVersion = Project + .extract(currentState) + .appendWithoutSession( + Seq( + scalaVersion.in(ThisBuild) := version, + publishArtifact.in(ThisBuild, packageDoc) := false, + publishArtifact.in(ThisBuild, packageSrc) := false + ), + currentState + ) + Project + .extract(withScalaVersion) + .runTask(publishLocalTransitive.in(ref), withScalaVersion) } } ) diff --git a/project/project/plugins.sbt b/project/project/plugins.sbt index 1ed4d0bd5..61ad648bf 100644 --- a/project/project/plugins.sbt +++ b/project/project/plugins.sbt @@ -1,2 +1,4 @@ addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.23") -unmanagedSources.in(Compile) += baseDirectory.value / ".." / "Dependencies.scala" +unmanagedSources.in( + Compile +) += baseDirectory.value / ".." / "Dependencies.scala" diff --git a/scalafix-cli/src/main/scala/scalafix/internal/interfaces/ScalafixErrorImpl.scala b/scalafix-cli/src/main/scala/scalafix/internal/interfaces/ScalafixErrorImpl.scala index b1389b52f..1c284719d 100644 --- a/scalafix-cli/src/main/scala/scalafix/internal/interfaces/ScalafixErrorImpl.scala +++ b/scalafix-cli/src/main/scala/scalafix/internal/interfaces/ScalafixErrorImpl.scala @@ -9,12 +9,11 @@ object ScalafixErrorImpl { val to = ScalafixError.values().toList assert(from.length == to.length, s"$from != $to") val map = from.zip(to).toMap - map.foreach { - case (key, value) => - assert( - key.name.toLowerCase() == value.toString.toLowerCase, - s"$key != $value" - ) + map.foreach { case (key, value) => + assert( + key.name.toLowerCase() == value.toString.toLowerCase, + s"$key != $value" + ) } map } diff --git a/scalafix-cli/src/main/scala/scalafix/internal/v1/Args.scala b/scalafix-cli/src/main/scala/scalafix/internal/v1/Args.scala index 6088975ab..62105a952 100644 --- a/scalafix-cli/src/main/scala/scalafix/internal/v1/Args.scala +++ b/scalafix-cli/src/main/scala/scalafix/internal/v1/Args.scala @@ -128,23 +128,23 @@ case class Args( @Section("Tab completions") @Description( """|Print out bash tab completions. To install: - |``` - |# macOS, requires "brew install bash-completion" - |scalafix --bash > /usr/local/etc/bash_completion.d/scalafix - |# Linux - |scalafix --bash > /etc/bash_completion.d/scalafix - |``` - |""".stripMargin + |``` + |# macOS, requires "brew install bash-completion" + |scalafix --bash > /usr/local/etc/bash_completion.d/scalafix + |# Linux + |scalafix --bash > /etc/bash_completion.d/scalafix + |``` + |""".stripMargin ) bash: Boolean = false, @Description( """|Print out zsh tab completions. To install: - |``` - |scalafix --zsh > /usr/local/share/zsh/site-functions/_scalafix - |unfunction _scalafix - |autoload -U _scalafix - |``` - |""".stripMargin + |``` + |scalafix --zsh > /usr/local/share/zsh/site-functions/_scalafix + |unfunction _scalafix + |autoload -U _scalafix + |``` + |""".stripMargin ) zsh: Boolean = false, // TODO: --sbt @@ -384,34 +384,33 @@ case class Args( } def validate: Configured[ValidatedArgs] = { - baseConfig.andThen { - case (base, scalafixConfig, delegator) => - ( - configuredSourceroot |@| - configuredSymtab |@| - configuredRules(base, scalafixConfig) |@| - resolvedPathReplace |@| - configuredDiffDisable |@| - configuredGlobal - ).map { - case ( + baseConfig.andThen { case (base, scalafixConfig, delegator) => + ( + configuredSourceroot |@| + configuredSymtab |@| + configuredRules(base, scalafixConfig) |@| + resolvedPathReplace |@| + configuredDiffDisable |@| + configuredGlobal + ).map { + case ( ((((root, symtab), rulez), pathReplace), diffDisable), global - ) => - ValidatedArgs( - this, - symtab, - rulez, - scalafixConfig, - classLoader, - root, - pathReplace, - diffDisable, - delegator, - semanticdbFilterMatcher, - global - ) - } + ) => + ValidatedArgs( + this, + symtab, + rulez, + scalafixConfig, + classLoader, + root, + pathReplace, + diffDisable, + delegator, + semanticdbFilterMatcher, + global + ) + } } } } @@ -477,14 +476,14 @@ object Args { TPrint.make[PathMatcher](_ => "") implicit val confPrint: TPrint[Conf] = TPrint.make[Conf](implicit cfg => TPrint.implicitly[ScalafixConfig].render) - implicit def optionPrint[T]( - implicit ev: pprint.TPrint[T] + implicit def optionPrint[T](implicit + ev: pprint.TPrint[T] ): TPrint[Option[T]] = TPrint.make { implicit cfg => ev.render } - implicit def iterablePrint[C[x] <: Iterable[x], T]( - implicit ev: pprint.TPrint[T] + implicit def iterablePrint[C[x] <: Iterable[x], T](implicit + ev: pprint.TPrint[T] ): TPrint[C[T]] = TPrint.make { implicit cfg => s"[${ev.render} ...]" diff --git a/scalafix-cli/src/main/scala/scalafix/internal/v1/CompletionsOps.scala b/scalafix-cli/src/main/scala/scalafix/internal/v1/CompletionsOps.scala index b696fd17e..03459b4c6 100644 --- a/scalafix-cli/src/main/scala/scalafix/internal/v1/CompletionsOps.scala +++ b/scalafix-cli/src/main/scala/scalafix/internal/v1/CompletionsOps.scala @@ -28,7 +28,9 @@ object CompletionsOps { s"$assign[$escaped]" } names(setting).map { name => - s""""$repeat${option(Case.camelToKebab(name))}$description$message$action"""" + s""""$repeat${option( + Case.camelToKebab(name) + )}$description$message$action"""" } } } diff --git a/scalafix-cli/src/main/scala/scalafix/internal/v1/MainOps.scala b/scalafix-cli/src/main/scala/scalafix/internal/v1/MainOps.scala index 656b808cd..75c538726 100644 --- a/scalafix-cli/src/main/scala/scalafix/internal/v1/MainOps.scala +++ b/scalafix-cli/src/main/scala/scalafix/internal/v1/MainOps.scala @@ -448,15 +448,15 @@ object MainOps { s"Scalafix ${Versions.version}" def usage: String = """|Usage: scalafix [options] [ ...] - |""".stripMargin + |""".stripMargin def description: D = D.paragraph( """|Scalafix is a refactoring and linting tool. - |Scalafix supports both syntactic and semantic linter and rewrite rules. - |Syntactic rules can run on source code without compilation. - |Semantic rules can run on source code that has been compiled with the - |SemanticDB compiler plugin. - |""".stripMargin + |Scalafix supports both syntactic and semantic linter and rewrite rules. + |Syntactic rules can run on source code without compilation. + |Semantic rules can run on source code that has been compiled with the + |SemanticDB compiler plugin. + |""".stripMargin ) /** Line wrap prose while keeping markdown code fences unchanged. */ diff --git a/scalafix-core/src/main/scala/scalafix/config/CustomMessage.scala b/scalafix-core/src/main/scala/scalafix/config/CustomMessage.scala index 1edd4bb31..220f4dc05 100644 --- a/scalafix-core/src/main/scala/scalafix/config/CustomMessage.scala +++ b/scalafix-core/src/main/scala/scalafix/config/CustomMessage.scala @@ -15,8 +15,8 @@ object CustomMessage { implicit val SymbolDecoder: ConfDecoder[CustomMessage[Symbol.Global]] = decoder[Symbol.Global](field = "symbol") - implicit def CustomMessageEitherDecoder[A, B]( - implicit AB: ConfDecoder[Either[CustomMessage[A], CustomMessage[B]]] + implicit def CustomMessageEitherDecoder[A, B](implicit + AB: ConfDecoder[Either[CustomMessage[A], CustomMessage[B]]] ): ConfDecoder[CustomMessage[Either[A, B]]] = AB.map { case Right(msg) => @@ -31,18 +31,17 @@ object CustomMessage { case obj: Conf.Obj => { (obj.get[T](field) |@| obj.getOption[String]("message") |@| - obj.getOption[String]("id")).map { - case ((value, message0), id) => - val message = - message0.map(msg => - if (msg.contains("\n")) { - "\n" + msg.stripMargin - } else { - msg - } - ) + obj.getOption[String]("id")).map { case ((value, message0), id) => + val message = + message0.map(msg => + if (msg.contains("\n")) { + "\n" + msg.stripMargin + } else { + msg + } + ) - new CustomMessage(value, message, id) + new CustomMessage(value, message, id) } } case els => diff --git a/scalafix-core/src/main/scala/scalafix/config/Regex.scala b/scalafix-core/src/main/scala/scalafix/config/Regex.scala index af2fc9722..327b99a92 100644 --- a/scalafix-core/src/main/scala/scalafix/config/Regex.scala +++ b/scalafix-core/src/main/scala/scalafix/config/Regex.scala @@ -13,12 +13,11 @@ class Regex( object Regex { implicit val regexDecoder: ConfDecoder[Regex] = - ConfDecoder.instance[Regex] { - case obj: Conf.Obj => - (obj.get[Pattern]("pattern") |@| obj.getOption[Int]("captureGroup")) - .map { - case (pattern, groupIndex) => new Regex(pattern, groupIndex) - } + ConfDecoder.instance[Regex] { case obj: Conf.Obj => + (obj.get[Pattern]("pattern") |@| obj.getOption[Int]("captureGroup")) + .map { case (pattern, groupIndex) => + new Regex(pattern, groupIndex) + } } implicit val customMessageRegexDecoder: ConfDecoder[CustomMessage[Regex]] = diff --git a/scalafix-core/src/main/scala/scalafix/internal/config/LogContext.scala b/scalafix-core/src/main/scala/scalafix/internal/config/LogContext.scala index 554cb80f9..235f4b8d9 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/config/LogContext.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/config/LogContext.scala @@ -9,8 +9,8 @@ case class LogContext( } object LogContext { - implicit def generate( - implicit line: sourcecode.Line, + implicit def generate(implicit + line: sourcecode.Line, file: sourcecode.File, enclosing: sourcecode.Enclosing ): LogContext = LogContext(line, file, enclosing) diff --git a/scalafix-core/src/main/scala/scalafix/internal/config/MetaconfigOps.scala b/scalafix-core/src/main/scala/scalafix/internal/config/MetaconfigOps.scala index 1b9e9c953..3f62891c6 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/config/MetaconfigOps.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/config/MetaconfigOps.scala @@ -31,8 +31,8 @@ object MetaconfigOps { res.product(configured).map { case (a, b) => b +: a } } } - def getKey[T](conf: Conf.Obj, path: String, extraNames: String*)( - implicit ev: ConfDecoder[T] + def getKey[T](conf: Conf.Obj, path: String, extraNames: String*)(implicit + ev: ConfDecoder[T] ): Configured[T] = { ConfGet.getKey(conf, path +: extraNames) match { case Some(value) => ev.read(value) diff --git a/scalafix-core/src/main/scala/scalafix/internal/config/ReaderUtil.scala b/scalafix-core/src/main/scala/scalafix/internal/config/ReaderUtil.scala index 489912617..446a0d2e1 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/config/ReaderUtil.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/config/ReaderUtil.scala @@ -17,17 +17,16 @@ object ReaderUtil { m: Map[String, T], additionalMessage: PartialFunction[String, String] = PartialFunction.empty ): ConfDecoder[T] = - ConfDecoder.instance[T] { - case Conf.Str(x) => - m.get(x) match { - case Some(y) => - Configured.Ok(y) - case None => - val available = m.keys.mkString(", ") - val extraMsg = additionalMessage.applyOrElse(x, (_: String) => "") - val msg = - s"Unknown input '$x'. Expected one of: $available. $extraMsg" - Configured.NotOk(ConfError.message(msg)) - } + ConfDecoder.instance[T] { case Conf.Str(x) => + m.get(x) match { + case Some(y) => + Configured.Ok(y) + case None => + val available = m.keys.mkString(", ") + val extraMsg = additionalMessage.applyOrElse(x, (_: String) => "") + val msg = + s"Unknown input '$x'. Expected one of: $available. $extraMsg" + Configured.NotOk(ConfError.message(msg)) + } } } diff --git a/scalafix-core/src/main/scala/scalafix/internal/config/ScalafixMetaconfigReaders.scala b/scalafix-core/src/main/scala/scalafix/internal/config/ScalafixMetaconfigReaders.scala index 6f6d02ea2..84ba19819 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/config/ScalafixMetaconfigReaders.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/config/ScalafixMetaconfigReaders.scala @@ -51,8 +51,8 @@ trait ScalafixMetaconfigReaders { object UriRuleString { def unapply(arg: Conf.Str): Option[(String, String)] = - UriRule.unapply(arg).map { - case (a, b) => a -> b.getSchemeSpecificPart + UriRule.unapply(arg).map { case (a, b) => + a -> b.getSchemeSpecificPart } } @@ -68,30 +68,28 @@ trait ScalafixMetaconfigReaders { private def isRuleKey(key: (String, Conf)) = ruleRegex.matcher(key._1).matches() def scalafixConfigEmptyRuleReader: ConfDecoder[(Conf, ScalafixConfig)] = - ConfDecoder.instance[(Conf, ScalafixConfig)] { - case Conf.Obj(values) => - val (rules, noRules) = values.partition(isRuleKey) - val ruleConf = - Configured.Ok(rules.lastOption.map(_._2).getOrElse(Conf.Lst())) - val config = - ScalafixConfig.ScalafixConfigDecoder.read(Conf.Obj(noRules)) - ruleConf.product(config) + ConfDecoder.instance[(Conf, ScalafixConfig)] { case Conf.Obj(values) => + val (rules, noRules) = values.partition(isRuleKey) + val ruleConf = + Configured.Ok(rules.lastOption.map(_._2).getOrElse(Conf.Lst())) + val config = + ScalafixConfig.ScalafixConfigDecoder.read(Conf.Obj(noRules)) + ruleConf.product(config) } def scalafixConfigConfDecoder( ruleDecoder: ConfDecoder[Rule], extraRules: List[String] = Nil ): ConfDecoder[(Rule, ScalafixConfig)] = - scalafixConfigEmptyRuleReader.flatMap { - case (ruleConf, config) => - val combinedRules: Conf.Lst = - if (extraRules.nonEmpty) - Conf.Lst(extraRules.map(Conf.Str)) - else - ruleConf match { - case rules @ Conf.Lst(_) => rules - case x => Conf.Lst(x :: Nil) - } - ruleDecoder.read(combinedRules).map(rule => rule -> config) + scalafixConfigEmptyRuleReader.flatMap { case (ruleConf, config) => + val combinedRules: Conf.Lst = + if (extraRules.nonEmpty) + Conf.Lst(extraRules.map(Conf.Str)) + else + ruleConf match { + case rules @ Conf.Lst(_) => rules + case x => Conf.Lst(x :: Nil) + } + ruleDecoder.read(combinedRules).map(rule => rule -> config) } private lazy val semanticRuleClass = classOf[SemanticRule] @@ -178,24 +176,25 @@ trait ScalafixMetaconfigReaders { implicit lazy val symbolReader: ConfDecoder[Symbol] = ConfDecoder.stringConfDecoder.map(Symbol.apply) private def parseSymbol(sym: String): Configured[Symbol] = - try Ok(Symbol(sym)) // Because https://github.com/scalameta/scalameta/issues/821 + try Ok( + Symbol(sym) + ) // Because https://github.com/scalameta/scalameta/issues/821 catch { case NonFatal(e) => ConfError.exception(e, 0).notOk } implicit lazy val symbolGlobalReader: ConfDecoder[Symbol.Global] = - ConfDecoder.instance[Symbol.Global] { - case Conf.Str(path) => - def symbolGlobal(symbol: Symbol): Configured[Symbol.Global] = - symbol match { - case g: Symbol.Global => Ok(g) - case els => - ConfError - .typeMismatch( - "Symbol.Global", - Conf.Str(s"$els: ${els.productPrefix}") - ) - .notOk - } - val toParse = SymbolOps.inferTrailingDot(path) - parseSymbol(toParse).andThen(symbolGlobal) + ConfDecoder.instance[Symbol.Global] { case Conf.Str(path) => + def symbolGlobal(symbol: Symbol): Configured[Symbol.Global] = + symbol match { + case g: Symbol.Global => Ok(g) + case els => + ConfError + .typeMismatch( + "Symbol.Global", + Conf.Str(s"$els: ${els.productPrefix}") + ) + .notOk + } + val toParse = SymbolOps.inferTrailingDot(path) + parseSymbol(toParse).andThen(symbolGlobal) } implicit lazy val AddGlobalImportReader: ConfDecoder[AddGlobalImport] = @@ -233,25 +232,24 @@ trait ScalafixMetaconfigReaders { implicit lazy val CustomMessagePattern: ConfDecoder[CustomMessage[Pattern]] = CustomMessage.decoder(field = "pattern") - implicit def EitherConfDecoder[A, B]( - implicit A: ConfDecoder[A], + implicit def EitherConfDecoder[A, B](implicit + A: ConfDecoder[A], B: ConfDecoder[B] ): ConfDecoder[Either[A, B]] = { def wrapLeft(a: A): Either[A, B] = Left(a) def wrapRight(b: B): Either[A, B] = Right(b) - ConfDecoder.instance[Either[A, B]] { - case conf => - B.map(wrapRight).orElse(A.map(wrapLeft)).read(conf) match { - case ok @ Ok(_) => ok - case NotOk(err) => - NotOk( - ConfError - .message( - "Failed to decode configuration for either of the following types:" - ) - .combine(err) - ) - } + ConfDecoder.instance[Either[A, B]] { case conf => + B.map(wrapRight).orElse(A.map(wrapLeft)).read(conf) match { + case ok @ Ok(_) => ok + case NotOk(err) => + NotOk( + ConfError + .message( + "Failed to decode configuration for either of the following types:" + ) + .combine(err) + ) + } } } } diff --git a/scalafix-core/src/main/scala/scalafix/internal/diff/DiffDisable.scala b/scalafix-core/src/main/scala/scalafix/internal/diff/DiffDisable.scala index 8ecb9a549..94a0ac990 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/diff/DiffDisable.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/diff/DiffDisable.scala @@ -26,14 +26,14 @@ object EmptyDiff extends DiffDisable { class FullDiffDisable(diffs: List[GitDiff]) extends DiffDisable { override def isEmpty: Boolean = diffs.isEmpty - private val newFiles: Set[String] = diffs.collect { - case NewFile(path) => path.toAbsolutePath.toString + private val newFiles: Set[String] = diffs.collect { case NewFile(path) => + path.toAbsolutePath.toString }.toSet private val modifiedFiles: Map[String, IntervalSet] = diffs.collect { case ModifiedFile(path, changes) => { - val ranges = changes.map { - case GitChange(start, end) => (start, end) + val ranges = changes.map { case GitChange(start, end) => + (start, end) } path.toAbsolutePath.toString -> IntervalSet(ranges) } @@ -78,8 +78,8 @@ class FullDiffDisable(diffs: List[GitDiff]) extends DiffDisable { diffs.foreach { case ModifiedFile(path, changes) => { add(path.toString) - changes.foreach { - case GitChange(start, end) => add(s" [$start, $end]") + changes.foreach { case GitChange(start, end) => + add(s" [$start, $end]") } } case _ => () diff --git a/scalafix-core/src/main/scala/scalafix/internal/patch/EscapeHatch.scala b/scalafix-core/src/main/scala/scalafix/internal/patch/EscapeHatch.scala index 70d70412a..a42081863 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/patch/EscapeHatch.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/patch/EscapeHatch.scala @@ -23,7 +23,8 @@ import scalafix.v0._ // used to cross-compile import scala.collection.compat._ // scalafix:ok -/** EscapeHatch is an algorithm to selectively disable rules. There +/** + * EscapeHatch is an algorithm to selectively disable rules. There * are two mechanisms to do so: anchored comments and the * standard `@SuppressWarnings` annotation. The latter takes * precedence over the former in case there are overlaps. @@ -40,20 +41,19 @@ class EscapeHatch private ( )(implicit ctx: RuleCtx): (Patch, List[RuleDiagnostic]) = { var patchBuilder = Patch.empty val diagnostics = List.newBuilder[RuleDiagnostic] - patchesByName.foreach { - case (rule, rulePatch) => - PatchInternals.foreachPatchUnit(rulePatch) { - case LintPatch(message) => - diagnostics += message.toDiagnostic(rule, ctx.config) - case rewritePatch => - patchBuilder += rewritePatch - } + patchesByName.foreach { case (rule, rulePatch) => + PatchInternals.foreachPatchUnit(rulePatch) { + case LintPatch(message) => + diagnostics += message.toDiagnostic(rule, ctx.config) + case rewritePatch => + patchBuilder += rewritePatch + } } (patchBuilder, diagnostics.result()) } - def filter(patchesByName: Map[RuleName, Patch])( - implicit ctx: RuleCtx, + def filter(patchesByName: Map[RuleName, Patch])(implicit + ctx: RuleCtx, index: SemanticdbIndex ): (Iterable[Patch], List[RuleDiagnostic]) = { if (isEmpty) return { @@ -102,8 +102,8 @@ class EscapeHatch private ( case e => e } - val patches = patchesByName.map { - case (name, patch) => loop(name, patch) + val patches = patchesByName.map { case (name, patch) => + loop(name, patch) } val unusedWarnings = (annotatedEscapes.unusedEscapes(usedEscapes) ++ @@ -155,7 +155,8 @@ object EscapeHatch { ) } - /** Rules are disabled via standard `@SuppressWarnings` annotations. The + /** + * Rules are disabled via standard `@SuppressWarnings` annotations. The * annotation can be placed in class, object, trait, type, def, val, var, * parameters and constructor definitions. * @@ -191,7 +192,9 @@ object EscapeHatch { def unusedEscapes(used: collection.Set[EscapeFilter]): Set[Position] = escapeTree.valuesIterator.flatten.collect { case f @ EscapeFilter(_, rulePos, _, _) - if !used(f) && rulePos.text.startsWith(OptionalRulePrefix) => // only report unused warnings for Scalafix rules + if !used(f) && rulePos.text.startsWith( + OptionalRulePrefix + ) => // only report unused warnings for Scalafix rules rulePos }.toSet } @@ -208,26 +211,25 @@ object EscapeHatch { private def collectEscapes(tree: Tree): AnnotatedEscapes = { val escapes = - tree.collect { - case t @ Mods(SuppressWarningsArgs(args)) => - val start = EscapeOffset(t.pos.start) - val end = EscapeOffset(t.pos.end) - val rules = rulesWithPosition(args) - val (matchAll, matchOne) = rules.partition(_._1 == SuppressAll) - val filters = ListBuffer.empty[EscapeFilter] - - // 'all' should come before individual rules so that we can warn unused rules later - for ((_, rulePos) <- matchAll) { - val matcher = FilterMatcher.matchEverything - filters += EscapeFilter(matcher, rulePos, start, Some(end)) - } - for ((rule, rulePos) <- matchOne) { - val unprefixedRuleName = rule.stripPrefix(OptionalRulePrefix) - val matcher = FilterMatcher(unprefixedRuleName) - filters += EscapeFilter(matcher, rulePos, start, Some(end)) - } + tree.collect { case t @ Mods(SuppressWarningsArgs(args)) => + val start = EscapeOffset(t.pos.start) + val end = EscapeOffset(t.pos.end) + val rules = rulesWithPosition(args) + val (matchAll, matchOne) = rules.partition(_._1 == SuppressAll) + val filters = ListBuffer.empty[EscapeFilter] + + // 'all' should come before individual rules so that we can warn unused rules later + for ((_, rulePos) <- matchAll) { + val matcher = FilterMatcher.matchEverything + filters += EscapeFilter(matcher, rulePos, start, Some(end)) + } + for ((rule, rulePos) <- matchOne) { + val unprefixedRuleName = rule.stripPrefix(OptionalRulePrefix) + val matcher = FilterMatcher(unprefixedRuleName) + filters += EscapeFilter(matcher, rulePos, start, Some(end)) + } - (start, filters.result()) + (start, filters.result()) } new AnnotatedEscapes(TreeMap(escapes: _*)) } @@ -236,32 +238,31 @@ object EscapeHatch { def unapply(mods: List[Mod]): Option[List[Term]] = mods.collectFirst { case Mod.Annot( - Init( - Type.Name(SuppressWarnings), - _, - List(Term.Apply(Term.Name("Array"), args) :: Nil) - ) + Init( + Type.Name(SuppressWarnings), + _, + List(Term.Apply(Term.Name("Array"), args) :: Nil) + ) ) => args case Mod.Annot( - Init( - Type.Select(_, Type.Name(SuppressWarnings)), - _, - List(Term.Apply(Term.Name("Array"), args) :: Nil) - ) + Init( + Type.Select(_, Type.Name(SuppressWarnings)), + _, + List(Term.Apply(Term.Name("Array"), args) :: Nil) + ) ) => args } } private def rulesWithPosition(rules: List[Term]): List[(String, Position)] = - rules.collect { - case lit @ Lit.String(rule) => - // get the exact position of the rule name - val lo = lit.pos.start + lit.pos.text.indexOf(rule) - val hi = lo + rule.length - rule -> Position.Range(lit.pos.input, lo, hi) + rules.collect { case lit @ Lit.String(rule) => + // get the exact position of the rule name + val lo = lit.pos.start + lit.pos.text.indexOf(rule) + val hi = lo + rule.length + rule -> Position.Range(lit.pos.input, lo, hi) } } @@ -374,9 +375,8 @@ object EscapeHatch { EscapeFilter(FilterMatcher.matchEverything, anchor.pos, start, end) ) } else { - rulesPos.map { - case (rule, pos) => - EscapeFilter(FilterMatcher(rule), pos, start, end) + rulesPos.map { case (rule, pos) => + EscapeFilter(FilterMatcher(rule), pos, start, end) } } } @@ -530,17 +530,15 @@ object EscapeHatch { ((source, target): @unchecked) match { case (AllRules, SomeRules(tgt)) => var newTgt = tgt - rulesPos.foreach { - case (rule, pos) => - if (!newTgt(rule)) newTgt += rule else unused += pos + rulesPos.foreach { case (rule, pos) => + if (!newTgt(rule)) newTgt += rule else unused += pos } (AllRules, SomeRules(newTgt)) case (SomeRules(src), AllRules) => var newSrc = src - rulesPos.foreach { - case (rule, pos) => - if (newSrc(rule)) newSrc -= rule else unused += pos + rulesPos.foreach { case (rule, pos) => + if (newSrc(rule)) newSrc -= rule else unused += pos } (SomeRules(newSrc), AllRules) } diff --git a/scalafix-core/src/main/scala/scalafix/internal/patch/ImportPatchOps.scala b/scalafix-core/src/main/scala/scalafix/internal/patch/ImportPatchOps.scala index d529a4f9a..9c5a3dc53 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/patch/ImportPatchOps.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/patch/ImportPatchOps.scala @@ -142,19 +142,18 @@ object ImportPatchOps { if (ctx.config.groupImportsByPrefix) importersToAdd .groupBy(_.ref.syntax) - .map { - case (_, is) => - Importer( - is.head.ref, - is.flatMap(_.importees) - .sortBy({ - case Importee.Name(n) => n.value - case Importee.Rename(n, _) => n.value - case Importee.Unimport(n) => n.value - case Importee.Wildcard() => '\uFFFF'.toString - }) - .toList - ) + .map { case (_, is) => + Importer( + is.head.ref, + is.flatMap(_.importees) + .sortBy({ + case Importee.Name(n) => n.value + case Importee.Rename(n, _) => n.value + case Importee.Unimport(n) => n.value + case Importee.Wildcard() => '\uFFFF'.toString + }) + .toList + ) } .toList else importersToAdd @@ -185,17 +184,16 @@ object ImportPatchOps { if hasRemovedImportee => ctx .toks(importer) - .collectFirst { - case open @ Token.LeftBrace() => - ctx.matchingParens - .close(open) - .map { close => - ctx.removeToken(open) + - removeSpaces(ctx.tokenList.trailing(open)) + - ctx.removeToken(close) + - removeSpaces(ctx.tokenList.leading(close)) - } - .asPatch + .collectFirst { case open @ Token.LeftBrace() => + ctx.matchingParens + .close(open) + .map { close => + ctx.removeToken(open) + + removeSpaces(ctx.tokenList.trailing(open)) + + ctx.removeToken(close) + + removeSpaces(ctx.tokenList.leading(close)) + } + .asPatch } .asPatch case _ => Patch.empty diff --git a/scalafix-core/src/main/scala/scalafix/internal/patch/LegacyPatchOps.scala b/scalafix-core/src/main/scala/scalafix/internal/patch/LegacyPatchOps.scala index 8ab87e62c..1815e5f88 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/patch/LegacyPatchOps.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/patch/LegacyPatchOps.scala @@ -75,8 +75,8 @@ trait LegacyPatchOps extends PatchOps { )(implicit noop: DummyImplicit, index: SemanticdbIndex): Patch = Patch.replaceSymbols(toReplace.toSeq: _*) @deprecated(DeprecationMessage, "0.6.0") - final def renameSymbol(fromSymbol: Symbol.Global, toName: String)( - implicit index: SemanticdbIndex + final def renameSymbol(fromSymbol: Symbol.Global, toName: String)(implicit + index: SemanticdbIndex ): Patch = ReplaceSymbol(fromSymbol, Root(Signature.Term(toName))) @deprecated(DeprecationMessage, "0.6.0") diff --git a/scalafix-core/src/main/scala/scalafix/internal/patch/PatchInternals.scala b/scalafix-core/src/main/scala/scalafix/internal/patch/PatchInternals.scala index 7146169b7..f915d3ce1 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/patch/PatchInternals.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/patch/PatchInternals.scala @@ -94,8 +94,7 @@ object PatchInternals { ) } - def treePatchApply(patch: Patch)( - implicit + def treePatchApply(patch: Patch)(implicit ctx: v0.RuleCtx, index: v0.SemanticdbIndex ): Iterable[TokenPatch] = { diff --git a/scalafix-core/src/main/scala/scalafix/internal/patch/ReplaceSymbolOps.scala b/scalafix-core/src/main/scala/scalafix/internal/patch/ReplaceSymbolOps.scala index 096cd163a..693431e8c 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/patch/ReplaceSymbolOps.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/patch/ReplaceSymbolOps.scala @@ -26,13 +26,13 @@ object ReplaceSymbolOps { val moves: Map[String, Symbol.Global] = moveSymbols.iterator.flatMap { case ReplaceSymbol( - term @ Symbol.Global(_, Signature.Method(_, _)), - to + term @ Symbol.Global(_, Signature.Method(_, _)), + to ) => (term.syntax -> to) :: Nil case ReplaceSymbol( - term @ Symbol.Global(qual, Signature.Term(name)), - to + term @ Symbol.Global(qual, Signature.Term(name)), + to ) => (term.syntax -> to) :: (Symbol.Global(qual, Signature.Type(name)).syntax -> to) :: @@ -48,14 +48,14 @@ object ReplaceSymbolOps { ctx.replaceTree(a, b) -> sym // ref is longer case ( - Select(qual, Name(_)), - Symbol.Global(Symbol.None, SignatureName(b)) + Select(qual, Name(_)), + Symbol.Global(Symbol.None, SignatureName(b)) ) => ctx.replaceTree(qual, b) -> Symbol.None // recurse case ( - Select(qual: Ref, a @ Name(_)), - Symbol.Global(symQual, SignatureName(b)) + Select(qual: Ref, a @ Name(_)), + Symbol.Global(symQual, SignatureName(b)) ) => val (patch, toImport) = loop(qual, symQual) (patch + ctx.replaceTree(a, b)) -> toImport @@ -73,31 +73,30 @@ object ReplaceSymbolOps { case Symbol.Multi(syms) => syms case els => els :: Nil } - .collectFirst { - case Moved(out) => out + .collectFirst { case Moved(out) => + out } result } } - val patches = ctx.tree.collect { - case n @ Move(to) => - // was this written as `to = "blah"` instead of `to = _root_.blah` - val isSelected = to match { - case Root(_) => false - case _ => true - } - n.parent match { - case Some(i @ Importee.Name(_)) => - ctx.removeImportee(i) - case Some(parent @ Select(_, `n`)) if isSelected => - val (patch, imp) = loop(parent, to) - ctx.addGlobalImport(imp) + patch - case Some(_) => - val addImport = - if (n.isDefinition) Patch.empty - else ctx.addGlobalImport(to) - addImport + ctx.replaceTree(n, to.signature.name) - } + val patches = ctx.tree.collect { case n @ Move(to) => + // was this written as `to = "blah"` instead of `to = _root_.blah` + val isSelected = to match { + case Root(_) => false + case _ => true + } + n.parent match { + case Some(i @ Importee.Name(_)) => + ctx.removeImportee(i) + case Some(parent @ Select(_, `n`)) if isSelected => + val (patch, imp) = loop(parent, to) + ctx.addGlobalImport(imp) + patch + case Some(_) => + val addImport = + if (n.isDefinition) Patch.empty + else ctx.addGlobalImport(to) + addImport + ctx.replaceTree(n, to.signature.name) + } } patches.asPatch } diff --git a/scalafix-core/src/main/scala/scalafix/internal/rule/RuleCtxImpl.scala b/scalafix-core/src/main/scala/scalafix/internal/rule/RuleCtxImpl.scala index abed911bd..9a9ebe6a9 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/rule/RuleCtxImpl.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/rule/RuleCtxImpl.scala @@ -25,7 +25,7 @@ class RuleCtxImpl( with LegacyPatchOps { ctx => def syntax: String = s"""${tree.input.syntax} - |${logger.revealWhitespace(tree.syntax.take(100))}""".stripMargin + |${logger.revealWhitespace(tree.syntax.take(100))}""".stripMargin override def toString: String = syntax def toks(t: Tree): Tokens = t.tokens(config.dialect) lazy val tokens: Tokens = tree.tokens(config.dialect) @@ -44,8 +44,8 @@ class RuleCtxImpl( // Debug utilities def index(implicit index: SemanticdbIndex): SemanticdbIndex = index - def debugIndex()( - implicit index: SemanticdbIndex, + def debugIndex()(implicit + index: SemanticdbIndex, fileLine: FileLine ): Unit = { val db = this.index(index) diff --git a/scalafix-core/src/main/scala/scalafix/internal/util/ClassloadRule.scala b/scalafix-core/src/main/scala/scalafix/internal/util/ClassloadRule.scala index b9def5217..e8811541a 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/util/ClassloadRule.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/util/ClassloadRule.scala @@ -70,8 +70,8 @@ class ClassloadRule[T](classLoader: ClassLoader)(implicit ev: ClassTag[T]) { else s" or constructor matching arguments $args" throw new IllegalArgumentException( s"""No suitable constructor on $clazz. - |Expected : zero argument constructor $argsMsg - |Found : $constructors + |Expected : zero argument constructor $argsMsg + |Found : $constructors """.stripMargin ) } @@ -109,13 +109,13 @@ class ClassloadRule[T](classLoader: ClassLoader)(implicit ev: ClassTag[T]) { val failures = result.collect { case util.Failure(e) => e } def pretty(ex: Throwable): String = s"""$ex - | ${ex.getStackTrace.take(10).mkString(" \n")}""".stripMargin + | ${ex.getStackTrace.take(10).mkString(" \n")}""".stripMargin if (successes.nonEmpty) Success(successes.head) else { util.Failure( new IllegalArgumentException( s"""Unable to load rule $fqcn with args $args. Tried the following: - |${failures.map(pretty).mkString("\n")}""".stripMargin + |${failures.map(pretty).mkString("\n")}""".stripMargin ) ) } diff --git a/scalafix-core/src/main/scala/scalafix/internal/util/EagerInMemorySemanticdbIndex.scala b/scalafix-core/src/main/scala/scalafix/internal/util/EagerInMemorySemanticdbIndex.scala index 29c68810d..a5be5953d 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/util/EagerInMemorySemanticdbIndex.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/util/EagerInMemorySemanticdbIndex.scala @@ -86,12 +86,15 @@ case class EagerInMemorySemanticdbIndex( table.info(symbol).orElse { val msym = v0.Symbol(symbol) denotation(msym).map(denot => - denotationToSymbolInformation(symbol, denot, { - msym match { - case v0.Symbol.Global(owner, _) => owner.syntax - case _ => "" + denotationToSymbolInformation( + symbol, + denot, { + msym match { + case v0.Symbol.Global(owner, _) => owner.syntax + case _ => "" + } } - }) + ) ) } } diff --git a/scalafix-core/src/main/scala/scalafix/internal/util/Failure.scala b/scalafix-core/src/main/scala/scalafix/internal/util/Failure.scala index 36ea87533..be8124c27 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/util/Failure.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/util/Failure.scala @@ -21,9 +21,9 @@ object Failure { extends Failure( InvariantFailedException( s"""Cannot mix two different SemanticdbIndex inside the same patch. - |SemanticdbIndex 1: $a - |RuleCtx 2: $b - |""".stripMargin + |SemanticdbIndex 1: $a + |RuleCtx 2: $b + |""".stripMargin ) ) case class Unsupported(msg: String) diff --git a/scalafix-core/src/main/scala/scalafix/internal/util/IntervalSet.scala b/scalafix-core/src/main/scala/scalafix/internal/util/IntervalSet.scala index 97a960633..c1d2c1dfa 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/util/IntervalSet.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/util/IntervalSet.scala @@ -29,9 +29,8 @@ class IntervalSet(range: BitSet) { interval.result() } - val is = intervals.map { - case (start, end) => - s"[$start, $end]" + val is = intervals.map { case (start, end) => + s"[$start, $end]" } s"""IntervalSet(${is.mkString(", ")})""" diff --git a/scalafix-core/src/main/scala/scalafix/internal/util/PrettyType.scala b/scalafix-core/src/main/scala/scalafix/internal/util/PrettyType.scala index e36001acb..592a4799e 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/util/PrettyType.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/util/PrettyType.scala @@ -269,8 +269,10 @@ class PrettyType private ( inits, Self(Name(""), None), declarations.flatMap { i => - if (!i.kind.isConstructor && - !i.isVarSetter) toStat(i) + if ( + !i.kind.isConstructor && + !i.isVarSetter + ) toStat(i) else Nil } ) @@ -329,9 +331,11 @@ class PrettyType private ( inits, Self(Name(""), None), declarations.flatMap { i => - if (!i.kind.isConstructor && + if ( + !i.kind.isConstructor && !i.isVarSetter && - !isSyntheticMember(i)) toStat(i) + !isSyntheticMember(i) + ) toStat(i) else Nil } ) @@ -446,9 +450,11 @@ class PrettyType private ( Term.Name(info.displayName) case QualifyStrategy.Readable => val owner = this.info(info.owner) - if (owner.kind.isPackageObject || + if ( + owner.kind.isPackageObject || owner.kind.isPackage || - (owner.kind.isObject && info.kind.isType)) { + (owner.kind.isObject && info.kind.isType) + ) { imports += info.symbol Term.Name(info.displayName) } else { @@ -478,16 +484,20 @@ class PrettyType private ( name } else { val owner = this.info(info.owner) - if (shorten.isReadable && ( + if ( + shorten.isReadable && ( owner.kind.isPackage || - owner.kind.isPackageObject || - (owner.kind.isObject && info.kind.isType) - )) { + owner.kind.isPackageObject || + (owner.kind.isObject && info.kind.isType) + ) + ) { imports += info.symbol name - } else if (owner.kind.isPackage || + } else if ( + owner.kind.isPackage || owner.kind.isObject || - info.language.isJava) { + info.language.isJava + ) { Type.Select(toTermRef(owner), name) } else if (owner.kind.isClass || owner.kind.isTrait) { Type.Project(toTypeRef(owner), name) @@ -607,8 +617,8 @@ class PrettyType private ( case head => head -> types.iterator.drop(1) } - tail.foldLeft(toType(head)) { - case (accum, next) => Type.With(accum, toType(next)) + tail.foldLeft(toType(head)) { case (accum, next) => + Type.With(accum, toType(next)) } case s.UniversalType(Some(typeParameters), underlying) => val universalName = t"T" diff --git a/scalafix-core/src/main/scala/scalafix/internal/util/ProductStructure.scala b/scalafix-core/src/main/scala/scalafix/internal/util/ProductStructure.scala index 70139b43c..15b03aa40 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/util/ProductStructure.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/util/ProductStructure.scala @@ -85,10 +85,10 @@ class ProductStructure( val allNamesAreUnhelpful = fieldNames.forall(isUnhelpfulFieldName) val args = if (showFieldNames && !allNamesAreUnhelpful) { - val table = fieldNames.zip(values).map { - case (fieldName, fieldValue) => + val table = + fieldNames.zip(values).map { case (fieldName, fieldValue) => Doc.text(fieldName) + Doc.text(" = ") + fieldValue - } + } Doc.intercalate(Doc.comma + Doc.line, table) } else { Doc.intercalate(Doc.comma + Doc.line, values) diff --git a/scalafix-core/src/main/scala/scalafix/internal/util/QualifyStrategy.scala b/scalafix-core/src/main/scala/scalafix/internal/util/QualifyStrategy.scala index 48360150a..b74dfd7c4 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/util/QualifyStrategy.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/util/QualifyStrategy.scala @@ -11,7 +11,8 @@ object QualifyStrategy { /** Fully quality up to and including _root_ package */ case object Full extends QualifyStrategy - /** Optimize for human-readability + /** + * Optimize for human-readability * * In general, tries to quality up to the closest enclosing package but with special handling in * a couple of other cases like type aliases inside of objects. diff --git a/scalafix-core/src/main/scala/scalafix/internal/util/SymbolOps.scala b/scalafix-core/src/main/scala/scalafix/internal/util/SymbolOps.scala index bbc87be25..52eea0b46 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/util/SymbolOps.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/util/SymbolOps.scala @@ -31,8 +31,8 @@ object SymbolOps { Symbol.Global(apply(), signature) def unapply(arg: Symbol): Option[Signature] = arg match { case Symbol.Global( - Symbol.Global(Symbol.None, Signature.Package("_root_")), - sig + Symbol.Global(Symbol.None, Signature.Package("_root_")), + sig ) => Some(sig) case _ => diff --git a/scalafix-core/src/main/scala/scalafix/internal/v0/LegacyRuleCtx.scala b/scalafix-core/src/main/scala/scalafix/internal/v0/LegacyRuleCtx.scala index d01d1e07d..9b3779f72 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/v0/LegacyRuleCtx.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/v0/LegacyRuleCtx.scala @@ -24,8 +24,8 @@ class LegacyRuleCtx(doc: SyntacticDocument) override def comments: AssociatedComments = doc.comments override def index(implicit index: SemanticdbIndex): SemanticdbIndex = index - override def debugIndex()( - implicit index: SemanticdbIndex, + override def debugIndex()(implicit + index: SemanticdbIndex, fileLine: FileLine ): Unit = throw new UnsupportedOperationException diff --git a/scalafix-core/src/main/scala/scalafix/internal/v1/DocumentFromProtobuf.scala b/scalafix-core/src/main/scala/scalafix/internal/v1/DocumentFromProtobuf.scala index 8dab62901..d1aab0523 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/v1/DocumentFromProtobuf.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/v1/DocumentFromProtobuf.scala @@ -10,8 +10,8 @@ object DocumentFromProtobuf { def convert(synth: s.Synthetic, doc: InternalSemanticDoc): SemanticTree = new DocumentFromProtobuf(synth)(new SemanticDocument(doc)).stree(synth.tree) } -final class DocumentFromProtobuf(original: s.Synthetic)( - implicit doc: SemanticDocument +final class DocumentFromProtobuf(original: s.Synthetic)(implicit + doc: SemanticDocument ) { val convert = new SymtabFromProtobuf(doc) def stree(t: s.Tree): SemanticTree = { diff --git a/scalafix-core/src/main/scala/scalafix/internal/v1/FingerprintOps.scala b/scalafix-core/src/main/scala/scalafix/internal/v1/FingerprintOps.scala index 51e46a0a2..393c1e9d5 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/v1/FingerprintOps.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/v1/FingerprintOps.scala @@ -21,9 +21,9 @@ object FingerprintOps { val hexChars = new Array[Char](bytes.length * 2) var j = 0 while (j < bytes.length) { - val v: Int = bytes(j) & 0xFF + val v: Int = bytes(j) & 0xff hexChars(j * 2) = hexArray(v >>> 4) - hexChars(j * 2 + 1) = hexArray(v & 0x0F) + hexChars(j * 2 + 1) = hexArray(v & 0x0f) j += 1 } new String(hexChars) diff --git a/scalafix-core/src/main/scala/scalafix/internal/v1/InternalSemanticDoc.scala b/scalafix-core/src/main/scala/scalafix/internal/v1/InternalSemanticDoc.scala index c8a73b887..98e17c22e 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/v1/InternalSemanticDoc.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/v1/InternalSemanticDoc.scala @@ -105,7 +105,9 @@ final class InternalSemanticDoc( private[this] lazy val locals = textDocument.symbols.iterator.collect { case info if info.symbol.startsWith("local") || - info.symbol.contains("$anon") // NOTE(olafur) workaround for a semanticdb-scala issue. + info.symbol.contains( + "$anon" + ) // NOTE(olafur) workaround for a semanticdb-scala issue. => info.symbol -> info }.toMap diff --git a/scalafix-core/src/main/scala/scalafix/internal/v1/TreePos.scala b/scalafix-core/src/main/scala/scalafix/internal/v1/TreePos.scala index 7025abf06..cb4525774 100644 --- a/scalafix-core/src/main/scala/scalafix/internal/v1/TreePos.scala +++ b/scalafix-core/src/main/scala/scalafix/internal/v1/TreePos.scala @@ -12,9 +12,11 @@ object TreePos { ): T = { val syntax = name.syntax // workaround for https://github.com/scalameta/scalameta/issues/1083 - if (syntax.startsWith("(") && + if ( + syntax.startsWith("(") && syntax.endsWith(")") && - syntax != name.value) { + syntax != name.value + ) { val pos = Position.Range(name.pos.input, name.pos.start + 1, name.pos.end - 1) val t = f(pos) diff --git a/scalafix-core/src/main/scala/scalafix/patch/Patch.scala b/scalafix-core/src/main/scala/scalafix/patch/Patch.scala index 28e8accb1..d26a3ee8f 100644 --- a/scalafix-core/src/main/scala/scalafix/patch/Patch.scala +++ b/scalafix-core/src/main/scala/scalafix/patch/Patch.scala @@ -144,16 +144,15 @@ object Patch { def replaceSymbols( toReplace: (String, String)* )(implicit c: SemanticContext): Patch = - toReplace.foldLeft(Patch.empty) { - case (a, (from, to)) => - val (fromSymbol, toSymbol) = - ScalafixMetaconfigReaders.parseReplaceSymbol(from, to).get - a + ReplaceSymbol(fromSymbol, toSymbol) + toReplace.foldLeft(Patch.empty) { case (a, (from, to)) => + val (fromSymbol, toSymbol) = + ScalafixMetaconfigReaders.parseReplaceSymbol(from, to).get + a + ReplaceSymbol(fromSymbol, toSymbol) } /** Replace occurrences of fromSymbol to use toName instead */ - def renameSymbol(fromSymbol: v1.Symbol, toName: String)( - implicit c: SemanticContext + def renameSymbol(fromSymbol: v1.Symbol, toName: String)(implicit + c: SemanticContext ): Patch = ReplaceSymbol( v0.Symbol(fromSymbol.value).asInstanceOf[v0.Symbol.Global], diff --git a/scalafix-core/src/main/scala/scalafix/patch/PatchOps.scala b/scalafix-core/src/main/scala/scalafix/patch/PatchOps.scala index fa1229ac4..cb5dc852b 100644 --- a/scalafix-core/src/main/scala/scalafix/patch/PatchOps.scala +++ b/scalafix-core/src/main/scala/scalafix/patch/PatchOps.scala @@ -103,8 +103,8 @@ trait PatchOps { * Experimental. May produce broken code in some cases. This * is the same patch as `replace:com.foo/com.bar` from sbt-scalafix. */ - def replaceSymbol(fromSymbol: Symbol.Global, toSymbol: Symbol.Global)( - implicit index: SemanticdbIndex + def replaceSymbol(fromSymbol: Symbol.Global, toSymbol: Symbol.Global)(implicit + index: SemanticdbIndex ): Patch /** @@ -113,8 +113,8 @@ trait PatchOps { * toName should be a legal identifier, it cannot be a tree such as `foo()`. * Use this patch for example to rename a methods on a class. */ - def renameSymbol(fromSymbol: Symbol.Global, toName: String)( - implicit index: SemanticdbIndex + def renameSymbol(fromSymbol: Symbol.Global, toName: String)(implicit + index: SemanticdbIndex ): Patch /** @@ -122,8 +122,8 @@ trait PatchOps { * * String values are treated as Symbol.Global. */ - def replaceSymbols(toReplace: (String, String)*)( - implicit index: SemanticdbIndex + def replaceSymbols(toReplace: (String, String)*)(implicit + index: SemanticdbIndex ): Patch /** diff --git a/scalafix-core/src/main/scala/scalafix/syntax/package.scala b/scalafix-core/src/main/scala/scalafix/syntax/package.scala index 9196b9232..da7a3abc9 100644 --- a/scalafix-core/src/main/scala/scalafix/syntax/package.scala +++ b/scalafix-core/src/main/scala/scalafix/syntax/package.scala @@ -12,8 +12,8 @@ import scalafix.util.TreeOps import scalafix.v0.Symbol package object syntax { - implicit class XtensionRefSymbolOpt(tree: Tree)( - implicit index: v0.SemanticdbIndex + implicit class XtensionRefSymbolOpt(tree: Tree)(implicit + index: v0.SemanticdbIndex ) { def symbol: Option[Symbol] = index.symbol(tree.pos) def denotation: Option[v0.Denotation] = index.denotation(tree) @@ -24,8 +24,8 @@ package object syntax { case _ => None } } - implicit class XtensionSymbolSemanticdbIndex(symbol: Symbol)( - implicit index: v0.SemanticdbIndex + implicit class XtensionSymbolSemanticdbIndex(symbol: Symbol)(implicit + index: v0.SemanticdbIndex ) { def denotation: Option[v0.Denotation] = index.denotation(symbol) def resultType: Option[Type] = diff --git a/scalafix-core/src/main/scala/scalafix/util/TokenList.scala b/scalafix-core/src/main/scala/scalafix/util/TokenList.scala index 10b43843b..737130b57 100644 --- a/scalafix-core/src/main/scala/scalafix/util/TokenList.scala +++ b/scalafix-core/src/main/scala/scalafix/util/TokenList.scala @@ -5,7 +5,7 @@ import scala.meta.tokens.Tokens import scalafix.util.Compat._ -/** Helper to traverse tokens as a doubly linked list. */ +/** Helper to traverse tokens as a doubly linked list. */ final class TokenList private (tokens: Tokens) { def trailing(token: Token): View[Token] = tokens.view.slice(tok2idx(token) + 1, tokens.length) @@ -22,7 +22,8 @@ final class TokenList private (tokens: Tokens) { } map .result() - .withDefault(t => throw new NoSuchElementException(s"token not found: $t") + .withDefault(t => + throw new NoSuchElementException(s"token not found: $t") ) } @@ -32,7 +33,8 @@ final class TokenList private (tokens: Tokens) { def slice(from: Token, to: Token): SeqView[Token] = tokens.view.slice(tok2idx(from), tok2idx(to)) - /** Returns the next/trailing token or the original token if none exists. + /** + * Returns the next/trailing token or the original token if none exists. * * @note You need to guard against infinite recursion if iterating through * a list of tokens using this method. This method does not fail @@ -46,7 +48,8 @@ final class TokenList private (tokens: Tokens) { } } - /** Returns the previous/leading token or the original token if none exists. + /** + * Returns the previous/leading token or the original token if none exists. * * @note You need to guard against infinite recursion if iterating through * a list of tokens using this method. This method does not fail diff --git a/scalafix-core/src/main/scala/scalafix/util/TokenOps.scala b/scalafix-core/src/main/scala/scalafix/util/TokenOps.scala index e09223312..08fb56320 100644 --- a/scalafix-core/src/main/scala/scalafix/util/TokenOps.scala +++ b/scalafix-core/src/main/scala/scalafix/util/TokenOps.scala @@ -4,7 +4,8 @@ import scala.meta.tokens.Token object TokenOps { - /** Returns true if this token is an identifier that requires a leading space before colon. + /** + * Returns true if this token is an identifier that requires a leading space before colon. * * Example: * needsLeadingSpaceBeforeColon(foo_) // true @@ -12,8 +13,7 @@ object TokenOps { * val foo_ : Int = 2 // OK * val foo_: Int = 2 // ERROR * val foo: Int = 2 // OK - * - **/ + */ def needsLeadingSpaceBeforeColon(ident: Token): Boolean = ident match { case Token.Ident(_) => ident.syntax.lastOption.exists { diff --git a/scalafix-core/src/main/scala/scalafix/util/TreeOps.scala b/scalafix-core/src/main/scala/scalafix/util/TreeOps.scala index 1f13991ea..a4c8ce1cc 100644 --- a/scalafix-core/src/main/scala/scalafix/util/TreeOps.scala +++ b/scalafix-core/src/main/scala/scalafix/util/TreeOps.scala @@ -60,8 +60,8 @@ object TreeOps { for { parent <- t.parent owner <- loop(parent) - next = chain(p.ref).foldRight(owner) { - case (n, o) => Symbols.Global(o, Descriptor.Package(n.value)) + next = chain(p.ref).foldRight(owner) { case (n, o) => + Symbols.Global(o, Descriptor.Package(n.value)) } } yield next case d: Member => diff --git a/scalafix-core/src/main/scala/scalafix/v0/LintCategory.scala b/scalafix-core/src/main/scala/scalafix/v0/LintCategory.scala index 4d5e48d2d..c504408b8 100644 --- a/scalafix-core/src/main/scala/scalafix/v0/LintCategory.scala +++ b/scalafix-core/src/main/scala/scalafix/v0/LintCategory.scala @@ -5,7 +5,8 @@ import scala.meta.inputs.Position import scalafix.internal.config.LintConfig import scalafix.lint.LintSeverity -/** A unique identifier for one kind of a linter message. +/** + * A unique identifier for one kind of a linter message. * * @param id a string ID for this message, typically the name of the * assigned variable. If id is empty, then the name of the diff --git a/scalafix-core/src/main/scala/scalafix/v0/LintMessage.scala b/scalafix-core/src/main/scala/scalafix/v0/LintMessage.scala index 21db378b7..a1a3d96ca 100644 --- a/scalafix-core/src/main/scala/scalafix/v0/LintMessage.scala +++ b/scalafix-core/src/main/scala/scalafix/v0/LintMessage.scala @@ -4,7 +4,8 @@ import scala.meta.Position import scalafix.lint.LintSeverity -/** An observation of a LintCategory at a particular position +/** + * An observation of a LintCategory at a particular position * * @param message The message to display to the user. If empty, LintID.explanation * is used instead. @@ -25,9 +26,9 @@ final case class LintMessage( val explanation = if (explain) s""" - |Explanation: - |${category.explanation} - |""".stripMargin + |Explanation: + |${category.explanation} + |""".stripMargin else "" s"[${category.id}] $message$explanation" diff --git a/scalafix-core/src/main/scala/scalafix/v0/Rule.scala b/scalafix-core/src/main/scala/scalafix/v0/Rule.scala index 2be51144d..c63039c02 100644 --- a/scalafix-core/src/main/scala/scalafix/v0/Rule.scala +++ b/scalafix-core/src/main/scala/scalafix/v0/Rule.scala @@ -10,7 +10,8 @@ import scalafix.internal.patch.PatchInternals import scalafix.lint.RuleDiagnostic import scalafix.syntax._ -/** A Scalafix Rule. +/** + * A Scalafix Rule. * * To provide automatic fixes for this rule, override the `fix` method. Example: * {{{ @@ -50,7 +51,8 @@ abstract class Rule(ruleName: RuleName) { self => /** Returns a patch to fix violations of this rule. */ def fix(ctx: RuleCtx): Patch = Patch.empty - /** Initialize this rule with the given user configuration. + /** + * Initialize this rule with the given user configuration. * * This method is called once by scalafix before rule is called. * Use this method to either read custom configuration or to build diff --git a/scalafix-core/src/main/scala/scalafix/v0/RuleCtx.scala b/scalafix-core/src/main/scala/scalafix/v0/RuleCtx.scala index 9c390207e..c3312f1b4 100644 --- a/scalafix-core/src/main/scala/scalafix/v0/RuleCtx.scala +++ b/scalafix-core/src/main/scala/scalafix/v0/RuleCtx.scala @@ -15,13 +15,15 @@ import scalafix.util.TokenList trait RuleCtx extends PatchOps { - /** The parsed syntax tree that should be fixed. + /** + * The parsed syntax tree that should be fixed. * * The scalafix API does not support fixing un-parseable code at this point. */ def tree: Tree - /** The input where the tree was parsed from. + /** + * The input where the tree was parsed from. * * This is typically either Input.VirtualFile for semantic rules * and Input.File for syntactic rules. For Input.VirtualFile, it is @@ -29,22 +31,22 @@ trait RuleCtx extends PatchOps { */ def input: Input - /** The tokenized tokens of this this tree. **/ + /** The tokenized tokens of this this tree. * */ def tokens: Tokens - /** Find matching open/close pairs of parens/braces/brackets. **/ + /** Find matching open/close pairs of parens/braces/brackets. * */ def matchingParens: MatchingParens - /** Traverse tokens as a doubly linked list. **/ + /** Traverse tokens as a doubly linked list. * */ def tokenList: TokenList - /** Find comments/docstrings associated with tree nodes. **/ + /** Find comments/docstrings associated with tree nodes. * */ def comments: AssociatedComments /** Get SemanticdbIndex for this single tree alone. */ def index(implicit index: SemanticdbIndex): SemanticdbIndex - /** Print out the contents of SemanticdbIndex for this input only. **/ + /** Print out the contents of SemanticdbIndex for this input only. * */ def debugIndex()(implicit index: SemanticdbIndex, fileLine: FileLine): Unit // Private scalafix methods, subject for removal without notice. diff --git a/scalafix-core/src/main/scala/scalafix/v0/SemanticdbIndex.scala b/scalafix-core/src/main/scala/scalafix/v0/SemanticdbIndex.scala index b86a0692d..1820d6705 100644 --- a/scalafix-core/src/main/scala/scalafix/v0/SemanticdbIndex.scala +++ b/scalafix-core/src/main/scala/scalafix/v0/SemanticdbIndex.scala @@ -32,7 +32,8 @@ trait SemanticdbIndex extends SemanticContext { /** Get all synthetics in this index. */ def synthetics: Seq[Synthetic] = database.synthetics - /** The resolved names in this database. + /** + * The resolved names in this database. * * Includes resolved name in synthetics, such as inferred implicits/types. */ @@ -41,7 +42,8 @@ trait SemanticdbIndex extends SemanticContext { /** Lookup symbol at this position. */ def symbol(position: Position): Option[Symbol] - /** Lookup symbol at this tree. + /** + * Lookup symbol at this tree. * * This method returns the same result as symbol(Tree.Position) in most cases * but handles some special cases: @@ -53,7 +55,8 @@ trait SemanticdbIndex extends SemanticContext { /** Lookup denotation of this symbol. */ def denotation(symbol: Symbol): Option[Denotation] - /** Lookup denotation of this tree. + /** + * Lookup denotation of this tree. * * Shorthand method for symbol(tree).flatMap(denotation). */ diff --git a/scalafix-core/src/main/scala/scalafix/v0/Signature.scala b/scalafix-core/src/main/scala/scalafix/v0/Signature.scala index 8a28845ee..ef29d328c 100644 --- a/scalafix-core/src/main/scala/scalafix/v0/Signature.scala +++ b/scalafix-core/src/main/scala/scalafix/v0/Signature.scala @@ -51,7 +51,9 @@ object Signature { final case class Self(name: String) extends Signature { override def syntax = - throw new UnsupportedOperationException("No longer supported.") // scalafix:ok + throw new UnsupportedOperationException( + "No longer supported." + ) // scalafix:ok override def structure: String = s"""Signature.Self("$name")""" override def toString: String = syntax } diff --git a/scalafix-core/src/main/scala/scalafix/v0/Symbol.scala b/scalafix-core/src/main/scala/scalafix/v0/Symbol.scala index 47141899a..7d1310bf3 100644 --- a/scalafix-core/src/main/scala/scalafix/v0/Symbol.scala +++ b/scalafix-core/src/main/scala/scalafix/v0/Symbol.scala @@ -28,8 +28,8 @@ object Symbol { case Root(sig) => sig.syntax case Symbol.Global( - Symbol.Global(Symbol.None, Signature.Term("_root_")), - sig + Symbol.Global(Symbol.None, Signature.Term("_root_")), + sig ) => // For legacy reasons, we special case the `_root_.` term symbol. sig.syntax @@ -97,7 +97,9 @@ object Symbol { def parseSymbol(owner: Symbol): Symbol = { def global(signature: Signature): Symbol.Global = { - if (owner == Symbol.None && signature != Signature.Package("_root_")) { + if ( + owner == Symbol.None && signature != Signature.Package("_root_") + ) { val root = Symbol.Global(Symbol.None, Signature.Package("_root_")) Symbol.Global(root, signature) } else { diff --git a/scalafix-core/src/main/scala/scalafix/v1/SemanticContext.scala b/scalafix-core/src/main/scala/scalafix/v1/SemanticContext.scala index 68377e13d..8e393008a 100644 --- a/scalafix-core/src/main/scala/scalafix/v1/SemanticContext.scala +++ b/scalafix-core/src/main/scala/scalafix/v1/SemanticContext.scala @@ -1,6 +1,7 @@ package scalafix.v1 -/** An implicit instance of SemanticContext implies the call-site has access to semantic APIs. +/** + * An implicit instance of SemanticContext implies the call-site has access to semantic APIs. * * Useful to guard users from calling semantic operations without access to semantic APIs. */ diff --git a/scalafix-core/src/main/scala/scalafix/v1/SymbolInformation.scala b/scalafix-core/src/main/scala/scalafix/v1/SymbolInformation.scala index b2da7f0b0..94a973476 100644 --- a/scalafix-core/src/main/scala/scalafix/v1/SymbolInformation.scala +++ b/scalafix-core/src/main/scala/scalafix/v1/SymbolInformation.scala @@ -47,8 +47,6 @@ import scalafix.internal.v1.SymtabFromProtobuf * @groupname language Language * @groupprio language 15 * @groupdesc language Describes which language the symbol is defined in. - * - * */ final class SymbolInformation private[scalafix] ( private[scalafix] val info: s.SymbolInformation diff --git a/scalafix-core/src/main/scala/scalafix/v1/package.scala b/scalafix-core/src/main/scala/scalafix/v1/package.scala index ce8bb8c06..dd54a60b7 100644 --- a/scalafix-core/src/main/scala/scalafix/v1/package.scala +++ b/scalafix-core/src/main/scala/scalafix/v1/package.scala @@ -22,13 +22,13 @@ package object v1 extends Api { } implicit class XtensionTermInfixScalafix(infix: Term.ApplyInfix) { @deprecated("0.9.7", "Use syntheticOperators") - def syntheticOperator( - implicit doc: SemanticDocument + def syntheticOperator(implicit + doc: SemanticDocument ): Option[SemanticTree] = syntheticOperators.headOption - def syntheticOperators( - implicit doc: SemanticDocument + def syntheticOperators(implicit + doc: SemanticDocument ): List[SemanticTree] = { val operatorPosition = Position.Range(infix.pos.input, infix.pos.start, infix.op.pos.end) diff --git a/scalafix-docs/src/main/scala/docs/website.scala b/scalafix-docs/src/main/scala/docs/website.scala index cecc8ed98..841de9167 100644 --- a/scalafix-docs/src/main/scala/docs/website.scala +++ b/scalafix-docs/src/main/scala/docs/website.scala @@ -141,14 +141,13 @@ package object website { def defaults[T](ruleName: String, all: List[(Setting, Any)]): String = { val sb = new StringBuilder sb.append("\n\n### Defaults\n\n```") - all.foreach { - case (setting, default) => - sb.append("\n") - .append(ruleName) - .append(".") - .append(setting.name) - .append(" = ") - .append(default) + all.foreach { case (setting, default) => + sb.append("\n") + .append(ruleName) + .append(".") + .append(setting.name) + .append(" = ") + .append(default) } sb.append("\n```\n\n") sb.toString() @@ -179,8 +178,8 @@ package object website { def rule[T]( ruleName: String, default: T - )( - implicit settings: Settings[T], + )(implicit + settings: Settings[T], ev: T <:< Product ): String = { val sb = new StringBuilder diff --git a/scalafix-docs/src/main/scala/scalafix/docs/PatchDocs.scala b/scalafix-docs/src/main/scala/scalafix/docs/PatchDocs.scala index 93affa7b6..1713d40e6 100644 --- a/scalafix-docs/src/main/scala/scalafix/docs/PatchDocs.scala +++ b/scalafix-docs/src/main/scala/scalafix/docs/PatchDocs.scala @@ -95,8 +95,8 @@ object PatchDocs { println(message) } - def unifiedDiff(obtained: String, context: Int)( - implicit doc: SemanticDocument + def unifiedDiff(obtained: String, context: Int)(implicit + doc: SemanticDocument ): String = { val in = Input.VirtualFile("before patch", doc.input.text) val out = Input.VirtualFile("after patch", obtained) diff --git a/scalafix-reflect/src/main/scala/scalafix/internal/reflect/ClasspathOps.scala b/scalafix-reflect/src/main/scala/scalafix/internal/reflect/ClasspathOps.scala index c8f0f50c3..ab2d42644 100644 --- a/scalafix-reflect/src/main/scala/scalafix/internal/reflect/ClasspathOps.scala +++ b/scalafix-reflect/src/main/scala/scalafix/internal/reflect/ClasspathOps.scala @@ -112,10 +112,12 @@ object ClasspathOps { if (classLoader.isInstanceOf[URLClassLoader]) { classLoader.asInstanceOf[URLClassLoader].getURLs() // java9+ - } else if (classLoader + } else if ( + classLoader .getClass() .getName() - .startsWith("jdk.internal.loader.ClassLoaders$")) { + .startsWith("jdk.internal.loader.ClassLoaders$") + ) { try { val field = classOf[Unsafe].getDeclaredField("theUnsafe") field.setAccessible(true) diff --git a/scalafix-reflect/src/main/scala/scalafix/internal/reflect/GitHubUrlRule.scala b/scalafix-reflect/src/main/scala/scalafix/internal/reflect/GitHubUrlRule.scala index 4daa6343b..592457595 100644 --- a/scalafix-reflect/src/main/scala/scalafix/internal/reflect/GitHubUrlRule.scala +++ b/scalafix-reflect/src/main/scala/scalafix/internal/reflect/GitHubUrlRule.scala @@ -21,9 +21,9 @@ object GitHubUrlRule { Some( ConfError .message(s"""Invalid url 'github:$invalid'. Valid formats are: - |- github:org/repo - |- github:org/repo/name - |- github:org/repo/name?sha=branch""".stripMargin) + |- github:org/repo + |- github:org/repo/name + |- github:org/repo/name?sha=branch""".stripMargin) .notOk ) case _ => None diff --git a/scalafix-reflect/src/main/scala/scalafix/internal/reflect/ScalafixToolbox.scala b/scalafix-reflect/src/main/scala/scalafix/internal/reflect/ScalafixToolbox.scala index c102bec97..923322c69 100644 --- a/scalafix-reflect/src/main/scala/scalafix/internal/reflect/ScalafixToolbox.scala +++ b/scalafix-reflect/src/main/scala/scalafix/internal/reflect/ScalafixToolbox.scala @@ -31,15 +31,17 @@ class ScalafixToolbox { code: Input, toolClasspath: URLClassLoader ): Configured[CompiledRules] = - ruleCache.getOrDefault(code, { - val uncached = getRuleUncached(code, toolClasspath) - uncached match { - case toCache @ Configured.Ok(_) => - ruleCache.put(code, toCache) - case _ => + ruleCache.getOrDefault( + code, { + val uncached = getRuleUncached(code, toolClasspath) + uncached match { + case toCache @ Configured.Ok(_) => + ruleCache.put(code, toCache) + case _ => + } + uncached } - uncached - }) + ) def getRuleUncached( code: Input, diff --git a/scalafix-reflect/src/main/scala/scalafix/internal/v0/LegacyInMemorySemanticdbIndex.scala b/scalafix-reflect/src/main/scala/scalafix/internal/v0/LegacyInMemorySemanticdbIndex.scala index 7b6b1273b..abd36892d 100644 --- a/scalafix-reflect/src/main/scala/scalafix/internal/v0/LegacyInMemorySemanticdbIndex.scala +++ b/scalafix-reflect/src/main/scala/scalafix/internal/v0/LegacyInMemorySemanticdbIndex.scala @@ -28,9 +28,8 @@ case class LegacyInMemorySemanticdbIndex( def info(symbol: String): Option[s.SymbolInformation] = symtab.info(symbol) override def inputs: Seq[m.Input] = { - index.values.collect { - case s: LegacySemanticdbIndex => - s.doc.input + index.values.collect { case s: LegacySemanticdbIndex => + s.doc.input }.toSeq } diff --git a/scalafix-reflect/src/main/scala/scalafix/v1/RuleDecoder.scala b/scalafix-reflect/src/main/scala/scalafix/v1/RuleDecoder.scala index a4e63fe3e..a580c0f50 100644 --- a/scalafix-reflect/src/main/scala/scalafix/v1/RuleDecoder.scala +++ b/scalafix-reflect/src/main/scala/scalafix/v1/RuleDecoder.scala @@ -23,7 +23,8 @@ import scalafix.v1 /** One-stop shop for loading scalafix rules from strings. */ object RuleDecoder { - /** Load a single rule from a string like "RemoveUnusedImports" or "file:path/to/Rule.scala" + /** + * Load a single rule from a string like "RemoveUnusedImports" or "file:path/to/Rule.scala" * * Supports loading rules in both scalafix.v0 and scalafix.v1. * diff --git a/scalafix-rules/src/main/scala/scala/meta/internal/pc/Identifier.scala b/scalafix-rules/src/main/scala/scala/meta/internal/pc/Identifier.scala index ec71c1de1..f8735fd22 100644 --- a/scalafix-rules/src/main/scala/scala/meta/internal/pc/Identifier.scala +++ b/scalafix-rules/src/main/scala/scala/meta/internal/pc/Identifier.scala @@ -77,14 +77,13 @@ object Identifier { c.getType == Character.OTHER_SYMBOL || "!#%&*+-/:<=>?@\\^|~".contains(c) } - val validChunks = chunks.zipWithIndex.forall { - case (chunk, index) => - chunk.forall(c => c.isLetter || c.isDigit || c == '$') || - (chunk.forall(validOperator) && - // operators can only come last - index == chunks.length - 1 && - // but cannot be preceded by only a _ - !(chunks.lift(index - 1).contains("") && index - 1 == 0)) + val validChunks = chunks.zipWithIndex.forall { case (chunk, index) => + chunk.forall(c => c.isLetter || c.isDigit || c == '$') || + (chunk.forall(validOperator) && + // operators can only come last + index == chunks.length - 1 && + // but cannot be preceded by only a _ + !(chunks.lift(index - 1).contains("") && index - 1 == 0)) } val firstLetterValid = diff --git a/scalafix-rules/src/main/scala/scala/meta/internal/pc/ScalafixGlobal.scala b/scalafix-rules/src/main/scala/scala/meta/internal/pc/ScalafixGlobal.scala index 41f07e8b7..b096e1cfd 100644 --- a/scalafix-rules/src/main/scala/scala/meta/internal/pc/ScalafixGlobal.scala +++ b/scalafix-rules/src/main/scala/scala/meta/internal/pc/ScalafixGlobal.scala @@ -153,15 +153,13 @@ class ScalafixGlobal( Map[String, String]( "scala/collection/mutable/" -> "mutable.", "java/util/" -> "ju." - ).map { - case (sym, name) => - val nme = - if (name.endsWith("#")) TypeName(name.stripSuffix("#")) - else if (name.endsWith(".")) TermName(name.stripSuffix(".")) - else TermName(name) - inverseSemanticdbSymbol(sym) -> nme - } - .view + ).map { case (sym, name) => + val nme = + if (name.endsWith("#")) TypeName(name.stripSuffix("#")) + else if (name.endsWith(".")) TermName(name.stripSuffix(".")) + else TermName(name) + inverseSemanticdbSymbol(sym) -> nme + }.view .filterKeys(_ != NoSymbol) .toMap @@ -203,9 +201,11 @@ class ScalafixGlobal( args.map(arg => loop(arg, None)) ) case _ => - if (sym.isAliasType && + if ( + sym.isAliasType && (sym.isAbstract || - sym.overrides.lastOption.exists(_.isAbstract))) { + sym.overrides.lastOption.exists(_.isAbstract)) + ) { // Always dealias abstract type aliases but leave concrete aliases alone. // trait Generic { type Repr /* dealias */ } @@ -350,7 +350,9 @@ class ScalafixGlobal( // Returns the package `a` for the symbol `_root_/a/b.c` def topPackage(s: Symbol): Symbol = { val owner = s.owner - if (s.isRoot || s.isRootPackage || s == NoSymbol || s.owner.isEffectiveRoot || s == owner) { + if ( + s.isRoot || s.isRootPackage || s == NoSymbol || s.owner.isEffectiveRoot || s == owner + ) { s } else { topPackage(owner) @@ -433,7 +435,9 @@ class ScalafixGlobal( def fullNameSyntax: String = { val out = new java.lang.StringBuilder def loop(s: Symbol): Unit = { - if (s.isRoot || s.isRootPackage || s == NoSymbol || s.owner.isEffectiveRoot) { + if ( + s.isRoot || s.isRootPackage || s == NoSymbol || s.owner.isEffectiveRoot + ) { out.append(Identifier(s.nameSyntax)) } else { loop(s.effectiveOwner.enclClass) @@ -448,8 +452,10 @@ class ScalafixGlobal( } def asInfixPattern: Option[String] = - if (sym.isCase && - !Character.isUnicodeIdentifierStart(sym.decodedName.head)) { + if ( + sym.isCase && + !Character.isUnicodeIdentifierStart(sym.decodedName.head) + ) { sym.primaryConstructor.paramss match { case (a :: b :: Nil) :: _ => Some(s"${a.decodedName} ${sym.decodedName} ${b.decodedName}") diff --git a/scalafix-rules/src/main/scala/scala/tools/nsc/interactive/ScalafixGlobalThread.scala b/scalafix-rules/src/main/scala/scala/tools/nsc/interactive/ScalafixGlobalThread.scala index 392326961..da75b208e 100644 --- a/scalafix-rules/src/main/scala/scala/tools/nsc/interactive/ScalafixGlobalThread.scala +++ b/scalafix-rules/src/main/scala/scala/tools/nsc/interactive/ScalafixGlobalThread.scala @@ -10,15 +10,18 @@ package scala.tools.nsc.interactive final class ScalafixGlobalThread(var compiler: Global, name: String = "") extends Thread("Scalafix Presentation Compiler [" + name + "]") { - /** The presentation compiler loop. + /** + * The presentation compiler loop. */ override def run(): Unit = { compiler.debugLog("starting new runner thread") while (compiler ne null) try { compiler.checkNoResponsesOutstanding() - compiler.log.logreplay("wait for more work", { - compiler.scheduler.waitForMoreWork(); true - }) + compiler.log.logreplay( + "wait for more work", { + compiler.scheduler.waitForMoreWork(); true + } + ) compiler.pollForWork(compiler.NoPosition) while (compiler.isOutOfDate) { try { diff --git a/scalafix-rules/src/main/scala/scalafix/internal/rule/CompilerTypePrinter.scala b/scalafix-rules/src/main/scala/scalafix/internal/rule/CompilerTypePrinter.scala index 7bb21e368..ed2b5310f 100644 --- a/scalafix-rules/src/main/scala/scalafix/internal/rule/CompilerTypePrinter.scala +++ b/scalafix-rules/src/main/scala/scalafix/internal/rule/CompilerTypePrinter.scala @@ -79,10 +79,9 @@ class CompilerTypePrinter(g: ScalafixGlobal, config: ExplicitResultTypesConfig)( gsym: Symbol, inverseSemanticdbSymbol: Symbol ): Option[v1.Patch] = { - val renames = g.renamedSymbols(context).filterNot { - case (sym, name) => - sym == g.NoSymbol || - name.toString() == "_" + val renames = g.renamedSymbols(context).filterNot { case (sym, name) => + sym == g.NoSymbol || + name.toString() == "_" } val history = new g.ShortenedNames( lookupSymbol = name => { @@ -92,11 +91,10 @@ class CompilerTypePrinter(g: ScalafixGlobal, config: ExplicitResultTypesConfig)( owners = parentSymbols(context), config = g.renameConfig ++ renames ) - val fromRewritten = willBeImported.filter { - case (name, short) => - (!context.isNameInScope(name) && - !context.isNameInScope(name.otherName)) || - history.nameResolvesToSymbol(name, short.symbol) + val fromRewritten = willBeImported.filter { case (name, short) => + (!context.isNameInScope(name) && + !context.isNameInScope(name.otherName)) || + history.nameResolvesToSymbol(name, short.symbol) } history.missingImports ++= fromRewritten val seenFromType = asSeenFromType(gsym, inverseSemanticdbSymbol) @@ -193,10 +191,9 @@ class CompilerTypePrinter(g: ScalafixGlobal, config: ExplicitResultTypesConfig)( } else { val head :: tail = pkg.ownerChain.reverse.tail // Skip root symbol .map(sym => m.Term.Name(sym.name.toString())) - val ref = tail.foldLeft(head: m.Term.Ref) { - case (owner, name) => - if (name.value == "package") owner - else m.Term.Select(owner, name) + val ref = tail.foldLeft(head: m.Term.Ref) { case (owner, name) => + if (name.value == "package") owner + else m.Term.Select(owner, name) } v1.Patch.addGlobalImport(m.Importer(ref, List(importee))) } @@ -323,11 +320,13 @@ class CompilerTypePrinter(g: ScalafixGlobal, config: ExplicitResultTypesConfig)( CompilerCompat.serializableClass(g).toSet[Symbol] val parentSymbols = parents.map(_.typeSymbol).toSet val strippedParents = - if (parentSymbols + if ( + parentSymbols .intersect(productRootClass) .nonEmpty && parentSymbols .intersect(serializableClass) - .nonEmpty) { + .nonEmpty + ) { parents.filterNot(isPossibleSyntheticParent) } else parents val newParents = diff --git a/scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntax.scala b/scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntax.scala index 698ca62b4..4265c9a4c 100644 --- a/scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntax.scala +++ b/scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntax.scala @@ -34,11 +34,10 @@ final class DisableSyntax(config: DisableSyntaxConfig) ) def messageSubstitution(matcher: Matcher, message: String): String = - (0 to matcher.groupCount).foldLeft(message) { - case (msg, idx) => - val groupText = matcher.group(idx) - if (groupText != null) msg.replace(s"{$$$idx}", matcher.group(idx)) - else msg + (0 to matcher.groupCount).foldLeft(message) { case (msg, idx) => + val groupText = matcher.group(idx) + if (groupText != null) msg.replace(s"{$$$idx}", matcher.group(idx)) + else msg } val regexDiagnostics = Seq.newBuilder[Diagnostic] @@ -269,8 +268,9 @@ final class DisableSyntax(config: DisableSyntaxConfig) private val noValPatternCategory: LintCategory = LintCategory.error( id = "noValPatterns", - explain = "Pattern matching in val assignment can result in match error, " + - "use \"_ match { ... }\" with a fallback case instead." + explain = + "Pattern matching in val assignment can result in match error, " + + "use \"_ match { ... }\" with a fallback case instead." ) private def noUniversalEqualityDiagnostic( @@ -285,7 +285,7 @@ object DisableSyntax { private val explanation = """|there is no guarantee that finalize will be called and - |overriding finalize incurs a performance penalty""".stripMargin + |overriding finalize incurs a performance penalty""".stripMargin def FinalizeMatcher(id: String): PartialFunction[Tree, List[Diagnostic]] = { case Defn.Def(_, name @ q"finalize", _, Nil | Nil :: Nil, _, _) => diff --git a/scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntaxConfig.scala b/scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntaxConfig.scala index 73cc46470..730f3b7f2 100644 --- a/scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntaxConfig.scala +++ b/scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntaxConfig.scala @@ -87,12 +87,12 @@ case class DisableSyntaxConfig( ) @ExampleValue( """|[ - | { - | id = "offensive" - | pattern = "[Pp]imp" - | message = "Please consider a less offensive word such as 'extension' or 'enrichment'" - | } - |]""".stripMargin + | { + | id = "offensive" + | pattern = "[Pp]imp" + | message = "Please consider a less offensive word such as 'extension' or 'enrichment'" + | } + |]""".stripMargin ) regex: List[CustomMessage[Either[Regex, Pattern]]] = Nil ) { diff --git a/scalafix-rules/src/main/scala/scalafix/internal/rule/ExplicitResultTypes.scala b/scalafix-rules/src/main/scala/scalafix/internal/rule/ExplicitResultTypes.scala index 3cb53004e..e99d88d46 100644 --- a/scalafix-rules/src/main/scala/scalafix/internal/rule/ExplicitResultTypes.scala +++ b/scalafix-rules/src/main/scala/scalafix/internal/rule/ExplicitResultTypes.scala @@ -63,9 +63,11 @@ final class ExplicitResultTypes( ) } } - if (config.scalacClasspath.nonEmpty && !supportedScalaVersions.contains( + if ( + config.scalacClasspath.nonEmpty && !supportedScalaVersions.contains( config.scalaVersion - )) { + ) + ) { val inputBinaryScalaVersion = toBinaryVersion(config.scalaVersion) val runtimeBinaryScalaVersion = @@ -202,8 +204,8 @@ final class ExplicitResultTypes( patch <- types.toPatch(name.pos, defnSymbol, replace, defn, space) } yield patch - def fixDefinition(defn: Defn, body: Term, types: TypePrinter)( - implicit ctx: SemanticDocument + def fixDefinition(defn: Defn, body: Term, types: TypePrinter)(implicit + ctx: SemanticDocument ): Patch = { val lst = ctx.tokenList val option = SymbolMatcher.exact("scala/Option.") diff --git a/scalafix-rules/src/main/scala/scalafix/internal/rule/ExplicitResultTypesConfig.scala b/scalafix-rules/src/main/scala/scalafix/internal/rule/ExplicitResultTypesConfig.scala index 0a0318368..f8d30850e 100644 --- a/scalafix-rules/src/main/scala/scalafix/internal/rule/ExplicitResultTypesConfig.scala +++ b/scalafix-rules/src/main/scala/scalafix/internal/rule/ExplicitResultTypesConfig.scala @@ -77,8 +77,8 @@ object SimpleDefinitions { case Bool(false) => Configured.ok(SimpleDefinitions(Set.empty)) case Bool(true) => Configured.ok(SimpleDefinitions(Set.empty)) case conf @ Lst(values) => - val strings = values.collect { - case Str(kind) => kind + val strings = values.collect { case Str(kind) => + kind } if (strings.length == values.length) { Configured.ok(SimpleDefinitions(strings.toSet)) diff --git a/scalafix-rules/src/main/scala/scalafix/internal/rule/LeakingImplicitClassVal.scala b/scalafix-rules/src/main/scala/scalafix/internal/rule/LeakingImplicitClassVal.scala index a74727716..8c289a2b6 100644 --- a/scalafix-rules/src/main/scala/scalafix/internal/rule/LeakingImplicitClassVal.scala +++ b/scalafix-rules/src/main/scala/scalafix/internal/rule/LeakingImplicitClassVal.scala @@ -13,11 +13,11 @@ class LeakingImplicitClassVal extends SyntacticRule("LeakingImplicitClassVal") { override def fix(implicit doc: SyntacticDocument): Patch = { doc.tree.collect { case Defn.Class( - cMods, - _, - _, - Ctor.Primary(_, _, (Term.Param(pMods, _, _, _) :: Nil) :: Nil), - Template(_, init"AnyVal" :: Nil, _, _) + cMods, + _, + _, + Ctor.Primary(_, _, (Term.Param(pMods, _, _, _) :: Nil) :: Nil), + Template(_, init"AnyVal" :: Nil, _, _) ) if cMods.exists(_.is[Mod.Implicit]) => val optPatch = for { anchorMod <- pMods.find(!_.is[Mod.Annot]) diff --git a/scalafix-rules/src/main/scala/scalafix/internal/rule/NoValInForComprehension.scala b/scalafix-rules/src/main/scala/scalafix/internal/rule/NoValInForComprehension.scala index 4108d9d4c..35dc77f91 100644 --- a/scalafix-rules/src/main/scala/scalafix/internal/rule/NoValInForComprehension.scala +++ b/scalafix-rules/src/main/scala/scalafix/internal/rule/NoValInForComprehension.scala @@ -12,11 +12,10 @@ class NoValInForComprehension extends SyntacticRule("NoValInForComprehension") { override def isRewrite: Boolean = true override def fix(implicit doc: SyntacticDocument): Patch = { - doc.tree.collect { - case v: Enumerator.Val => - val valTokens = - v.tokens.takeWhile(t => t.syntax == "val" || t.is[Whitespace]) - valTokens.map(Patch.removeToken).asPatch.atomic + doc.tree.collect { case v: Enumerator.Val => + val valTokens = + v.tokens.takeWhile(t => t.syntax == "val" || t.is[Whitespace]) + valTokens.map(Patch.removeToken).asPatch.atomic }.asPatch } diff --git a/scalafix-rules/src/main/scala/scalafix/internal/rule/RemoveUnused.scala b/scalafix-rules/src/main/scala/scalafix/internal/rule/RemoveUnused.scala index a9702b72a..4806edc42 100644 --- a/scalafix-rules/src/main/scala/scalafix/internal/rule/RemoveUnused.scala +++ b/scalafix-rules/src/main/scala/scalafix/internal/rule/RemoveUnused.scala @@ -38,8 +38,8 @@ class RemoveUnused(config: RemoveUnusedConfig) if (!hasWarnUnused) { Configured.error( s"""|The Scala compiler option "-Ywarn-unused" is required to use RemoveUnused. - |To fix this problem, update your build to use at least one Scala compiler - |option like -Ywarn-unused, -Xlint:unused (2.12.2 or above), or -Wunused (2.13 only)""".stripMargin + |To fix this problem, update your build to use at least one Scala compiler + |option like -Ywarn-unused, -Xlint:unused (2.12.2 or above), or -Wunused (2.13 only)""".stripMargin ) } else { config.conf @@ -55,13 +55,17 @@ class RemoveUnused(config: RemoveUnusedConfig) doc.diagnostics.foreach { diagnostic => if (config.imports && diagnostic.message == "Unused import") { isUnusedImport += diagnostic.position - } else if (config.privates && + } else if ( + config.privates && diagnostic.message.startsWith("private") && - diagnostic.message.endsWith("is never used")) { + diagnostic.message.endsWith("is never used") + ) { isUnusedTerm += diagnostic.position - } else if (config.locals && + } else if ( + config.locals && diagnostic.message.startsWith("local") && - diagnostic.message.endsWith("is never used")) { + diagnostic.message.endsWith("is never used") + ) { isUnusedTerm += diagnostic.position } } diff --git a/scalafix-testkit/src/main/scala/scalafix/internal/testkit/AssertDelta.scala b/scalafix-testkit/src/main/scala/scalafix/internal/testkit/AssertDelta.scala index e4d9dc483..b279a23ff 100644 --- a/scalafix-testkit/src/main/scala/scalafix/internal/testkit/AssertDelta.scala +++ b/scalafix-testkit/src/main/scala/scalafix/internal/testkit/AssertDelta.scala @@ -45,7 +45,8 @@ case class AssertDelta( val line = pos.lineContent val assertCarret = (" " * carPos.startColumn) + "^-- asserted" - val lintCarret = (" " * lintDiagnostic.position.startColumn) + "^-- reported" + val lintCarret = + (" " * lintDiagnostic.position.startColumn) + "^-- reported" List( line, @@ -62,7 +63,7 @@ case class AssertDelta( if (!sameKey(assert.key)) { List( s"""|-${assert.key} - |+${lintDiagnostic.id.fullID}""".stripMargin + |+${lintDiagnostic.id.fullID}""".stripMargin ) } else { Nil diff --git a/scalafix-testkit/src/main/scala/scalafix/internal/testkit/AssertDiff.scala b/scalafix-testkit/src/main/scala/scalafix/internal/testkit/AssertDiff.scala index 2ca47cd09..21b84e59d 100644 --- a/scalafix-testkit/src/main/scala/scalafix/internal/testkit/AssertDiff.scala +++ b/scalafix-testkit/src/main/scala/scalafix/internal/testkit/AssertDiff.scala @@ -123,8 +123,8 @@ case class AssertDiff( if (mismatch.isEmpty) "" else { """|===========> Mismatch <=========== - | - |""".stripMargin + | + |""".stripMargin } val showMismatchs = @@ -148,8 +148,8 @@ case class AssertDiff( if (unexpected.isEmpty) "" else { """|===========> Unexpected <=========== - | - |""".stripMargin + | + |""".stripMargin } val showUnexpected = @@ -166,8 +166,8 @@ case class AssertDiff( if (unreported.isEmpty) "" else { """|===========> Unreported <=========== - | - |""".stripMargin + | + |""".stripMargin } val showUnreported = diff --git a/scalafix-testkit/src/main/scala/scalafix/testkit/AbstractSemanticRuleSuite.scala b/scalafix-testkit/src/main/scala/scalafix/testkit/AbstractSemanticRuleSuite.scala index b619ebe4c..9e30b8ea8 100644 --- a/scalafix-testkit/src/main/scala/scalafix/testkit/AbstractSemanticRuleSuite.scala +++ b/scalafix-testkit/src/main/scala/scalafix/testkit/AbstractSemanticRuleSuite.scala @@ -15,7 +15,8 @@ import scalafix.internal.reflect.ClasspathOps import scalafix.internal.testkit.AssertDiff import scalafix.internal.testkit.CommentAssertion -/** Construct a test suite for running semantic Scalafix rules. +/** + * Construct a test suite for running semantic Scalafix rules. *

* Mix-in FunSuiteLike (ScalaTest 3.0), AnyFunSuiteLike (ScalaTest 3.1+) or * the testing style of your choice if you add your own tests. diff --git a/scalafix-testkit/src/main/scala/scalafix/testkit/AbstractSyntacticRuleSuite.scala b/scalafix-testkit/src/main/scala/scalafix/testkit/AbstractSyntacticRuleSuite.scala index 9f7042f44..fe88cc294 100644 --- a/scalafix-testkit/src/main/scala/scalafix/testkit/AbstractSyntacticRuleSuite.scala +++ b/scalafix-testkit/src/main/scala/scalafix/testkit/AbstractSyntacticRuleSuite.scala @@ -9,7 +9,8 @@ import scalafix.internal.config.ScalafixConfig import scalafix.syntax._ import scalafix.v0._ -/** Utility to unit test syntactic rules. +/** + * Utility to unit test syntactic rules. *

* Mix-in FunSuiteLike (ScalaTest 3.0), AnyFunSuiteLike (ScalaTest 3.1+) or * the testing style of your choice if you add your own tests. diff --git a/scalafix-testkit/src/main/scala/scalafix/testkit/DiffAssertions.scala b/scalafix-testkit/src/main/scala/scalafix/testkit/DiffAssertions.scala index f7901a0f4..af2cadf97 100644 --- a/scalafix-testkit/src/main/scala/scalafix/testkit/DiffAssertions.scala +++ b/scalafix-testkit/src/main/scala/scalafix/testkit/DiffAssertions.scala @@ -63,13 +63,13 @@ trait DiffAssertions extends Suite { val sb = new StringBuilder if (obtained.length < 1000) { sb.append(s""" - #${header("Obtained")} - #${trailingSpace(obtained)} + #${header("Obtained")} + #${trailingSpace(obtained)} """.stripMargin('#')) } sb.append(s""" - #${header("Diff")} - #${trailingSpace(compareContents(obtained, expected))} + #${header("Diff")} + #${trailingSpace(compareContents(obtained, expected))} """.stripMargin('#')) sb.toString() } diff --git a/scalafix-tests/unit/src/main/scala/scalafix/test/FqnRule.scala b/scalafix-tests/unit/src/main/scala/scalafix/test/FqnRule.scala index f3c762601..ee981133b 100644 --- a/scalafix-tests/unit/src/main/scala/scalafix/test/FqnRule.scala +++ b/scalafix-tests/unit/src/main/scala/scalafix/test/FqnRule.scala @@ -13,17 +13,16 @@ case class FqnRule(index: v0.SemanticdbIndex) override def fix(ctx: v0.RuleCtx): Patch = ctx.addGlobalImport(importer"scala.collection.immutable") + { val fqnRule = SymbolMatcher.exact(v0.Symbol("test/FqnRule.")) - ctx.tree.collect { - case fqnRule(t: Term.Name) => - ctx.addLeft(t, "/* matched */ ") + ctx.tree.collect { case fqnRule(t: Term.Name) => + ctx.addLeft(t, "/* matched */ ") }.asPatch } } case object FqnRule2 extends v0.Rule("FqnRule2") { override def fix(ctx: v0.RuleCtx): Patch = - ctx.tree.collectFirst { - case n: Name => ctx.replaceTree(n, n.value + "2") + ctx.tree.collectFirst { case n: Name => + ctx.replaceTree(n, n.value + "2") }.asPatch } diff --git a/scalafix-tests/unit/src/main/scala/scalafix/test/StringFS.scala b/scalafix-tests/unit/src/main/scala/scalafix/test/StringFS.scala index bac22137e..ce54d011e 100644 --- a/scalafix-tests/unit/src/main/scala/scalafix/test/StringFS.scala +++ b/scalafix-tests/unit/src/main/scala/scalafix/test/StringFS.scala @@ -36,7 +36,8 @@ object StringFS { AbsolutePath(root) } - /** Gives a string representation of a directory. For example + /** + * Gives a string representation of a directory. For example * * /build.sbt * val x = project @@ -60,7 +61,7 @@ object StringFS { .map { path => val contents = new String(Files.readAllBytes(path), charset) s"""|/${file.toNIO.relativize(path)} - |$contents""".stripMargin + |$contents""".stripMargin } .mkString("\n") .replace(File.separator, "/") // ensure original separators diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/BaseCliSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/BaseCliSuite.scala index 42e0595dc..2ee10c5f5 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/BaseCliSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/BaseCliSuite.scala @@ -31,16 +31,16 @@ trait BaseCliSuite extends AnyFunSuite with DiffAssertions { val original: String = """|object Main { - | def foo() { - | } - |} - |""".stripMargin + | def foo() { + | } + |} + |""".stripMargin val expected: String = """|object Main { - | def foo(): Unit = { - | } - |} - |""".stripMargin + | def foo(): Unit = { + | } + |} + |""".stripMargin val cwd: Path = Files.createTempDirectory("scalafix-cli") val ps = new PrintStream(new ByteArrayOutputStream()) diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliGitDiffSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliGitDiffSuite.scala index 2bf20ad99..a9ca23e45 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliGitDiffSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliGitDiffSuite.scala @@ -22,9 +22,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.add( oldCode, """|object OldCode { - | // This is old code, where var's blossom - | var oldVar = 1 - |}""".stripMargin + | // This is old code, where var's blossom + | var oldVar = 1 + |}""".stripMargin ) git.add(oldCode) addConf(fs, git) @@ -35,9 +35,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.add( newCode, """|object NewCode { - | // New code, no vars - | var newVar = 1 - |}""".stripMargin + | // New code, no vars + | var newVar = 1 + |}""".stripMargin ) git.add(newCode) git.commit() @@ -46,9 +46,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { val expected = s"""|$newCodeAbsPath:3:3: error: [DisableSyntax.var] mutable state should be avoided - | var newVar = 1 - | ^^^ - |""".stripMargin + | var newVar = 1 + | ^^^ + |""".stripMargin assertNoDiff(obtained, expected) } @@ -60,9 +60,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.add( oldCode, """|object OldCode { - | // This is old code, where var's blossom - | var oldVar = 1 - |}""".stripMargin + | // This is old code, where var's blossom + | var oldVar = 1 + |}""".stripMargin ) git.add(oldCode) addConf(fs, git) @@ -72,13 +72,13 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.replace( oldCode, """|object OldCode { - | // This is old code, where var's blossom - | var oldVar = 1 - |} - |object NewCode { - | // It's not ok to add new vars - | var newVar = 2 - |}""".stripMargin + | // This is old code, where var's blossom + | var oldVar = 1 + |} + |object NewCode { + | // It's not ok to add new vars + | var newVar = 2 + |}""".stripMargin ) git.add(oldCode) git.commit() @@ -87,9 +87,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { val expected = s"""|$oldCodeAbsPath:7:3: error: [DisableSyntax.var] mutable state should be avoided - | var newVar = 2 - | ^^^ - |""".stripMargin + | var newVar = 2 + | ^^^ + |""".stripMargin assertNoDiff(obtained, expected) } @@ -102,9 +102,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.add( oldCode, """|object OldCode { - | // This is old code, where var's blossom - | var oldVar = 1 - |}""".stripMargin + | // This is old code, where var's blossom + | var oldVar = 1 + |}""".stripMargin ) git.add(oldCode) addConf(fs, git) @@ -114,11 +114,11 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.replace( oldCode, """|object OldCode { - | // This is old code, where var's blossom - | var oldVar = 1 - | // It's not ok to add new vars - | var newVar = 2 - |}""".stripMargin + | // This is old code, where var's blossom + | var oldVar = 1 + | // It's not ok to add new vars + | var newVar = 2 + |}""".stripMargin ) fs.mv(oldCode, newCode) git.add(oldCode) @@ -129,9 +129,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { val expected = s"""|$newCodeAbsPath:5:3: error: [DisableSyntax.var] mutable state should be avoided - | var newVar = 2 - | ^^^ - |""".stripMargin + | var newVar = 2 + | ^^^ + |""".stripMargin assertNoDiff(obtained, expected) } @@ -154,9 +154,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.add( oldCode, """|object OldCode { - | // This is old code, where var's blossom - | var oldVar = 1 - |}""".stripMargin + | // This is old code, where var's blossom + | var oldVar = 1 + |}""".stripMargin ) git.add(oldCode) addConf(fs, git) @@ -171,11 +171,11 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.replace( oldCode, """|object OldCode { - | // This is old code, where var's blossom - | var oldVar = 1 - | // It's not ok to add new vars - | var newVar = 2 - |}""".stripMargin + | // This is old code, where var's blossom + | var oldVar = 1 + | // It's not ok to add new vars + | var newVar = 2 + |}""".stripMargin ) fs.mv(oldCode, newCode) git.add(oldCode) @@ -187,9 +187,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { val expected = s"""|$newCodeAbsPath:5:3: error: [DisableSyntax.var] mutable state should be avoided - | var newVar = 2 - | ^^^ - |""".stripMargin + | var newVar = 2 + | ^^^ + |""".stripMargin assertNoDiff(obtained, expected) } @@ -200,9 +200,9 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.add( oldCode, """|object OldCode { - | // This is old code, where var's blossom - | var oldVar = 1 - |}""".stripMargin + | // This is old code, where var's blossom + | var oldVar = 1 + |}""".stripMargin ) git.add(oldCode) addConf(fs, git) @@ -227,21 +227,21 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { val code = "code.scala" val foo1 = """|object A { - | def foo() {} - |} - |""".stripMargin + | def foo() {} + |} + |""".stripMargin val bar1 = """|object B { - | def bar() {} - |} - |""".stripMargin + | def bar() {} + |} + |""".stripMargin val bar2 = """|object B { - | def bar(): Unit = {} - |} - |""".stripMargin + | def bar(): Unit = {} + |} + |""".stripMargin fs.add(code, foo1) git.add(code) @@ -253,8 +253,8 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { fs.replace( code, s"""|$foo1 - | - |$bar1""".stripMargin + | + |$bar1""".stripMargin ) git.add(code) git.commit() @@ -263,8 +263,8 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { val obtained = fs.read(code) val expected = s"""|$foo1 - | - |$bar2""".stripMargin // only bar is modified + | + |$bar2""".stripMargin // only bar is modified assertNoDiff(obtained, expected) } @@ -284,8 +284,11 @@ class CliGitDiffSuite extends AnyFunSuite with DiffAssertions { } private def addConf(fs: Fs): Unit = { - fs.add(confFile, """|rules = DisableSyntax - |DisableSyntax.noVars = true""".stripMargin) + fs.add( + confFile, + """|rules = DisableSyntax + |DisableSyntax.noVars = true""".stripMargin + ) } private def noColor(in: String): String = diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliSuppressSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliSuppressSuite.scala index bfa5d722b..c41446843 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliSuppressSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliSuppressSuite.scala @@ -11,8 +11,8 @@ import scalafix.v1.SyntacticRule class NoVars extends SyntacticRule("NoVars") { override def fix(implicit doc: SyntacticDocument): Patch = { val error = LintCategory.error("No vars!") - doc.tree.collect { - case v @ Defn.Var(_, _, _, _) => Patch.lint(error.at("no vars", v.pos)) + doc.tree.collect { case v @ Defn.Var(_, _, _, _) => + Patch.lint(error.at("no vars", v.pos)) }.asPatch } } @@ -20,8 +20,8 @@ class NoVars extends SyntacticRule("NoVars") { class NoInts extends SyntacticRule("NoInts") { override def fix(implicit doc: SyntacticDocument): Patch = { val error = LintCategory.error("No ints!") - doc.tree.collect { - case i @ Lit.Int(_) => Patch.lint(error.at("no ints", i.pos)) + doc.tree.collect { case i @ Lit.Int(_) => + Patch.lint(error.at("no ints", i.pos)) }.asPatch } } @@ -30,30 +30,30 @@ class CliSuppressSuite extends BaseCliSuite { checkSuppress( name = "suppress vars", originalFile = """ - |object A { - | var a = 1 - |} + |object A { + | var a = 1 + |} """.stripMargin, rule = "scala:scalafix.tests.cli.NoVars", expectedFile = """ - |object A { - | var/* scalafix:ok */ a = 1 - |} + |object A { + | var/* scalafix:ok */ a = 1 + |} """.stripMargin ) checkSuppress( name = "suppress int", originalFile = """ - |object A { - | var a = 1 - |} + |object A { + | var a = 1 + |} """.stripMargin, rule = "scala:scalafix.tests.cli.NoInts", expectedFile = """ - |object A { - | var a = 1/* scalafix:ok */ - |} + |object A { + | var a = 1/* scalafix:ok */ + |} """.stripMargin ) } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliSyntacticSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliSyntacticSuite.scala index c17cc37f0..c1db0dc25 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliSyntacticSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/CliSyntacticSuite.scala @@ -51,38 +51,38 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "fix file", originalLayout = s"""/hello.scala - |$original - |""".stripMargin, + |$original + |""".stripMargin, args = Array("-r", "ProcedureSyntax", "hello.scala"), expectedLayout = s"""/hello.scala - |$expected - |""".stripMargin, + |$expected + |""".stripMargin, expectedExit = ExitStatus.Ok ) check( name = "--syntactic ignores semantic rule", originalLayout = s"""| - |/.scalafix.conf - |rules = [ - | RemoveUnused - | ExplicitResultTypes - | ProcedureSyntax - |] - |/hello.scala - |$original - |""".stripMargin, + |/.scalafix.conf + |rules = [ + | RemoveUnused + | ExplicitResultTypes + | ProcedureSyntax + |] + |/hello.scala + |$original + |""".stripMargin, args = Array("--syntactic", "hello.scala"), expectedLayout = s"""| - |/.scalafix.conf - |rules = [ - | RemoveUnused - | ExplicitResultTypes - | ProcedureSyntax - |] - |/hello.scala - |$expected - |""".stripMargin, + |/.scalafix.conf + |rules = [ + | RemoveUnused + | ExplicitResultTypes + | ProcedureSyntax + |] + |/hello.scala + |$expected + |""".stripMargin, expectedExit = ExitStatus.Ok ) @@ -90,38 +90,38 @@ class CliSyntacticSuite extends BaseCliSuite { // same test as above except using @args expansion name = "@args", originalLayout = s"""/hello.scala - |$original - |/scalafix.args - |-r - |ProcedureSyntax - |hello.scala - |""".stripMargin, + |$original + |/scalafix.args + |-r + |ProcedureSyntax + |hello.scala + |""".stripMargin, args = Array("@scalafix.args"), expectedLayout = s"""/hello.scala - |$expected - |/scalafix.args - |-r - |ProcedureSyntax - |hello.scala - |""".stripMargin, + |$expected + |/scalafix.args + |-r + |ProcedureSyntax + |hello.scala + |""".stripMargin, expectedExit = ExitStatus.Ok ) check( name = "fix directory", originalLayout = s"""|/dir/a.scala - |$original - |/dir/b.scala - |$original""".stripMargin, + |$original + |/dir/b.scala + |$original""".stripMargin, args = Array( "-r", "ProcedureSyntax", "dir" ), expectedLayout = s"""|/dir/a.scala - |$expected - |/dir/b.scala - |$expected""".stripMargin, + |$expected + |/dir/b.scala + |$expected""".stripMargin, expectedExit = ExitStatus.Ok ) @@ -144,22 +144,22 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "TestError", originalLayout = s"""/foobar.scala - |$original""".stripMargin, + |$original""".stripMargin, args = Array("--check", "-r", "ProcedureSyntax", "foobar.scala"), expectedLayout = s"""/foobar.scala - |$original""".stripMargin, + |$original""".stripMargin, expectedExit = ExitStatus.TestError, outputAssert = { out => assert( out.endsWith( """| - |@@ -1,4 +1,4 @@ - | object Main { - |- def foo() { - |+ def foo(): Unit = { - | } - | } - |""".stripMargin + |@@ -1,4 +1,4 @@ + | object Main { + |- def foo() { + |+ def foo(): Unit = { + | } + | } + |""".stripMargin ) ) } @@ -168,52 +168,52 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "--check OK", originalLayout = s"""/foobar.scala - |$expected""".stripMargin, + |$expected""".stripMargin, args = Array("--check", "-r", "ProcedureSyntax", "foobar.scala"), expectedLayout = s"""/foobar.scala - |$expected""".stripMargin, + |$expected""".stripMargin, expectedExit = ExitStatus.Ok ) check( name = "--triggered is respected", originalLayout = s"""| - |/.scalafix.conf - |rules = [ - | RemoveUnused - |] - | - |triggered.rules = [ProcedureSyntax] - | - |/hello.scala - |$original - |""".stripMargin, + |/.scalafix.conf + |rules = [ + | RemoveUnused + |] + | + |triggered.rules = [ProcedureSyntax] + | + |/hello.scala + |$original + |""".stripMargin, args = Array("--triggered", "hello.scala"), expectedLayout = s"""| - |/.scalafix.conf - |rules = [ - | RemoveUnused - |] - | - |triggered.rules = [ProcedureSyntax] - | - |/hello.scala - |$expected - |""".stripMargin, + |/.scalafix.conf + |rules = [ + | RemoveUnused + |] + | + |triggered.rules = [ProcedureSyntax] + | + |/hello.scala + |$expected + |""".stripMargin, expectedExit = ExitStatus.Ok ) check( name = "linter error", originalLayout = s"""/foobar.scala - |$original""".stripMargin, + |$original""".stripMargin, args = Array( "-r", "scala:scalafix.tests.cli.LintError", "foobar.scala" ), expectedLayout = s"""/foobar.scala - |$original""".stripMargin, + |$original""".stripMargin, expectedExit = ExitStatus.LinterError, outputAssert = { out => assert(out.contains("Error!")) @@ -223,7 +223,7 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "linter warning promoted to error", originalLayout = s"""/foobar.scala - |$original""".stripMargin, + |$original""".stripMargin, args = Array( "--settings.lint.error", "LintWarning.warning", @@ -232,7 +232,7 @@ class CliSyntacticSuite extends BaseCliSuite { "foobar.scala" ), expectedLayout = s"""/foobar.scala - |$original""".stripMargin, + |$original""".stripMargin, expectedExit = ExitStatus.LinterError, outputAssert = { out => assert(out.contains("foobar.scala:1:1")) @@ -242,9 +242,9 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "--exclude is respected", originalLayout = s"""|/ignoreme.scala - |$original - |/fixme.scala - |$original""".stripMargin, + |$original + |/fixme.scala + |$original""".stripMargin, args = Array( "--exclude", "**ignoreme.scala", @@ -254,17 +254,17 @@ class CliSyntacticSuite extends BaseCliSuite { "fixme.scala" ), expectedLayout = s"""|/fixme.scala - |$expected - |/ignoreme.scala - |$original""".stripMargin, + |$expected + |/ignoreme.scala + |$original""".stripMargin, expectedExit = ExitStatus.Ok ) check( name = "--stdout does not write to file", originalLayout = s"""|/a.scala - |$original - |""".stripMargin, + |$original + |""".stripMargin, args = Array( "--stdout", "-r", @@ -272,7 +272,7 @@ class CliSyntacticSuite extends BaseCliSuite { "a.scala" ), expectedLayout = s"""|/a.scala - |$original""".stripMargin, + |$original""".stripMargin, expectedExit = ExitStatus.Ok, output => assertNoDiff(output, expected) ) @@ -280,23 +280,23 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "ParseError", originalLayout = s"""|/a.scala - |objec bar - |""".stripMargin, + |objec bar + |""".stripMargin, args = Array( "-r", "ProcedureSyntax", "a.scala" ), expectedLayout = s"""|/a.scala - |objec bar""".stripMargin, + |objec bar""".stripMargin, expectedExit = ExitStatus.ParseError, outputAssert = { out => assert( out.endsWith( """|a.scala:1:1: error: expected class or object definition identifier - |objec bar - |^^^^^ - |""".stripMargin + |objec bar + |^^^^^ + |""".stripMargin ) ) } @@ -305,36 +305,36 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "fix sbt files", originalLayout = s"""|/a.sbt - |def foo { println(1) } - |lazy val bar = project - |""".stripMargin, + |def foo { println(1) } + |lazy val bar = project + |""".stripMargin, args = Array( "-r", "ProcedureSyntax", "a.sbt" ), expectedLayout = s"""|/a.sbt - |def foo: Unit = { println(1) } - |lazy val bar = project - |""".stripMargin, + |def foo: Unit = { println(1) } + |lazy val bar = project + |""".stripMargin, expectedExit = ExitStatus.Ok ) check( name = "deprecated name emits warning", originalLayout = s"""|/a.scala - |object a { - |} - |""".stripMargin, + |object a { + |} + |""".stripMargin, args = Array( "-r", "OldDeprecatedName", // class:scalafix.tests.cli.DeprecatedName "a.scala" ), expectedLayout = s"""|/a.scala - |object a { - |} - |""".stripMargin, + |object a { + |} + |""".stripMargin, expectedExit = ExitStatus.Ok, output => assert(output.contains("Use DeprecatedName instead")) ) @@ -342,19 +342,20 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "no files to fix is error", originalLayout = s"""|/dir/a.java - |package a; - |class A - |""".stripMargin, + |package a; + |class A + |""".stripMargin, args = Array( "-r", "ProcedureSyntax", "dir" ), expectedLayout = s"""|/dir/a.java - |package a; - |class A - |""".stripMargin, - expectedExit = ExitStatus.NoFilesError, { output => + |package a; + |class A + |""".stripMargin, + expectedExit = ExitStatus.NoFilesError, + { output => assert(output.contains("No files to fix")) } ) @@ -362,9 +363,9 @@ class CliSyntacticSuite extends BaseCliSuite { check( name = "--out-from --out-to change output path", originalLayout = """ - |/src/shared/a.scala - |object a { def foo { println(1) } } - |""".stripMargin, + |/src/shared/a.scala + |object a { def foo { println(1) } } + |""".stripMargin, args = Array( "-r", "ProcedureSyntax", @@ -375,63 +376,63 @@ class CliSyntacticSuite extends BaseCliSuite { "src" ), expectedLayout = """ - |/src/fixed/a.scala - |object a { def foo: Unit = { println(1) } } - | - |/src/shared/a.scala - |object a { def foo { println(1) } } - |""".stripMargin, + |/src/fixed/a.scala + |object a { def foo: Unit = { println(1) } } + | + |/src/shared/a.scala + |object a { def foo { println(1) } } + |""".stripMargin, expectedExit = ExitStatus.Ok ) check( name = "skip parser when it's not needed", originalLayout = """ - |/src/shared/a.scala - |object a { - |""".stripMargin, + |/src/shared/a.scala + |object a { + |""".stripMargin, args = Array( "-r", "NoOpRule" ), expectedLayout = """ - |/src/shared/a.scala - |object a { - |""".stripMargin, + |/src/shared/a.scala + |object a { + |""".stripMargin, expectedExit = ExitStatus.Ok ) check( name = "don't skip parser when there is a suppression", originalLayout = """ - |/src/shared/a.scala - |object a { // scalafix: - |""".stripMargin, + |/src/shared/a.scala + |object a { // scalafix: + |""".stripMargin, args = Array( "-r", "NoOpRule" ), expectedLayout = """ - |/src/shared/a.scala - |object a { // scalafix: - |""".stripMargin, + |/src/shared/a.scala + |object a { // scalafix: + |""".stripMargin, expectedExit = ExitStatus.ParseError ) check( name = "unexpected error", originalLayout = """ - |/src/shared/a.scala - |object a { } - |""".stripMargin, + |/src/shared/a.scala + |object a { } + |""".stripMargin, args = Array( "-r", "CrashingRule" ), expectedLayout = """ - |/src/shared/a.scala - |object a { } - |""".stripMargin, + |/src/shared/a.scala + |object a { } + |""".stripMargin, outputAssert = { out => assert(out.contains("FileException"), out) assert(out.contains("a.scala"), out) @@ -462,14 +463,16 @@ class CliSyntacticSuite extends BaseCliSuite { checkCommandLineError( "--scala-version error", - Array("-r", "Scala2_9", "--scala-version", "2.12.8"), { out => + Array("-r", "Scala2_9", "--scala-version", "2.12.8"), + { out => assert(out.contains("must start with 2.9")) } ) checkCommandLineError( "--scalac-options error", - Array("-r", "Scala2_9", "--scala-version", "2.9.6"), { out => + Array("-r", "Scala2_9", "--scala-version", "2.9.6"), + { out => assert(out.contains("must contain -Ysource:2.9")) } ) diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/ScalafixImplSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/ScalafixImplSuite.scala index 8740bfc3d..850524edd 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/ScalafixImplSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/cli/ScalafixImplSuite.scala @@ -99,12 +99,12 @@ class ScalafixImplSuite extends AnyFunSuite with DiffAssertions { val cwd = StringFS .string2dir( """|/src/Semicolon.scala - | - |object Semicolon { - | def main { println(42) } - |} - |/.scalafix.conf - |rules = ["DisableSyntax"] + | + |object Semicolon { + | def main { println(42) } + |} + |/.scalafix.conf + |rules = ["DisableSyntax"] """.stripMargin, charset ) @@ -142,17 +142,17 @@ class ScalafixImplSuite extends AnyFunSuite with DiffAssertions { val cwd = StringFS .string2dir( """|/src/Semicolon.scala - | - |object Semicolon { - | val a = 1; // みりん þæö - | implicit val b = List(1) - | def main { println(42) } - |} - | - |/src/Excluded.scala - |object Excluded { - | val a = 1; - |} + | + |object Semicolon { + | val a = 1; // みりん þæö + | implicit val b = List(1) + | def main { println(42) } + |} + | + |/src/Excluded.scala + |object Excluded { + | val a = 1; + |} """.stripMargin, charset ) @@ -273,24 +273,24 @@ class ScalafixImplSuite extends AnyFunSuite with DiffAssertions { assertNoDiff( linterDiagnostics, """|src/Semicolon.scala:3:12: ERROR: semicolons are disabled - | val a = 1; // ??? ??? - | ^ + | val a = 1; // ??? ??? + | ^ """.stripMargin ) assertNoDiff( stdout, """|--- src/Semicolon.scala - |+++ - |@@ -1,6 +1,7 @@ - | object Semicolon { - | val a = 1; // ??? ??? - |- implicit val b = List(1) - |- def main { println(42) } - |+ implicit val b: List[Int] = List(1) - |+ def main: Unit = { println(42) } - | } - |+// Hello world! - |""".stripMargin + |+++ + |@@ -1,6 +1,7 @@ + | object Semicolon { + | val a = 1; // ??? ??? + |- implicit val b = List(1) + |- def main { println(42) } + |+ implicit val b: List[Int] = List(1) + |+ def main: Unit = { println(42) } + | } + |+// Hello world! + |""".stripMargin ) } } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/config/DisableSyntaxConfigSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/config/DisableSyntaxConfigSuite.scala index 8bb8d0969..a0f260fc2 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/config/DisableSyntaxConfigSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/config/DisableSyntaxConfigSuite.scala @@ -11,9 +11,9 @@ class DisableSyntaxConfigSuite extends AnyFunSuite { test("Warn about invalid keywords") { val rawConfig = """|keywords = [ - | banana - |] - |""".stripMargin + | banana + |] + |""".stripMargin val errorMessage = "banana is not in our supported keywords." assertError(rawConfig, errorMessage) } @@ -21,9 +21,9 @@ class DisableSyntaxConfigSuite extends AnyFunSuite { test("Provide suggestions when typos are present in keywords") { val rawConfig = """|keywords = [ - | overide - |] - |""".stripMargin + | overide + |] + |""".stripMargin val errorMessage = "overide is not in our supported keywords. (Did you mean: override?)" assertError(rawConfig, errorMessage) @@ -32,24 +32,24 @@ class DisableSyntaxConfigSuite extends AnyFunSuite { test("Warn about wrong types") { val rawConfig = """|keywords = [ - | 42 - |] - |""".stripMargin + | 42 + |] + |""".stripMargin val errorMessage = """|Type mismatch; - | found : Number (value: 42) - | expected : String""".stripMargin + | found : Number (value: 42) + | expected : String""".stripMargin assertError(rawConfig, errorMessage) } test("Handles non-string types") { val rawConfig = """|keywords = [ - | null - | false - | true - |] - |""".stripMargin + | null + | false + | true + |] + |""".stripMargin val obtained = read(rawConfig).get val expected = DisableSyntaxConfig( diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/config/ScalafixConfigSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/config/ScalafixConfigSuite.scala index 15d8f6cfa..d0cadce43 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/config/ScalafixConfigSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/config/ScalafixConfigSuite.scala @@ -5,8 +5,8 @@ import metaconfig.typesafeconfig._ import scalafix.internal.config.ScalafixConfig class ScalafixConfigSuite extends munit.FunSuite { - def check(name: String, config: String, expected: ScalafixConfig)( - implicit loc: munit.Location + def check(name: String, config: String, expected: ScalafixConfig)(implicit + loc: munit.Location ): Unit = { test(name) { val obtained = Conf.parseString(config).get.as[ScalafixConfig].get diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/DialectSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/DialectSuite.scala index 7aeb150c1..b38cdfcf9 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/DialectSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/DialectSuite.scala @@ -11,14 +11,13 @@ class DialectSuite extends AbstractSyntacticRuleSuite with AnyFunSuiteLike { val original: String = """|object LiteralType { - | val x: 41 = 41 - |} - |""".stripMargin + | val x: 41 = 41 + |} + |""".stripMargin val LiteralType: Rule = Rule.syntactic("LiteralType") { ctx => - ctx.tree.collect { - case lit @ Lit.Int(n) => - ctx.replaceTree(lit, (n + 1).toString) + ctx.tree.collect { case lit @ Lit.Int(n) => + ctx.replaceTree(lit, (n + 1).toString) }.asPatch } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/EscapeHatchSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/EscapeHatchSuite.scala index 0b5b6a274..77d03c938 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/EscapeHatchSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/EscapeHatchSuite.scala @@ -75,7 +75,12 @@ class EscapeHatchSuite extends AnyFunSuite { intercept[DontTouchMe] { EscapeHatch(input, untouchableTree, comments, EmptyDiff) } - EscapeHatch(input, tree, untouchableComments, EmptyDiff) // should not touch comments + EscapeHatch( + input, + tree, + untouchableComments, + EmptyDiff + ) // should not touch comments } test("`apply` should evaluate tree if `@SuppressWarnings` is found") { @@ -84,14 +89,24 @@ class EscapeHatchSuite extends AnyFunSuite { intercept[DontTouchMe] { EscapeHatch(input, untouchableTree, comments, EmptyDiff) } - EscapeHatch(input, tree, untouchableComments, EmptyDiff) // should not touch comments + EscapeHatch( + input, + tree, + untouchableComments, + EmptyDiff + ) // should not touch comments } test( "`isEmpty` should not evaluate tree nor associated comments if escapes are not found" ) { assert( - EscapeHatch(noEscapes, untouchableTree, untouchableComments, EmptyDiff).isEmpty + EscapeHatch( + noEscapes, + untouchableTree, + untouchableComments, + EmptyDiff + ).isEmpty ) } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/PatchSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/PatchSuite.scala index 47d2e952c..53d54f5cb 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/PatchSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/PatchSuite.scala @@ -62,13 +62,13 @@ class PatchSuite extends AbstractSyntacticRuleSuite with AnyFunSuiteLike { addRightRule, Input.File(file), s"""--- ${file.getAbsolutePath} - |+++ ${file.getAbsolutePath} - |@@ -1,4 +1,4 @@ - | // Foobar - |-object a { - |+object abba { - | val x = 2 - | }""".stripMargin + |+++ ${file.getAbsolutePath} + |@@ -1,4 +1,4 @@ + | // Foobar + |-object a { + |+object abba { + | val x = 2 + | }""".stripMargin ) val addLeftRule: Rule = Rule.syntactic("addLeft") { (ctx) => diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/PrettyTypeSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/PrettyTypeSuite.scala index ee5dd41a5..3b02ec4dc 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/PrettyTypeSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/PrettyTypeSuite.scala @@ -39,25 +39,24 @@ class PrettyTypeSuite extends BasePrettyTypeSuite { case m.Defn.Def(mods, name, tparams, paramss, Some(decltpe), _) => m.Decl.Def(mods, name, tparams, paramss, decltpe) } - stats.collect { - case expected: m.Member => - val name = expected.name.value - test(s"${expected.productPrefix} - $name") { - val suffix: String = expected match { - case _: m.Defn.Object => s"$name." - case _: m.Pkg.Object => s"$name/package." - case _ => s"$name#" - } - val sym = s"test/$suffix" - val info = - table.info(sym).getOrElse(throw new NoSuchElementException(sym)) - val obtained = - PrettyType - .toTree(info, table, QualifyStrategy.Readable, fatalErrors = true) - .tree - val expectedSyntax = expected.syntax - assertNoDiff(obtained.syntax, expectedSyntax) + stats.collect { case expected: m.Member => + val name = expected.name.value + test(s"${expected.productPrefix} - $name") { + val suffix: String = expected match { + case _: m.Defn.Object => s"$name." + case _: m.Pkg.Object => s"$name/package." + case _ => s"$name#" } + val sym = s"test/$suffix" + val info = + table.info(sym).getOrElse(throw new NoSuchElementException(sym)) + val obtained = + PrettyType + .toTree(info, table, QualifyStrategy.Readable, fatalErrors = true) + .tree + val expectedSyntax = expected.syntax + assertNoDiff(obtained.syntax, expectedSyntax) + } } } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/SemanticdbIndexSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/SemanticdbIndexSuite.scala index 066876e84..6301e2d3c 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/SemanticdbIndexSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/SemanticdbIndexSuite.scala @@ -12,11 +12,10 @@ class SemanticdbIndexSuite extends BaseSemanticSuite("SemanticdbIndexTest") { val mutable = SymbolMatcher.exact(Symbol("scala/collection/mutable/")) var hasAssert = false - source.collect { - case importee @ Importee.Name(name @ Name("mutable")) => - assert(index.symbol(importee) == index.symbol(name)) - assert(importee.matches(mutable)) - hasAssert = true + source.collect { case importee @ Importee.Name(name @ Name("mutable")) => + assert(index.symbol(importee) == index.symbol(name)) + assert(importee.matches(mutable)) + hasAssert = true } assert(hasAssert) } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/util/TokenListSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/util/TokenListSuite.scala index b7a36541f..e6921185e 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/core/util/TokenListSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/core/util/TokenListSuite.scala @@ -98,7 +98,9 @@ class TokenListSuite extends AnyFunSuite { assert(tokenList.slice(tokens.head, tokens(1)).toList == List(tokens.head)) } - test("slice returns empty seq if `from` and `to` tokens are the same object") { + test( + "slice returns empty seq if `from` and `to` tokens are the same object" + ) { assert(tokenList.slice(tokens.head, tokens.head).toList == List()) } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/interfaces/ScalafixArgumentsSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/interfaces/ScalafixArgumentsSuite.scala index 25b332567..1639a7c6d 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/interfaces/ScalafixArgumentsSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/interfaces/ScalafixArgumentsSuite.scala @@ -44,14 +44,14 @@ class ScalafixArgumentsSuite extends AnyFunSuite with DiffAssertions { val cwd: Path = StringFS .string2dir( """|/src/Main.scala - |import scala.concurrent.duration - |import scala.concurrent.Future - | - |object Main extends App { - | import scala.concurrent.Await - | println("test"); - | println("ok") - |} + |import scala.concurrent.duration + |import scala.concurrent.Future + | + |object Main extends App { + | import scala.concurrent.Await + | println("test"); + | println("ok") + |} """.stripMargin, charset ) @@ -104,11 +104,11 @@ class ScalafixArgumentsSuite extends AnyFunSuite with DiffAssertions { assert(fileEvaluation.isSuccessful) val expected = """| - |object Main extends App { - | println("test"); - | println("ok") - |} - |""".stripMargin + |object Main extends App { + | println("test"); + | println("ok") + |} + |""".stripMargin val obtained = fileEvaluation.previewPatches.get() assertNoDiff(obtained, expected) @@ -125,8 +125,8 @@ class ScalafixArgumentsSuite extends AnyFunSuite with DiffAssertions { assertNoDiff( linterErrorFormatted, """|src/Main.scala:6:18: ERROR: semicolons are disabled - | println("test"); - | ^ + | println("test"); + | ^ """.stripMargin ) @@ -136,14 +136,14 @@ class ScalafixArgumentsSuite extends AnyFunSuite with DiffAssertions { val expectedWithOnePatch = """| - |import scala.concurrent.Future - | - |object Main extends App { - | import scala.concurrent.Await - | println("test"); - | println("ok") - |} - |""".stripMargin + |import scala.concurrent.Future + | + |object Main extends App { + | import scala.concurrent.Await + | println("test"); + | println("ok") + |} + |""".stripMargin // if applying all patches we should get the same result val obtained2 = fileEvaluation.previewPatches(patches.toArray).get() @@ -267,11 +267,11 @@ class ScalafixArgumentsSuite extends AnyFunSuite with DiffAssertions { test("Suppression mechanism isn't applied with non atomic patches") { val content = """|import scala.concurrent.duration // scalafix:ok - |import scala.concurrent.Future""".stripMargin + |import scala.concurrent.Future""".stripMargin val cwd = StringFS .string2dir( s"""|/src/Main.scala - |$content""".stripMargin, + |$content""".stripMargin, charset ) .toNIO @@ -285,18 +285,18 @@ class ScalafixArgumentsSuite extends AnyFunSuite with DiffAssertions { // A patch without `atomic` will ignore suppressions. val expected = """|/*import scala.concurrent.duration // scalafix:ok - |import scala.concurrent.Future*/""".stripMargin + |import scala.concurrent.Future*/""".stripMargin assertNoDiff(obtained, expected) } test("Suppression mechanism is applied with atomic patches") { val content = """|import scala.concurrent.duration // scalafix:ok - |import scala.concurrent.Future""".stripMargin + |import scala.concurrent.Future""".stripMargin val cwd = StringFS .string2dir( s"""|/src/Main.scala - |$content""".stripMargin, + |$content""".stripMargin, charset ) .toNIO diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/interfaces/ScalafixSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/interfaces/ScalafixSuite.scala index 9533bb6bb..a722f7009 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/interfaces/ScalafixSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/interfaces/ScalafixSuite.scala @@ -27,7 +27,10 @@ class ScalafixSuite extends AnyFunSuite { } def fetchAndLoad(scalaVersion: String): Unit = { - test(s"fetch & load instance for Scala version $scalaVersion", SkipWindows) { + test( + s"fetch & load instance for Scala version $scalaVersion", + SkipWindows + ) { val scalafixAPI = Scalafix.fetchAndClassloadInstance( scalaVersion, Seq[Repository]( @@ -62,7 +65,9 @@ class ScalafixSuite extends AnyFunSuite { maybeDiagnostic = Some(diagnostic) } args - .withPaths(Seq(ruleSource).asJava) // any file would do, we just want rules to be loaded + .withPaths( + Seq(ruleSource).asJava + ) // any file would do, we just want rules to be loaded .withRules(Seq(s"file:$ruleSource").asJava) .withMainCallback(scalafixMainCallback) .run() @@ -81,8 +86,12 @@ class ScalafixSuite extends AnyFunSuite { Seq[String]("com.nequissimus::sort-imports:0.5.2").asJava, Seq[Repository](Repository.central()).asJava ) - assert(args.availableRules.asScala.map(_.name).contains("RemoveUnused")) // built-in rule - assert(args.availableRules.asScala.map(_.name).contains("SortImports")) // community rule + assert( + args.availableRules.asScala.map(_.name).contains("RemoveUnused") + ) // built-in rule + assert( + args.availableRules.asScala.map(_.name).contains("SortImports") + ) // community rule } } val supportedScalaBinaryVersions: Set[String] = Set("2.11", "2.12", "2.13") diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/reflect/ToolClasspathSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/reflect/ToolClasspathSuite.scala index 27d6f192a..4b9964c71 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/reflect/ToolClasspathSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/reflect/ToolClasspathSuite.scala @@ -33,7 +33,10 @@ class ToolClasspathSuite extends AnyFunSuite with BeforeAndAfterAll { scalafmtClasspath = jars.map(AbsolutePath(_)) } - test("--tool-classpath is respected when compiling from source", SkipWindows) { + test( + "--tool-classpath is respected when compiling from source", + SkipWindows + ) { val scalafmtRewrite = """ |import org.scalafmt._ diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/testkit/AssertDeltaSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/testkit/AssertDeltaSuite.scala index 448602204..d8ad9c70f 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/testkit/AssertDeltaSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/testkit/AssertDeltaSuite.scala @@ -23,25 +23,25 @@ class AssertDeltaSuite() extends AnyFunSuite with DiffAssertions { val input = Input.VirtualFile( path = "foo/bar/Disable.scala", value = """|case object Disable { - | Option(1).get /* assert: Disable.get - | ^ - |Option.get is the root of all evils - |*/ - | - | Option(2).get // assert: Disable.foo - | - | 3 // assert: Disable.get - | - | Option(4).get - | - | 5 // assert: Disable.get - | - | Option(6).get - | - | 7 // assert: Disable.get - | - | Option(8).get - |}""".stripMargin + | Option(1).get /* assert: Disable.get + | ^ + |Option.get is the root of all evils + |*/ + | + | Option(2).get // assert: Disable.foo + | + | 3 // assert: Disable.get + | + | Option(4).get + | + | 5 // assert: Disable.get + | + | Option(6).get + | + | 7 // assert: Disable.get + | + | Option(8).get + |}""".stripMargin ) def disable(offset: Int): RuleDiagnostic = @@ -76,73 +76,73 @@ class AssertDeltaSuite() extends AnyFunSuite with DiffAssertions { val expected = """|===========> Mismatch <=========== - | - |Obtained: foo/bar/Disable.scala:2:13: error: [Disable.get]: - |Option.get is the root of all evils - | Option(1).get /* assert: Disable.get - | ^ - |Expected: foo/bar/Disable.scala:2:14: error: - |Option.get is the root of all evils - | Option(1).get /* assert: Disable.get - | ^ - |Diff: - | Option(1).get /* assert: Disable.get - | ^-- asserted - | ^-- reported - | - | - |--------------------------------------- - | - |Obtained: foo/bar/Disable.scala:7:13: error: [Disable.get]: - |Option.get is the root of all evils - | Option(2).get // assert: Disable.foo - | ^ - |Expected: foo/bar/Disable.scala:7:17: error - | Option(2).get // assert: Disable.foo - | ^^^^^^^^^^^^^^^^^^^^^^ - |Diff: - |-Disable.foo - |+Disable.get - | - |===========> Unexpected <=========== - | - |foo/bar/Disable.scala:11:13: error: [Disable.get]: - |Option.get is the root of all evils - | Option(4).get - | ^ - | - |--------------------------------------- - | - |foo/bar/Disable.scala:15:13: error: [Disable.get]: - |Option.get is the root of all evils - | Option(6).get - | ^ - | - |--------------------------------------- - | - |foo/bar/Disable.scala:19:13: error: [Disable.get]: - |Option.get is the root of all evils - | Option(8).get - | ^ - | - |===========> Unreported <=========== - | - |foo/bar/Disable.scala:9:5: error - | 3 // assert: Disable.get - | ^^^^^^^^^^^^^^^^^^^^^^ - | - |--------------------------------------- - | - |foo/bar/Disable.scala:13:5: error - | 5 // assert: Disable.get - | ^^^^^^^^^^^^^^^^^^^^^^ - | - |--------------------------------------- - | - |foo/bar/Disable.scala:17:5: error - | 7 // assert: Disable.get - | ^^^^^^^^^^^^^^^^^^^^^^ - |""".stripMargin + | + |Obtained: foo/bar/Disable.scala:2:13: error: [Disable.get]: + |Option.get is the root of all evils + | Option(1).get /* assert: Disable.get + | ^ + |Expected: foo/bar/Disable.scala:2:14: error: + |Option.get is the root of all evils + | Option(1).get /* assert: Disable.get + | ^ + |Diff: + | Option(1).get /* assert: Disable.get + | ^-- asserted + | ^-- reported + | + | + |--------------------------------------- + | + |Obtained: foo/bar/Disable.scala:7:13: error: [Disable.get]: + |Option.get is the root of all evils + | Option(2).get // assert: Disable.foo + | ^ + |Expected: foo/bar/Disable.scala:7:17: error + | Option(2).get // assert: Disable.foo + | ^^^^^^^^^^^^^^^^^^^^^^ + |Diff: + |-Disable.foo + |+Disable.get + | + |===========> Unexpected <=========== + | + |foo/bar/Disable.scala:11:13: error: [Disable.get]: + |Option.get is the root of all evils + | Option(4).get + | ^ + | + |--------------------------------------- + | + |foo/bar/Disable.scala:15:13: error: [Disable.get]: + |Option.get is the root of all evils + | Option(6).get + | ^ + | + |--------------------------------------- + | + |foo/bar/Disable.scala:19:13: error: [Disable.get]: + |Option.get is the root of all evils + | Option(8).get + | ^ + | + |===========> Unreported <=========== + | + |foo/bar/Disable.scala:9:5: error + | 3 // assert: Disable.get + | ^^^^^^^^^^^^^^^^^^^^^^ + | + |--------------------------------------- + | + |foo/bar/Disable.scala:13:5: error + | 5 // assert: Disable.get + | ^^^^^^^^^^^^^^^^^^^^^^ + | + |--------------------------------------- + | + |foo/bar/Disable.scala:17:5: error + | 7 // assert: Disable.get + | ^^^^^^^^^^^^^^^^^^^^^^ + |""".stripMargin assertNoDiff(expected, obtained) } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/util/PrettyExpectSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/util/PrettyExpectSuite.scala index 86ea6b018..e8efc02ab 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/util/PrettyExpectSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/util/PrettyExpectSuite.scala @@ -29,12 +29,11 @@ class PrettyExpectSuite extends ExpectSuite { pos -> Pretty.pretty(info) } val rows = (synthetics ++ types) - .sortBy { - case (pos, _) => pos.start + .sortBy { case (pos, _) => + pos.start } - .map { - case (pos, doc) => - s"[${pos.rangeNumber}]: " -> doc + .map { case (pos, doc) => + s"[${pos.rangeNumber}]: " -> doc } Doc.tabulate(rows.toList).render(80) diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/util/ScalametaStructureSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/util/ScalametaStructureSuite.scala index d6850d4d7..8dd020ef1 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/util/ScalametaStructureSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/util/ScalametaStructureSuite.scala @@ -11,16 +11,16 @@ class ScalametaStructureSuite extends AnyFunSuite with DiffAssertions { val obtained = q"a.b.c.d".structureWidth(1) val expected = """|Term.Select( - | Term.Select( - | Term.Select( - | Term.Name("a"), - | Term.Name("b") - | ), - | Term.Name("c") - | ), - | Term.Name("d") - |) - |""".stripMargin + | Term.Select( + | Term.Select( + | Term.Name("a"), + | Term.Name("b") + | ), + | Term.Name("c") + | ), + | Term.Name("d") + |) + |""".stripMargin assertNoDiff(obtained, expected) } @@ -28,17 +28,17 @@ class ScalametaStructureSuite extends AnyFunSuite with DiffAssertions { val obtained = q"a.b.c.d".structureLabeled(1) val expected = """| - |Term.Select( - | qual = Term.Select( - | qual = Term.Select( - | qual = Term.Name("a"), - | name = Term.Name("b") - | ), - | name = Term.Name("c") - | ), - | name = Term.Name("d") - |) - |""".stripMargin + |Term.Select( + | qual = Term.Select( + | qual = Term.Select( + | qual = Term.Name("a"), + | name = Term.Name("b") + | ), + | name = Term.Name("c") + | ), + | name = Term.Name("d") + |) + |""".stripMargin assertNoDiff(obtained, expected) } @@ -46,8 +46,8 @@ class ScalametaStructureSuite extends AnyFunSuite with DiffAssertions { assertNoDiff( q"def foo: A = ???".decltpe.structureWidth(1), """| - |Some(Type.Name("A")) - |""".stripMargin + |Some(Type.Name("A")) + |""".stripMargin ) } @@ -56,9 +56,9 @@ class ScalametaStructureSuite extends AnyFunSuite with DiffAssertions { // NOTE(olafur): need downcast because List is no longer a Product in 2.13. q"foo(a)".args.asInstanceOf[Product].structureWidth(1), """|List( - | Term.Name("a") - |) - |""".stripMargin + | Term.Name("a") + |) + |""".stripMargin ) } } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/v0/LegacyDenotationSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/v0/LegacyDenotationSuite.scala index 333c7003b..6bf4161e2 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/v0/LegacyDenotationSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/v0/LegacyDenotationSuite.scala @@ -10,31 +10,30 @@ class LegacyDenotationSuite extends BaseSemanticSuite("LegacyDenotationTest") { private val denotations = Map( "cmap" -> """|private val method cmap: Map[Int, Int] - | [0..3): Map => scala/collection/Map# - | [4..7): Int => scala/Int# - | [9..12): Int => scala/Int#""".stripMargin, + | [0..3): Map => scala/collection/Map# + | [4..7): Int => scala/Int# + | [9..12): Int => scala/Int#""".stripMargin, "cset" -> """|private val method cset: Set[Int] - | [0..3): Set => scala/collection/Set# - | [4..7): Int => scala/Int#""".stripMargin, + | [0..3): Set => scala/collection/Set# + | [4..7): Int => scala/Int#""".stripMargin, "imap" -> """|private val method imap: Map[Int, Int] - | [0..3): Map => scala/collection/immutable/Map# - | [4..7): Int => scala/Int# - | [9..12): Int => scala/Int#""".stripMargin, + | [0..3): Map => scala/collection/immutable/Map# + | [4..7): Int => scala/Int# + | [9..12): Int => scala/Int#""".stripMargin, "iset" -> """|private val method iset: Set[Int] - | [0..3): Set => scala/collection/immutable/Set# - | [4..7): Int => scala/Int#""".stripMargin + | [0..3): Set => scala/collection/immutable/Set# + | [4..7): Int => scala/Int#""".stripMargin ) def unapply(n: Term.Name): Option[String] = denotations.get(n.syntax) } val converted = source - .collect { - case tree @ TestDenotation(expected) => - index - .denotation(tree) - .map(obtained => (obtained.toString, expected)) + .collect { case tree @ TestDenotation(expected) => + index + .denotation(tree) + .map(obtained => (obtained.toString, expected)) } .flatten .distinct diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/v0/SymbolMatcherSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/v0/SymbolMatcherSuite.scala index ddbf33589..b875750b4 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/v0/SymbolMatcherSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/v0/SymbolMatcherSuite.scala @@ -12,12 +12,11 @@ class SymbolMatcherSuite extends BaseSemanticSuite("SymbolMatcherTest") { test("matches/unapply") { val symbolMatcher = SymbolMatcher.exact(Symbol("test/SymbolMatcherTest.")) - val assertions = source.collect { - case symbolMatcher(t @ Name(_)) => - assert(t.is[Term.Name]) - assert(t.parent.get.is[Defn.Object]) - assert(symbolMatcher.matches(t)) - assert(t.matches(symbolMatcher)) + val assertions = source.collect { case symbolMatcher(t @ Name(_)) => + assert(t.is[Term.Name]) + assert(t.parent.get.is[Defn.Object]) + assert(symbolMatcher.matches(t)) + assert(t.matches(symbolMatcher)) } assert(assertions.length == 1) } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/v1/SymbolMatcherSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/v1/SymbolMatcherSuite.scala index 4f3186abb..79e4716a5 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/v1/SymbolMatcherSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/v1/SymbolMatcherSuite.scala @@ -51,11 +51,10 @@ class SymbolMatcherSuite extends AnyFunSuite { test("matches/unapply") { val symbolMatcher = SymbolMatcher.exact("test/SymbolMatcherTest.") - val assertions = doc.tree.collect { - case symbolMatcher(t @ Name(_)) => - assert(t.is[Term.Name]) - assert(t.parent.get.is[Defn.Object]) - assert(symbolMatcher.matches(t)) + val assertions = doc.tree.collect { case symbolMatcher(t @ Name(_)) => + assert(t.is[Term.Name]) + assert(t.parent.get.is[Defn.Object]) + assert(symbolMatcher.matches(t)) } assert(assertions.length == 1) } diff --git a/scalafix-tests/unit/src/test/scala/scalafix/tests/v1/SymbolSuite.scala b/scalafix-tests/unit/src/test/scala/scalafix/tests/v1/SymbolSuite.scala index 77de27f15..479d737b2 100644 --- a/scalafix-tests/unit/src/test/scala/scalafix/tests/v1/SymbolSuite.scala +++ b/scalafix-tests/unit/src/test/scala/scalafix/tests/v1/SymbolSuite.scala @@ -10,8 +10,8 @@ class SymbolSuite extends munit.FunSuite { BaseSemanticSuite.loadDoc("SymbolTest.scala") test("normalized") { - val ref :: Nil = doc.tree.collect { - case Import(Importer(ref, _) :: Nil) => ref + val ref :: Nil = doc.tree.collect { case Import(Importer(ref, _) :: Nil) => + ref } assertEquals(ref.symbol.normalized.owner.value, "test.a.")