Search code examples
scalascalafmt

Reuse Scalafmt Config File Across Projects


I have a set of Scala projects and for all of those projects, I would like to introduce some scala source code formatting for which purpose, I'm using the scamafmt sbt pliugin. I have compiled the config file and this config file is in a separate project repo. I would now like to reuse this in all of the other Scala projects. I see two possibilities:

  1. Use the repo where the conf file is located as a git submodule in all the other 10 projects where I want to run the scala formatter

  2. Do not do anything, just add a README documentation that every user who is working on the codebase should download the scalafmt conf file to the project (I will pre add a .gitignore to all projects to ignore the local conf file)

Is there any other approach? I definitely do not want the conf file to diverge if I leave it as is in all the projects.


Solution

  • As per the documentation, one option is to build (and publish in your org) a SBT plugin with your configuration:

    https://scalameta.org/scalafmt/docs/installation.html#share-configuration-between-builds

    To share configuration across different sbt builds, create a custom sbt plugin that generates .scalafmt-common.conf on build reload, then include the generated file from .scalafmt.conf

    // project/MyScalafmtPlugin.scala
    import sbt._
    object MyScalafmtPlugin 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"),
            "maxColumn = 100".stripMargin.getBytes("UTF-8")
          )
      }
    }
    
    // .scalafmt.conf
    include ".scalafmt-common.conf"