Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade the formatter for this repo to v3.1.0 #161

Merged
merged 1 commit into from
Nov 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
version = 2.2.1
version = 3.1.0
runner.dialect = scala213
project.git = true
project.excludeFilters = [
plugin/src/sbt-test
]
rewrite {
rules = [
Imports,
RedundantBraces,
RedundantParens
]
imports {
sort = ascii
groups = [
["javax?\\..*"],
["sbt\\..*"],
["scala\\..*"],
["org\\..*"]
]
}
}
align.tokens = none
assumeStandardLibraryStripMargin = true
onTestFailure = "To fix this, run ./bin/scalafmt from the project root directory"
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.scalafmt.sbt

import java.nio.file.Path

import org.scalafmt.interfaces.{Scalafmt, ScalafmtSession}

private[sbt] class CompatibilityScalafmtSession(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@ package org.scalafmt.sbt
trait ConcurrentRestrictionTags {
import sbt.ConcurrentRestrictions.Tag

/**
* This tag can be used to control the maximum number of parallel scalafmt tasks in large-scale build trees.
/** This tag can be used to control the maximum number of parallel scalafmt
* tasks in large-scale build trees.
*
* Global / concurrentRestrictions += Tags.limit(org.scalafmt.sbt.ConcurrentRestrictionTags.Scalafmt, 3)
* {{{
* Global / concurrentRestrictions +=
* Tags.limit(org.scalafmt.sbt.ConcurrentRestrictionTags.Scalafmt, 3)
* }}}
*
* would prevent SBT from spawning more than three simultaneous Scalafmt tasks
* would prevent SBT from spawning more than three simultaneous Scalafmt
* tasks
*
* @see https://www.scala-sbt.org/1.x/docs/Parallel-Execution.html
* @see
* https://www.scala-sbt.org/1.x/docs/Parallel-Execution.html
*/
val Scalafmt = Tag("scalafmt")
}
Expand Down
91 changes: 42 additions & 49 deletions plugin/src/main/scala/org/scalafmt/sbt/ScalafmtPlugin.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,20 @@ import java.io.OutputStreamWriter
import java.nio.file.Path

import sbt.Keys._
import sbt.Def
import sbt._
import complete.DefaultParsers._
import sbt.librarymanagement.MavenRepository
import sbt.util.CacheImplicits._
import sbt.util.CacheStoreFactory
import sbt.util.FileInfo
import sbt.util.FilesInfo
import sbt.util.Logger

import scala.util.Failure
import scala.util.Success
import scala.util.Try

import org.scalafmt.interfaces.{Scalafmt, ScalafmtSessionFactory}
import sbt.ConcurrentRestrictions.Tag
import sbt.librarymanagement.MavenRepository

import complete.DefaultParsers._

object ScalafmtPlugin extends AutoPlugin {
override def trigger: PluginTrigger = allRequirements
Expand Down Expand Up @@ -73,25 +72,27 @@ object ScalafmtPlugin extends AutoPlugin {
case class ScalafmtAnalysis(failedScalafmtCheck: Set[File])
object ScalafmtAnalysis {
import sjsonnew.{:*:, LList, LNil}
implicit val analysisIso = LList.iso({ a: ScalafmtAnalysis =>
("failedScalafmtCheck", a.failedScalafmtCheck) :*: LNil
}, { in: Set[File] :*: LNil =>
ScalafmtAnalysis(in.head)
})
implicit val analysisIso = LList.iso(
{ a: ScalafmtAnalysis =>
("failedScalafmtCheck", a.failedScalafmtCheck) :*: LNil
},
{ in: Set[File] :*: LNil =>
ScalafmtAnalysis(in.head)
}
)
}

private val scalafmtDoFormatOnCompile =
taskKey[Unit]("Format Scala source files if scalafmtOnCompile is on.")

private val scalaConfig = {
private val scalaConfig =
scalafmtConfig.map { f =>
if (f.exists()) {
f.toPath
} else {
throw new MessageOnlyException(s"File not exists: ${f.toPath}")
}
}
}
private val sbtConfig = scalaConfig

private type Input = String
Expand All @@ -110,8 +111,8 @@ object ScalafmtPlugin extends AutoPlugin {
onFormat: (File, Input, Output) => T
): Seq[Option[T]] = {
val reporter = new ScalafmtSbtReporter(log, writer, detailedErrorEnabled)
val repositories = resolvers.collect {
case r: MavenRepository => r.root
val repositories = resolvers.collect { case r: MavenRepository =>
r.root
}
val scalafmtSession =
globalInstance
Expand Down Expand Up @@ -154,7 +155,7 @@ object ScalafmtPlugin extends AutoPlugin {
writer: OutputStreamWriter,
resolvers: Seq[Resolver],
detailedErrorEnabled: Boolean
): Unit = {
): Unit =
trackSourcesAndConfig(cacheStoreFactory, sources, config) {
(outDiff, configChanged, prev) =>
log.debug(outDiff.toString)
Expand All @@ -179,7 +180,6 @@ object ScalafmtPlugin extends AutoPlugin {
}
ScalafmtAnalysis(Set.empty)
}
}

private def formatSources(
sources: Set[File],
Expand All @@ -197,16 +197,14 @@ object ScalafmtPlugin extends AutoPlugin {
writer,
resolvers,
detailedErrorEnabled
)(
(file, input, output) => {
if (input != output) {
IO.write(file, output)
1
} else {
0
}
) { (file, input, output) =>
if (input != output) {
IO.write(file, output)
1
} else {
0
}
).flatten.sum
}.flatten.sum

if (cnt > 1) {
log.info(s"Reformatted $cnt Scala sources")
Expand All @@ -222,7 +220,7 @@ object ScalafmtPlugin extends AutoPlugin {
writer: OutputStreamWriter,
resolvers: Seq[Resolver],
detailedErrorEnabled: Boolean
): ScalafmtAnalysis = {
): ScalafmtAnalysis =
trackSourcesAndConfig(cacheStoreFactory, sources, config) {
(outDiff, configChanged, prev) =>
log.debug(outDiff.toString)
Expand All @@ -247,7 +245,6 @@ object ScalafmtPlugin extends AutoPlugin {
failedScalafmtCheck = result.failedScalafmtCheck | prevFailed
)
}
}

private def trueOrBoom(analysis: ScalafmtAnalysis): Boolean = {
val failureCount = analysis.failedScalafmtCheck.size
Expand All @@ -259,9 +256,8 @@ object ScalafmtPlugin extends AutoPlugin {
true
}

private def warnBadFormat(file: File, log: Logger): Unit = {
private def warnBadFormat(file: File, log: Logger): Unit =
log.warn(s"${file.toString} isn't formatted properly!")
}

private def checkSources(
sources: Seq[File],
Expand All @@ -282,15 +278,13 @@ object ScalafmtPlugin extends AutoPlugin {
writer,
resolvers,
detailedErrorEnabled
)(
(file, input, output) => {
val diff = input != output
if (diff) {
warnBadFormat(file, log)
Some(file)
} else None
}
).flatten.flatten.toSet
) { (file, input, output) =>
val diff = input != output
if (diff) {
warnBadFormat(file, log)
Some(file)
} else None
}.flatten.flatten.toSet
ScalafmtAnalysis(failedScalafmtCheck = unformatted)
}

Expand All @@ -313,14 +307,13 @@ object ScalafmtPlugin extends AutoPlugin {
val prev = prev0.getOrElse(ScalafmtAnalysis(Set.empty))
val tracker = Tracked.inputChanged[HashFileInfo, ScalafmtAnalysis](
cacheStoreFactory.make("config")
) {
case (configChanged, configHash) =>
Tracked.diffOutputs(
cacheStoreFactory.make("output-diff"),
FileInfo.lastModified
)(sources.toSet) { (outDiff: ChangeReport[File]) =>
f(outDiff, configChanged, prev)
}
) { case (configChanged, configHash) =>
Tracked.diffOutputs(
cacheStoreFactory.make("output-diff"),
FileInfo.lastModified
)(sources.toSet) { (outDiff: ChangeReport[File]) =>
f(outDiff, configChanged, prev)
}
}
tracker(FileInfo.hash(config.toFile))
}
Expand Down Expand Up @@ -448,14 +441,14 @@ object ScalafmtPlugin extends AutoPlugin {
.value,
scalafmtOnly := {
val files = spaceDelimited("<files>").parsed
val absFiles = files.flatMap(fileS => {
Try { IO.resolve(baseDirectory.value, new File(fileS)) } match {
val absFiles = files.flatMap { fileS =>
Try(IO.resolve(baseDirectory.value, new File(fileS))) match {
case Failure(e) =>
streams.value.log.error(s"Error with $fileS file: $e")
None
case Success(file) => Some(file)
}
})
}

// scalaConfig
formatSources(
Expand Down
15 changes: 7 additions & 8 deletions plugin/src/main/scala/org/scalafmt/sbt/ScalafmtSbtReporter.scala
Original file line number Diff line number Diff line change
@@ -1,39 +1,38 @@
package org.scalafmt.sbt

import java.io.PrintWriter
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.nio.file.Path
import org.scalafmt.interfaces.ScalafmtReporter

import sbt.internal.util.MessageOnlyException
import sbt.util.Logger

import scala.util.control.NoStackTrace

import org.scalafmt.interfaces.ScalafmtReporter

class ScalafmtSbtReporter(
log: Logger,
out: OutputStreamWriter,
detailedErrorEnabled: Boolean
) extends ScalafmtReporter {
override def error(file: Path, message: String): Unit = {
override def error(file: Path, message: String): Unit =
throw new MessageOnlyException(s"$message: $file")
}

override def error(file: Path, e: Throwable): Unit = {
override def error(file: Path, e: Throwable): Unit =
Option(e.getMessage) match {
case Some(_) if detailedErrorEnabled =>
throw new ScalafmtSbtError(file, e)
case Some(_) => error(file, e.getMessage)
case None => throw new FailedToFormat(file.toString, e)
}
}

override def error(file: Path, message: String, e: Throwable): Unit = {
override def error(file: Path, message: String, e: Throwable): Unit =
if (e.getMessage != null) {
error(file, s"$message: ${e.getMessage()}")
} else {
throw new FailedToFormat(file.toString, e)
}
}

override def excluded(file: Path): Unit =
log.debug(s"file excluded: $file")
Expand Down