Skip to content

Commit

Permalink
scalafmt: enable RedundantBraces rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Mar 31, 2024
1 parent d76cb7c commit 62270fe
Show file tree
Hide file tree
Showing 83 changed files with 678 additions and 918 deletions.
5 changes: 5 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,14 @@ newlines {
}
rewrite {
rules = [
RedundantBraces,
RedundantParens,
SortModifiers,
]
redundantBraces {
ifElseExpressions = true
stringInterpolation = true
}
sortModifiers.preset = styleGuide
}
# Disabled in default since this operation is potentially
Expand Down
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ val ReleaseCandidate = s"($V-RC\\d+).*".r
val Milestone = s"($V-M\\d+).*".r

lazy val stableVersion = Def
.setting { (ThisBuild / version).value.replaceAll("\\+.*", "") }
.setting((ThisBuild / version).value.replaceAll("\\+.*", ""))

lazy val buildInfoSettings: Seq[Def.Setting[_]] = Seq(
buildInfoKeys := Seq[BuildInfoKey](
Expand Down
3 changes: 1 addition & 2 deletions project/Mima.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import com.typesafe.tools.mima.core._

object Mima {
val ignoredABIProblems: Seq[ProblemFilter] = {
val ignoredABIProblems: Seq[ProblemFilter] =
// After v0.5, start running mima checks in CI and document breaking changes here.
// See https://github.com/typesafehub/migration-manager/wiki/sbt-plugin#basic-usage
Seq(
Expand All @@ -12,5 +12,4 @@ object Mima {
ProblemFilters.exclude[Problem]("org.scalafmt.rewrite.*"),
ProblemFilters.exclude[Problem]("org.scalafmt.util.*")
)
}
}
31 changes: 12 additions & 19 deletions readme/src/main/scala/org/scalafmt/readme/Readme.scala
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ object Readme {
hl.scala(result)
}

def config(frags: Frag*) = { cliFlags(frags.render) }
def config(frags: Frag*) = cliFlags(frags.render)
def cliFlags(flags: String) = {
Config.fromHoconString(flags).get
hl.scala(flags)
Expand Down Expand Up @@ -118,18 +118,14 @@ object Readme {
def configurationBlock(
style: ScalafmtConfig,
collapsed: Boolean = false
): TypedTag[String] = {
div(
span(
"Show/hide configuration used for this example",
`class` := "scalafmt-configuration-toggle"
),
pre(changedConfig(style)),
`class` := {
"scalafmt-configuration" + (if (collapsed) " collapsed" else "")
}
)
}
): TypedTag[String] = div(
span(
"Show/hide configuration used for this example",
`class` := "scalafmt-configuration-toggle"
),
pre(changedConfig(style)),
`class` := "scalafmt-configuration" + (if (collapsed) " collapsed" else "")
)

def fullWidthDemo(style: ScalafmtConfig)(code: String): TypedTag[String] = {
val formatted = Scalafmt.format(code, style).get
Expand All @@ -148,9 +144,8 @@ object Readme {
div(sideBySide(code, formatted), configurationBlock(style))
}

def example(code: String): TypedTag[String] = {
def example(code: String): TypedTag[String] =
example(code, ScalafmtConfig.default40)
}

def exampleAlign(code: String): TypedTag[String] = {
val formatted = Scalafmt.format(
Expand Down Expand Up @@ -270,9 +265,8 @@ object Readme {
def lastUpdated = new SimpleDateFormat("MMM d, y")
.format(new Date(Versions.timestamp.toLong))

def format(code: String): TypedTag[String] = {
def format(code: String): TypedTag[String] =
format(ScalafmtConfig.default)(code)
}

val alignNone = ScalafmtConfig.default.copy(align = Align.none)
val alignSome = ScalafmtConfig.default.copy(align = Align.some)
Expand All @@ -283,9 +277,8 @@ object Readme {
.copy(align = Align.default.copy(arrowEnumeratorGenerator = true))
val alignModuleId = ScalafmtConfig.defaultWithAlign

def format(style: ScalafmtConfig)(code: String): TypedTag[String] = {
def format(style: ScalafmtConfig)(code: String): TypedTag[String] =
example(code, style.copy(runner = ScalafmtRunner.sbt))
}

def example(code: String, style: ScalafmtConfig): TypedTag[String] = {
val formatted = Scalafmt.format(code, style).get
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,13 @@ abstract class MacroBenchmark(parallel: Boolean, maxFiles: Int)
override def toString = s"${this.getClass.getName}(parallel=$parallel)"

@Setup
def setup(): Unit = {
files = {
val x = Corpus.files(Corpus.fastparse.copy(
// TODO(olafur) remove once testkit 1.7 is out
url = Corpus.fastparse.url.replace("olafurpg", "scalameta")
)).filter { f => f.projectUrl.contains("scala-js") }.take(maxFiles)
.map(_.read).toBuffer
if (parallel) x.par else x
}
def setup(): Unit = files = {
val x = Corpus.files(Corpus.fastparse.copy(
// TODO(olafur) remove once testkit 1.7 is out
url = Corpus.fastparse.url.replace("olafurpg", "scalameta")
)).filter(f => f.projectUrl.contains("scala-js")).take(maxFiles).map(_.read)
.toBuffer
if (parallel) x.par else x
}

def testMe(): Unit = {
Expand All @@ -44,14 +42,10 @@ abstract class MacroBenchmark(parallel: Boolean, maxFiles: Int)
}

@Benchmark
def scalafmt(): Unit = {
files.foreach { file => Try(Scalafmt.format(file)) }
}
def scalafmt(): Unit = files.foreach(file => Try(Scalafmt.format(file)))

@Benchmark
def scalafmt_rewrite(): Unit = {
files.foreach { file => Try(formatRewrite(file)) }
}
def scalafmt_rewrite(): Unit = files.foreach(file => Try(formatRewrite(file)))

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ import org.scalafmt.config.{RewriteSettings, ScalafmtConfig}
import org.scalafmt.rewrite.{RedundantBraces, SortImports}

trait FormatBenchmark {
def formatRewrite(code: String): String = {
Scalafmt.formatCode(
code,
baseStyle = ScalafmtConfig.default
.copy(rewrite = RewriteSettings(rules = Seq(SortImports, RedundantBraces)))
).get
}
def formatRewrite(code: String): String = Scalafmt.formatCode(
code,
baseStyle = ScalafmtConfig.default
.copy(rewrite = RewriteSettings(rules = Seq(SortImports, RedundantBraces)))
).get
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ abstract class MicroBenchmark(path: String*) extends FormatBenchmark {
var code: String = _

@Setup
def setup(): Unit = { code = FileOps.readFile(getPath) }
def setup(): Unit = code = FileOps.readFile(getPath)

def getPath: Path = {
val filename = FileOps.getFile(Seq("src", "resources") ++ path)
Expand All @@ -42,10 +42,10 @@ abstract class MicroBenchmark(path: String*) extends FormatBenchmark {
}

@Benchmark
def scalafmt(): String = { Scalafmt.format(code).get }
def scalafmt(): String = Scalafmt.format(code).get

@Benchmark
def scalafmt_rewrite(): String = { formatRewrite(code) }
def scalafmt_rewrite(): String = formatRewrite(code)

def testMe(): Unit = {
setup()
Expand Down
33 changes: 13 additions & 20 deletions scalafmt-cli/src/main/scala/org/scalafmt/cli/Cli.scala
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,16 @@ object Cli {
nGContext.exit(exit.code)
}

private def throwIfError(exit: ExitCode): Unit = {
if (exit != ExitCode.Ok) {
throw new RuntimeException(exit.toString) with NoStackTrace
}
}
private def throwIfError(exit: ExitCode): Unit = if (exit != ExitCode.Ok)
throw new RuntimeException(exit.toString) with NoStackTrace

def main(args: Array[String]): Unit = {
val exit = mainWithOptions(args, CliOptions.default)
sys.exit(exit.code)
}

def exceptionThrowingMain(args: Array[String]): Unit = {
def exceptionThrowingMain(args: Array[String]): Unit =
exceptionThrowingMainWithOptions(args, CliOptions.default)
}

def exceptionThrowingMainWithOptions(
args: Array[String],
Expand All @@ -57,12 +53,11 @@ object Cli {
throwIfError(exit)
}

def mainWithOptions(args: Array[String], options: CliOptions): ExitCode = {
def mainWithOptions(args: Array[String], options: CliOptions): ExitCode =
getConfig(args, options) match {
case Some(x) => run(x)
case None => ExitCode.CommandLineArgumentError
}
}

def getConfig(args: Array[String], init: CliOptions): Option[CliOptions] = {
val expandedArguments = expandArguments(args)
Expand All @@ -81,14 +76,13 @@ object Cli {
builder.result()
}

private[cli] def run(options: CliOptions): ExitCode = {
private[cli] def run(options: CliOptions): ExitCode =
findRunner(options) match {
case Left(message) =>
options.common.err.println(message)
ExitCode.UnsupportedVersion
case Right(runner) => runWithRunner(options, runner)
}
}

private val isNativeImage: Boolean = "true" ==
System.getProperty("scalafmt.native-image", "false")
Expand Down Expand Up @@ -125,7 +119,7 @@ object Cli {
|""".stripMargin
)
} {
case Left(error) => Left(s"error: invalid configuration: ${error}")
case Left(error) => Left(s"error: invalid configuration: $error")
case Right(`stableVersion`) =>
options.common.debug.println(s"Using core runner [$stableVersion]")
Right(ScalafmtCoreRunner)
Expand Down Expand Up @@ -162,20 +156,19 @@ object Cli {

val exit = runner.run(options, termDisplayMessage)

if (options.writeMode == WriteMode.Test) {
if (exit.isOk) {
options.common.out.println("All files are formatted with scalafmt :)")
} else if (exit.is(ExitCode.TestError)) {
if (options.writeMode == WriteMode.Test)
if (exit.isOk) options.common.out
.println("All files are formatted with scalafmt :)")
else if (exit.is(ExitCode.TestError)) {
options.common.out.println("error: --test failed")
options.onTestFailure.foreach(options.common.out.println)
} else { options.common.out.println(s"error: $exit") }
}
} else options.common.out.println(s"error: $exit")
if (
options.writeMode == WriteMode.Test && !options.fatalWarnings &&
exit.is(ExitCode.ParseError)
) {
)
// Ignore parse errors etc.
ExitCode.Ok
} else { exit }
else exit
}
}
11 changes: 5 additions & 6 deletions scalafmt-cli/src/main/scala/org/scalafmt/cli/CliArgParser.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import scopt.OptionParser

object CliArgParser {

implicit val readPath: scopt.Read[Path] = scopt.Read.reads { Paths.get(_) }
implicit val readPath: scopt.Read[Path] = scopt.Read.reads(Paths.get(_))

val usageExamples: String =
"""|scalafmt # Format all files in the current project, configuration is determined in this order:
Expand Down Expand Up @@ -40,9 +40,8 @@ object CliArgParser {
c
}

private def readConfig(contents: String, c: CliOptions): CliOptions = {
c.copy(configStr = Some(contents))
}
private def readConfig(contents: String, c: CliOptions): CliOptions = c
.copy(configStr = Some(contents))

head("scalafmt", Versions.nightly)
opt[Unit]('h', "help").action(printAndExit(includeUsage = true))
Expand Down Expand Up @@ -114,7 +113,7 @@ object CliArgParser {
s"""|Format files listed in `git diff` against given git ref.
|Deprecated: use --mode diff-ref=<ref> instead""".stripMargin
)
opt[Unit]("build-info").action((_, _) => { println(buildInfo); sys.exit })
opt[Unit]("build-info").action { (_, _) => println(buildInfo); sys.exit }
.text("prints build information")
opt[Unit]("quiet").action((_, c) => c.copy(quiet = true))
.text("don't print out stuff to console.")
Expand Down Expand Up @@ -148,7 +147,7 @@ object CliArgParser {
|build time: ${new Date(Versions.timestamp.toLong)}""".stripMargin

private def writeMode(c: CliOptions, writeMode: WriteMode): CliOptions = c
.writeModeOpt.fold { c.copy(writeModeOpt = Some(writeMode)) } { x =>
.writeModeOpt.fold(c.copy(writeModeOpt = Some(writeMode))) { x =>
if (x != writeMode)
throw new Conflict(s"writeMode changing from $x to $writeMode")
c
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ case class CliOptions(

private[cli] def getProposedConfigFile: Path = canonicalConfigFile
.flatMap(_.toOption)
.getOrElse { gitOps.getProposedConfigFile(cwd, config).path }
.getOrElse(gitOps.getProposedConfigFile(cwd, config).path)

/** Parse the scalafmt configuration and try to encode it to `ScalafmtConfig`.
* If `--config-str` is specified, this will parse the configuration string
Expand Down
6 changes: 2 additions & 4 deletions scalafmt-cli/src/main/scala/org/scalafmt/cli/ExitCode.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,20 @@ object ExitCode {
: ExitCode = generateExitStatus
// format: on
lazy val all: List[ExitCode] = allInternal.toList
private def codeToName(code: Int): String = {
private def codeToName(code: Int): String =
if (code == 0) Ok.name
else {
val names = all
.collect { case exit if (exit.code & code) != 0 => exit.name }
names.mkString("+")
}
}
def apply(code: Int): ExitCode = {
def apply(code: Int): ExitCode =
if (cache.contains(code)) cache.get(code)
else {
val result = new ExitCode(code, codeToName(code)) {}
cache.put(code, result)
result
}
}

def merge(exit1: ExitCode, exit2: ExitCode): ExitCode =
apply(exit1.code | exit2.code)
Expand Down
11 changes: 4 additions & 7 deletions scalafmt-cli/src/main/scala/org/scalafmt/cli/InputMethod.scala
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,9 @@ sealed abstract class InputMethod {
object InputMethod {

object StdinCode {
def apply(assumeFilename: String, inputStream: InputStream): StdinCode = {
def apply(assumeFilename: String, inputStream: InputStream): StdinCode =
StdinCode
.apply(assumeFilename, Source.fromInputStream(inputStream).mkString)
}
}
case class StdinCode(filename: String, input: String) extends InputMethod {
override def path: Path = Paths.get(filename)
Expand Down Expand Up @@ -92,10 +91,8 @@ object InputMethod {
val b = jList(revised, original.isEmpty || noEol(original.last))
val diff = difflib.DiffUtils.diff(a, b)
if (diff.getDeltas.isEmpty) ""
else {
difflib.DiffUtils
.generateUnifiedDiff(s"a$filename", s"b$filename", a, diff, 1)
.iterator().asScala.mkString("\n")
}
else difflib.DiffUtils
.generateUnifiedDiff(s"a$filename", s"b$filename", a, diff, 1).iterator()
.asScala.mkString("\n")
}
}
Loading

0 comments on commit 62270fe

Please sign in to comment.