aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/com.drivergrp.sbt/SbtSettings.scala
blob: e633e64ada05b038da5c72851676945feb07b386 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package com.drivergrp.sbt

import sbt._
import sbt.Keys._

import java.io.File
import com.typesafe.sbt.SbtGit.git
import com.typesafe.sbt.SbtNativePackager.Universal
import com.typesafe.sbt.packager.SettingsHelper._
import com.typesafe.sbt.packager.archetypes.JavaServerAppPackaging
import com.typesafe.sbt.{GitBranchPrompt, GitVersioning}
import org.scalafmt.sbt.ScalaFmtPlugin.autoImport._
import org.scalastyle.sbt.ScalastylePlugin._
import sbt.{Project, Resolver, State, _}
import sbtassembly.AssemblyKeys._
import sbtassembly._
import sbtbuildinfo.BuildInfoPlugin
import sbtbuildinfo.BuildInfoPlugin.autoImport.{BuildInfoKey, BuildInfoOption, _}
import sbtdocker.DockerPlugin
import sbtrelease.{Version, _}
import wartremover.WartRemover.autoImport._
// we hide the existing definition for setReleaseVersion to replace it with our own
import sbtrelease.ReleasePlugin.autoImport.ReleaseTransformations._
import sbtrelease.ReleasePlugin.autoImport._
import sbtrelease.ReleaseStateTransformations.{setReleaseVersion => _}


/**
  * @see https://engineering.sharethrough.com/blog/2015/09/23/capturing-common-config-with-an-sbt-parent-plugin/
  */
object SbtSettings extends AutoPlugin {

  object autoImport {

    lazy val testAll = TaskKey[Unit]("test-all", "Launches all unit and integration tests")

    lazy val releaseSettings = {
      def setVersionOnly(selectVersion: Versions => String): ReleaseStep = { st: State =>
        val vs = st.get(ReleaseKeys.versions).getOrElse(
          sys.error("No versions are set! Was this release part executed before inquireVersions?"))
        val selected = selectVersion(vs)

        st.log.info("Setting version to '%s'." format selected)
        val useGlobal = Project.extract(st).get(releaseUseGlobalVersion)

        reapply(Seq(
          if (useGlobal) version in ThisBuild := selected else version := selected
        ), st)
      }

      lazy val setReleaseVersion: ReleaseStep = setVersionOnly(_._1)

      Seq(
        releaseIgnoreUntrackedFiles := true,
        // Check http://blog.byjean.eu/2015/07/10/painless-release-with-sbt.html for details
        releaseVersionBump := sbtrelease.Version.Bump.Minor,
        releaseVersion <<= releaseVersionBump(bumper => {
          ver => Version(ver)
            .map(_.withoutQualifier)
            .map(_.bump(bumper).string).getOrElse(versionFormatError)
        }),
        releaseProcess := Seq[ReleaseStep](
          checkSnapshotDependencies,
          inquireVersions,
          runTest, // probably, runTest after setReleaseVersion, if tests depend on version
          setReleaseVersion,
          commitReleaseVersion, // performs the initial git checks
          tagRelease,
          publishArtifacts,
          setNextVersion,
          commitNextVersion,
          pushChanges // also checks that an upstream branch is properly configured
        )
      )
    }

    lazy val publicationSettings = Seq(
      publishTo := Some(Resolver.file("file", new File("releases")))

      // publishTo := { // TODO: For actual Driver jar repo
      //   val nexus = "https://my.artifact.repo.net/"
      //   if (isSnapshot.value)
      //     Some("snapshots" at nexus + "content/repositories/snapshots")
      //   else
      //     Some("releases"  at nexus + "service/local/staging/deploy/maven2")
      // }

      // publishTo <<= (version, sbtPlugin) { (v: String, isPlugin: Boolean) =>
      //   val root = "http://artifacts.example.com/sharethrough"
      //   val layout = if (isPlugin) Resolver.ivyStylePatterns else Resolver.mavenStylePatterns
      //   val status = if (v.trim.endsWith("SNAPSHOT")) "snapshot" else "release"
      //   val repository = s"libs-${status}s-local"
      //
      //   Some(Resolver.url(repository, new URL(s"$root/$repository/"))(layout))
      // }
    )

    lazy val acyclicSettings = Seq(
      autoCompilerPlugins := true,
      addCompilerPlugin("com.lihaoyi" %% "acyclic" % "0.1.4"))


    implicit class driverConfigurations(project: Project) {

      def gitPluginConfiguration: Project = {
        val VersionRegex = "v([0-9]+.[0-9]+.[0-9]+)-?(.*)?".r

        project
          .enablePlugins(GitVersioning, GitBranchPrompt)
          .settings(
            git.useGitDescribe := true,
            git.baseVersion := "0.0.0",
            git.gitTagToVersionNumber := {
              case VersionRegex(v, "SNAPSHOT") => Some(s"$ v-SNAPSHOT")
              case VersionRegex(v, "") => Some(v)
              case VersionRegex(v, s) => Some(s"$v-$s-SNAPSHOT")
              case _ => None
            })
      }

      def buildInfoConfiguration: Project = {
        project
          .enablePlugins(BuildInfoPlugin)
          .settings(
            buildInfoKeys := Seq[BuildInfoKey](
              name, version, scalaVersion, sbtVersion, buildInfoBuildNumber, git.gitHeadCommit),
            buildInfoPackage := "com.drivergrp",
            buildInfoOptions += BuildInfoOption.BuildTime)
      }

      def integrationTestingConfiguration: Project = {
        project
          .configs(IntegrationTest)
          .settings(Defaults.itSettings ++ Seq(
            testAll <<= (test in IntegrationTest).dependsOn(test in Test)
          ))
      }

      def packagingConfiguration: Project = {
        project
          .enablePlugins(JavaServerAppPackaging)
          .settings(// for sbt-native-packager
            makeDeploymentSettings(Universal, packageBin in Universal, "zip")
          )
          .settings(// for assembly plugin
            test in assembly := {},
            assemblyMergeStrategy in assembly := {
              case PathList("org", "slf4j", "impl", xs@_*) => MergeStrategy.rename
              case "logback.xml" => MergeStrategy.first
              case strategy: String =>
                val oldStrategy = (assemblyMergeStrategy in assembly).value
                oldStrategy(strategy)
            })
      }

      def dockerConfiguration: Project = {
        project
          .enablePlugins(DockerPlugin)
        // .settings(
        //   aggregate in Docker := false, // when building Docker image, don't build images for sub-projects
        //   maintainer in Linux := "XXX",
        //   dockerExposedPorts in Docker := Seq(9000, 9443),
        //   dockerRepository := Some("localhost:5000"),
        //   dockerCommands ++= Seq(
        //     ExecCmd("VOLUME", "/var/www/uploads")
        //   )
        // )

        // And then you can run "sbt docker:publishLocal"
      }
    }
  }

  // Make our own settings and commands readily available for the reset of the file

  lazy val compileScalastyle = taskKey[Unit]("compileScalastyle")

  lazy val wartRemoverSettings = Seq(
    wartremoverErrors in (Compile, compile) ++= Warts.allBut(
      Wart.AsInstanceOf, Wart.Nothing, Wart.Overloading, Wart.DefaultArguments, Wart.Any,
      Wart.Option2Iterable, Wart.ExplicitImplicitTypes, Wart.Throw, Wart.ToString, Wart.NoNeedForMonad))

  lazy val scalafmtSettings = Seq(
    scalafmtConfig in ThisBuild := Some(file(".scalafmt")),
    testExecution in (Test, test) <<=
      (testExecution in (Test, test)) dependsOn (scalafmtTest in Compile, scalafmtTest in Test))

  override def trigger: PluginTrigger = allRequirements
  override def projectSettings: Seq[Setting[_]] = Defaults.coreDefaultSettings ++ Seq (
    organization := "com.drivergrp",
    scalaVersion := "2.11.8",

    scalacOptions ++= Seq(
      "-unchecked",
      "-deprecation",
      "-feature",
      "-Xlint",
      "-encoding",
      "utf8",
      "-language:higherKinds",
      "-language:implicitConversions",
      "-language:postfixOps",
      "-Ywarn-infer-any",
      "-Ywarn-dead-code",
      "-Ywarn-unused",
      "-Ywarn-unused-import"
    ),

    libraryDependencies ++= Seq(
      "org.scalaz"     %% "scalaz-core"    % "7.2.4",
      "com.lihaoyi"    %% "acyclic"        % "0.1.4" % "provided"
    ),

    fork in run := true,
    compileScalastyle := (scalastyle in Compile).toTask("").value,
    (compile in Compile) <<= ((compile in Compile) dependsOn compileScalastyle)
  ) ++ wartRemoverSettings ++ scalafmtSettings
}