Skip to content

Commit

Permalink
Formatting: use redundantBraces.oneStatApply
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Dec 27, 2024
1 parent 1d22de8 commit a146125
Show file tree
Hide file tree
Showing 54 changed files with 809 additions and 813 deletions.
4 changes: 4 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ rewrite {
}
redundantBraces {
preset = all
oneStatApply {
parensMaxSpan = 300
bracesMinSpan = 300
}
}
redundantParens {
preset = all
Expand Down
46 changes: 24 additions & 22 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,30 @@ def isCI = System.getenv("CI") != null
def scala212 = "2.12.20"
def scala213 = "2.13.15"

inThisBuild(List(
version ~= { dynVer =>
if (isCI) dynVer else localSnapshotVersion // only for local publishing
},
organization := "org.scalameta",
homepage := Some(url("https://github.com/scalameta/scalafmt")),
licenses :=
List("Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")),
developers := List(Developer(
"olafurpg",
"Ólafur Páll Geirsson",
"[email protected]",
url("https://geirsson.com"),
)),
scalaVersion := scala213,
crossScalaVersions := List(scala213, scala212),
resolvers ++= Resolver.sonatypeOssRepos("releases"),
resolvers ++= Resolver.sonatypeOssRepos("snapshots"),
testFrameworks += new TestFramework("munit.Framework"),
// causes native image issues
dependencyOverrides += "org.jline" % "jline" % "3.28.0",
))
inThisBuild {
List(
version ~= { dynVer =>
if (isCI) dynVer else localSnapshotVersion // only for local publishing
},
organization := "org.scalameta",
homepage := Some(url("https://github.com/scalameta/scalafmt")),
licenses :=
List("Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")),
developers := List(Developer(
"olafurpg",
"Ólafur Páll Geirsson",
"[email protected]",
url("https://geirsson.com"),
)),
scalaVersion := scala213,
crossScalaVersions := List(scala213, scala212),
resolvers ++= Resolver.sonatypeOssRepos("releases"),
resolvers ++= Resolver.sonatypeOssRepos("snapshots"),
testFrameworks += new TestFramework("munit.Framework"),
// causes native image issues
dependencyOverrides += "org.jline" % "jline" % "3.28.0",
)
}

