summaryrefslogtreecommitdiff
path: root/integration/test/resources/play-json/reformat.sc
blob: c44b2f97dbfb6ea7357e85d3d1823a9a0da92048 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import $ivy.`org.scalariform::scalariform:0.2.5`

import mill._, scalalib._
import ammonite.ops._
import scalariform.formatter._
import scalariform.formatter.preferences._
import scalariform.parser.ScalaParserException

trait Scalariform extends ScalaModule {
  val playJsonPreferences = FormattingPreferences()
    .setPreference(SpacesAroundMultiImports, true)
    .setPreference(SpaceInsideParentheses, false)
    .setPreference(DanglingCloseParenthesis, Preserve)
    .setPreference(PreserveSpaceBeforeArguments, true)
    .setPreference(DoubleIndentConstructorArguments, false)

  def compile = T {
    reformat()
    super.compile()
  }

  def reformat = T {
    val files = filesToFormat(sources())
    T.ctx.log.info(s"Formatting ${files.size} Scala sources")
    files.map { path =>
      try {
        val formatted = ScalaFormatter.format(
          read(path),
          playJsonPreferences,
          scalaVersion = scalaVersion()
        )
        write.over(path, formatted)
      } catch {
        case ex: ScalaParserException =>
          T.ctx.log.error(s"Failed to format file: ${path}. Error: ${ex.getMessage}")
      }
      path
    }
  }

  def checkCodeFormat() = T.command {
    filesToFormat(sources()).foreach { path =>
      try {
        val input = read(path)
        val formatted = ScalaFormatter.format(
          input,
          playJsonPreferences,
          scalaVersion = scalaVersion()
        )
        if (input != formatted) sys.error(
          s"""
             |ERROR: Scalariform check failed at file: ${path}
             |To fix, format your sources using `mill __.reformat` before submitting a pull request.
             |Additionally, please squash your commits (eg, use git commit --amend) if you're going to update this pull request.
          """.stripMargin
        )
      } catch {
        case ex: ScalaParserException =>
          T.ctx.log.error(s"Failed to format file: ${path}. Error: ${ex.getMessage}")
      }
    }
  }

  private def filesToFormat(sources: Seq[PathRef]) = {
    for {
      pathRef <- sources if exists(pathRef.path)
      file <- ls.rec(pathRef.path) if file.isFile && file.ext == "scala"
    } yield file
  }

}