SBT Formatter Plugin Using Common Config File

80 Views Asked by At

I have the following piece of code:

package my.package

import sbt._
import Keys._

object OpenElectronsScalaFmtPlugin extends AutoPlugin {
  override def trigger = allRequirements
  override def requires = plugins.JvmPlugin
  override def buildSettings: Seq[Def.Setting[_]] = {
    SettingKey[Unit]("scalafmtGenerateConfig") :=
      IO.write(
        // writes to file once when build is loaded
        file(".scalafmt-common.conf"),
        ("version = 3.6.1\n" +
          "runner.dialect = scala213source3\n\n" +
          "project.git = true\n" +
          "preset = default\n\n" +
          "align.preset = none\n" +
          "align.tokens = [\n" +
          "  {code = \"<-\"},\n" +
          "]\n\n" +
          "docstrings.style = keep\n" +
          "maxColumn = 120\n\n"
          ).stripMargin.getBytes("UTF-8")
      )
  }
}

As you can see, I'm appending the entries one by one which I find tedious. My IDE is not helping me to look into the IO.write function where I want to know what the parameters are so that I can pass in a .scalafmt-common.conf as a file instead of individual elements. Any ideas?

1

There are 1 best solutions below

0
On BEST ANSWER

Here is what I came up with:

val commonScalaFormatConfig: String =
    """
      |version = 3.6.1
      |runner.dialect = scala213source3
      |
      |project.git = true
      |preset = default
      |
      |align.preset = none
      |align.tokens = [
      |  {code = "<-"},
      |]
      |
      |docstrings.style = keep
      |maxColumn = 120
      |
      |rewrite.rules = [
      |  SortImports,
      |  AvoidInfix,
      |]
      |
      |spaces.inImportCurlyBraces = true
      |includeNoParensInSelectChains = false
      |trailingCommas = preserve
      |
      |continuationIndent {
      |  callSite = 2
      |  defnSite = 2
      |  extendSite = 2
      |}
      |
      |optIn {
      |  forceBlankLineBeforeDocstring = false
      |}
      |
      |newlines {
      |  source = keep
      |  afterCurlyLambdaParams = preserve
      |  beforeCurlyLambdaParams = multilineWithCaseOnly
      |  topLevelBodyIfMinStatements = []
      |}
      |""".stripMargin

  override def trigger = allRequirements
  override def requires = plugins.JvmPlugin
  override def buildSettings: Seq[Def.Setting[_]] = {
    SettingKey[Unit]("scalafmtGenerateConfig") :=
      IO.write(
        // writes to file once when build is loaded
        file(".scalafmt-common.conf"), commonScalaFormatConfig.stripMargin.getBytes("UTF-8")
      )
  }

Not quite what I expected, but atleast one step better than my original version.

The other approach would be to place the conf file in a certain location and use IO.copyFromFile(..., ...) to read it from there.