name := "scalafmtRoot"
publish / skip := true
Expand Down
10 changes: 4 additions & 6 deletions project/Dependencies.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@ object Dependencies {
val munitV = "1.0.2"
val mdocV = mdoc.BuildInfo.version

val scalapb = Def.setting {
ExclusionRule(
organization = "com.thesamet.scalapb",
name = s"scalapb-runtime_${scalaBinaryVersion.value}",
)
}
val scalapb = Def.setting(ExclusionRule(
organization = "com.thesamet.scalapb",
name = s"scalapb-runtime_${scalaBinaryVersion.value}",
))

val scalametaTestkit = Def.setting("org.scalameta" %%% "testkit" % scalametaV)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ private[scalafmt] trait CliUtils {

def nailMain(nGContext: NGContext): Unit = {
val workingDirectory = AbsoluteFile
.fromPathIfAbsolute(nGContext.getWorkingDirectory).getOrElse {
.fromPathIfAbsolute(nGContext.getWorkingDirectory).getOrElse(
throw new IllegalStateException(
s"Expected absolute path, " +
s"obtained nGContext.getWorkingDirectory = ${nGContext
.getWorkingDirectory}",
)
}
),
)
val exit = Cli.mainWithOptions(
nGContext.getArgs,
CliOptions.default.copy(common =
Expand Down
22 changes: 10 additions & 12 deletions scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/Cli.scala
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,13 @@ object Cli extends CliUtils {
private type MaybeRunner = Either[String, ScalafmtRunner]

private def findRunner(options: CliOptions): MaybeRunner = options.hoconOpt
.fold[MaybeRunner] {
Left(
s"""|error: missing Scalafmt configuration file.
|Consider creating '${options.getProposedConfigFile}'
|with the following (other parameters may also be required):
|${getProposedConfigVersion(options)}
|""".stripMargin,
)
} {
.fold[MaybeRunner](Left(
s"""|error: missing Scalafmt configuration file.
|Consider creating '${options.getProposedConfigFile}'
|with the following (other parameters may also be required):
|${getProposedConfigVersion(options)}
|""".stripMargin,
)) {
// Run format using
// - `scalafmt-dynamic` if the specified `version` setting doesn't match build version.
// - `scalafmt-core` if the specified `version` setting match with build version
Expand All @@ -101,7 +99,7 @@ object Cli extends CliUtils {
options.common.debug.println(s"Using core runner [$stableVersion]")
Right(ScalafmtCoreRunner)
case Right(v) if isNative =>
Left(
Left {
s"""|error: invalid Scalafmt version.
|
|This Scalafmt installation has version '$stableVersion' and the version configured in '${options
Expand All @@ -113,8 +111,8 @@ object Cli extends CliUtils {
|
|NOTE: this error happens only when running a native Scalafmt binary.
|Scalafmt automatically installs and invokes the correct version of Scalafmt when running on the JVM.
|""".stripMargin,
)
|""".stripMargin
}
case Right(v) =>
options.common.debug.println(s"Using dynamic runner [$v]")
Right(getDynamicRunner())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,11 @@ object CliArgParser {
|""".stripMargin,
)

checkConfig { c =>
checkConfig(c =>
if (c.config.isDefined && c.configStr.isDefined)
failure("may not specify both --config and --config-str")
else success
}
else success,
)
}
def buildInfo =
s"""|build commit: ${Versions.commit}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,10 @@ case class CliOptions(
* @return
* A path to a configuration file
*/
def configPath: Path = tempConfigPath.getOrElse {
def configPath: Path = tempConfigPath.getOrElse(
canonicalConfigFile
.fold(throw new NoSuchFileException("Config file not found"))(_.get)
}
.fold(throw new NoSuchFileException("Config file not found"))(_.get),
)

private[cli] lazy val canonicalConfigFile: Option[Try[Path]] = gitOps
.getCanonicalConfigFile(cwd, config)
Expand All @@ -145,12 +145,9 @@ case class CliOptions(
.fold(Configured.ok(baseConfig))(ScalafmtConfig.fromConf(_, baseConfig))

private[cli] lazy val hoconOpt: Option[ConfParsed] = configStr
.map(ConfParsed.fromString(_)).orElse {
canonicalConfigFile.map(_.fold(
x => new ConfParsed(Configured.exception(x)),
ConfParsed.fromPath(_),
))
}
.map(ConfParsed.fromString(_)).orElse(canonicalConfigFile.map(
_.fold(x => new ConfParsed(Configured.exception(x)), ConfParsed.fromPath(_)),
))

lazy val fileFetchMode: FileFetchMode = mode
.getOrElse(if (isGit) GitFiles else RecursiveSearch)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ object FileFetchMode {
* RecursiveSearch and GitFiles are the fallback used in the absence of other
* options
*/
implicit val read: Read[FileFetchMode] = Read.reads { x =>
implicit val read: Read[FileFetchMode] = Read.reads(x =>
if (x.startsWith(diffRefPrefix))
DiffFiles(x.substring(diffRefPrefix.length).trim)
else availableModesMap
.getOrElse(x, throw new IllegalArgumentException(s"unknown mode: $x"))
}
.getOrElse(x, throw new IllegalArgumentException(s"unknown mode: $x")),
)

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,12 @@ object ScalafmtCoreRunner extends ScalafmtRunner {

val termDisplay = newTermDisplay(options, inputMethods, termDisplayMessage)
val exitCode = new AtomicReference(ExitCode.Ok)
Breaks.breakable {
inputMethods.compatPar.foreach { inputMethod =>
val code = handleFile(inputMethod, options, adjustedScalafmtConf)
exitCode.getAndUpdate(ExitCode.merge(code, _))
if (options.check && !code.isOk) Breaks.break
termDisplay.taskProgress(termDisplayMessage)
}
}
Breaks.breakable(inputMethods.compatPar.foreach { inputMethod =>
val code = handleFile(inputMethod, options, adjustedScalafmtConf)
exitCode.getAndUpdate(ExitCode.merge(code, _))
if (options.check && !code.isOk) Breaks.break
termDisplay.taskProgress(termDisplayMessage)
})
termDisplay.completedTask(termDisplayMessage, exitCode.get.isOk)
termDisplay.stop()
exitCode.get()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,17 @@ object ScalafmtDynamicRunner extends ScalafmtRunner {
val termDisplay = newTermDisplay(options, inputMethods, termDisplayMessage)

val exitCode = new AtomicReference(ExitCode.Ok)
breakable {
inputMethods.compatPar.foreach { inputMethod =>
try {
val code = handleFile(inputMethod, session, options)
exitCode.getAndUpdate(ExitCode.merge(code, _))
} catch {
case e: Error.MisformattedFile =>
reporter.error(e.file, e)
if (options.check) break
}
termDisplay.taskProgress(termDisplayMessage)
breakable(inputMethods.compatPar.foreach { inputMethod =>
try {
val code = handleFile(inputMethod, session, options)
exitCode.getAndUpdate(ExitCode.merge(code, _))
} catch {
case e: Error.MisformattedFile =>
reporter.error(e.file, e)
if (options.check) break
}
}
termDisplay.taskProgress(termDisplayMessage)
})

val exit = ExitCode.merge(exitCode.get, reporter.getExitCode)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,15 @@ object AlignToken {

class Matcher(val owner: Option[jurPattern], val parents: Seq[jurPattern]) {
def matches(tree: meta.Tree): Boolean = owner.forall(check(tree)) &&
(parents.isEmpty || tree.parent.exists { p =>
(parents.isEmpty || tree.parent.exists(p =>
parents.forall(check(p)) ||
(p match {
case ParamClauseParent(pp) => parents.forall(check(pp))
case _: meta.Member.SyntaxValuesClause => p.parent
.exists(pp => parents.forall(check(pp)))
case _ => false
})
})
(p match {
case ParamClauseParent(pp) => parents.forall(check(pp))
case _: meta.Member.SyntaxValuesClause => p.parent
.exists(pp => parents.forall(check(pp)))
case _ => false
}),
))
}

@inline
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,14 +261,12 @@ case class Newlines(
@inline
def keepBreak(implicit ft: FT): Boolean = keepBreak(ft.hasBreak)

val breakAfterInfix: AfterInfix = afterInfix.getOrElse {
source match {
case Newlines.unfold => AfterInfix.many
case Newlines.fold => AfterInfix.some
case Newlines.keep => AfterInfix.keep
case Newlines.classic => AfterInfix.keep
}
}
val breakAfterInfix: AfterInfix = afterInfix.getOrElse(source match {
case Newlines.unfold => AfterInfix.many
case Newlines.fold => AfterInfix.some
case Newlines.keep => AfterInfix.keep
case Newlines.classic => AfterInfix.keep
})
val formatInfix: Boolean = breakAfterInfix ne AfterInfix.keep

def checkInfixConfig(infixCount: Int): Newlines =
Expand Down Expand Up @@ -326,9 +324,9 @@ case class Newlines(
/* minBreaks has to come first; since we'll be adding blanks, this could
* potentially move us into another setting which didn't match before we
* we added the blanks; the rest are sorted to put more specific first */
topLevelStatementBlankLines.filter(x => x.minNest <= x.maxNest).sortBy {
x => (x.minBreaks, x.maxNest, -x.minNest, x.regex.fold(0)(-_.length))
}
topLevelStatementBlankLines.filter(x => x.minNest <= x.maxNest).sortBy(
x => (x.minBreaks, x.maxNest, -x.minNest, x.regex.fold(0)(-_.length)),
)

@inline
def hasTopStatBlankLines = topStatBlankLinesSorted.nonEmpty
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ object ReaderUtil {
ConfError.message(msg)
}
})
val encoder = ConfEncoder.instance[T] { value =>
val encoder = ConfEncoder.instance[T](value =>
options.collectFirst { case sourcecode.Text(`value`, source) =>
Conf.Str(source)
}.getOrElse(Conf.Null())
}
}.getOrElse(Conf.Null()),
)
new ConfCodecEx(encoder, decoder)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,12 @@ case class ScalafmtConfig(

private def getConfigViaLayoutInfoFor(absfile: AbsoluteFile)(
f: (ProjectFiles.Layout, String) => ScalafmtConfig,
): Option[ScalafmtConfig] = project.layout.flatMap { layout =>
): Option[ScalafmtConfig] = project.layout.flatMap(layout =>
layout.getInfo(absfile).map { info =>
val style = f(layout, info.lang)
if (info.isTest) style.forTest else style.forMain
}
}
},
)

def getConfigFor(filename: String): Try[ScalafmtConfig] = {
val absfile = AbsoluteFile(filename)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,11 @@ private class BestFirstSearch private (range: Set[Range])(implicit
}
Some(nextState)
}
memo.get(key).orElse {
memo.get(key).orElse(
if (isOpt) Some(None) // we wouldn't recurse unless the span was large
else if (!start.terminal()) orElse(hadSlb = false)
else slbMemo.get(key).orElse(orElse(hadSlb = true))
}
else slbMemo.get(key).orElse(orElse(hadSlb = true)),
)
}

/** Runs best first search to find lowest penalty split.
Expand Down Expand Up @@ -168,10 +168,10 @@ private class BestFirstSearch private (range: Set[Range])(implicit
} else preFork = false
}

actualSplits.foreach { split =>
actualSplits.foreach(split =>
if (optimalFound) sendEvent(split)
else processNextState(getNext(curr, split))
}
else processNextState(getNext(curr, split)),
)
}
}
}
Expand Down Expand Up @@ -293,12 +293,10 @@ private class BestFirstSearch private (range: Set[Range])(implicit
initStyle.runner.event(FormatEvent.Routes(routes))
val state = {
def run = shortestPath(State.start, Int.MaxValue)
run.getOrElse {
stats.retry.flatMap { x =>
stats = x
run.toOption
}.orNull
}
run.getOrElse(stats.retry.flatMap { x =>
stats = x
run.toOption
}.orNull)
}
if (null != state) {
stats.complete(state)
Expand Down
Loading

0 comments on commit a146125

Please sign in to comment.