Skip to content

Instantly share code, notes, and snippets.

@pbassiner
Last active April 30, 2017 15:58
Show Gist options
  • Select an option

  • Save pbassiner/2c861acd606d4e2f4b7ae9953cfe666d to your computer and use it in GitHub Desktop.

Select an option

Save pbassiner/2c861acd606d4e2f4b7ae9953cfe666d to your computer and use it in GitHub Desktop.
Automate Scalafmt Plugin
import org.scalafmt.bootstrap.ScalafmtBootstrap
import org.scalafmt.sbt.ScalafmtPlugin
import sbt._
import sbt.Keys._
import sbt.inc.Analysis
object AutomateScalafmtPlugin extends AutoPlugin {
object autoImport {
def automateScalafmtFor(configurations: Configuration*): Seq[Setting[_]] =
configurations.flatMap { c =>
inConfig(c)(
Seq(
compileInputs.in(compile) := {
scalafmtInc.value
compileInputs.in(compile).value
},
sourceDirectories.in(scalafmtInc) := Seq(scalaSource.value),
scalafmtInc := {
val cache = streams.value.cacheDirectory / "scalafmt"
val include = includeFilter.in(scalafmtInc).value
val exclude = excludeFilter.in(scalafmtInc).value
val sources =
sourceDirectories
.in(scalafmtInc)
.value
.descendantsExcept(include, exclude)
.get
.toSet
def format(handler: Set[File] => Unit, msg: String) = {
def update(handler: Set[File] => Unit, msg: String)(
in: ChangeReport[File], out: ChangeReport[File]) = {
val label = Reference.display(thisProjectRef.value)
val files = in.modified -- in.removed
Analysis
.counted("Scala source", "", "s", files.size)
.foreach(count => streams.value.log.info(s"$msg $count in $label ..."))
handler(files)
files
}
FileFunction.cached(cache)(FilesInfo.hash,
FilesInfo.exists)(update(handler, msg))(sources)
}
def formattingHandler(files: Set[File]) =
if (files.nonEmpty) {
val filesArg = files.map(_.getAbsolutePath).mkString(",")
scalafmt.foreach(_.cli.main(Array("--non-interactive", "-i", "-f", filesArg)))
}
format(formattingHandler, "Formatting")
format(_ => (), "Reformatted") // Recalculate the cache
}
)
)
}
}
val scalafmt: Option[ScalafmtBootstrap] = {
val either = ScalafmtBootstrap.fromVersion("0.6.3")
either.left.foreach(_.printStackTrace())
either.right.toOption
}
private val scalafmtInc = taskKey[Unit]("Incrementally format modified sources")
override def requires = ScalafmtPlugin
override def trigger = allRequirements
override def projectSettings =
(includeFilter.in(scalafmtInc) := "*.scala") +: autoImport.automateScalafmtFor(Compile, Test)
}
addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "0.6.3")
# must rename to .scalafmt.conf
style = defaultWithAlign
align.tokens = [off]
danglingParentheses = true
docstrings = JavaDoc
indentOperator = spray
maxColumn = 120
rewrite.rules = [RedundantBraces, RedundantParens, SortImports]
unindentTopLevelOperators = true
binPack.callSite = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment