-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathSpiewakPlugin.scala
478 lines (379 loc) · 16.3 KB
/
SpiewakPlugin.scala
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/*
* Copyright 2020 Daniel Spiewak
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sbtspiewak
import sbt._, Keys._
import com.typesafe.sbt.GitPlugin
import com.typesafe.sbt.SbtGit.git
import com.typesafe.tools.mima.plugin.MimaPlugin, MimaPlugin.autoImport._
import de.heikoseeberger.sbtheader.AutomateHeaderPlugin
import dotty.tools.sbtplugin.DottyPlugin, DottyPlugin.autoImport._
import _root_.io.crashbox.gpg.SbtGpg
import sbtcrossproject.{CrossPlugin, CrossType}, CrossPlugin.autoImport.crossProjectPlatform
import sbtghactions.{GenerativeKeys, GenerativePlugin, GitHubActionsKeys, GitHubActionsPlugin, WorkflowStep}, GenerativeKeys._, GitHubActionsKeys._
import scala.sys.process._
import scala.util.Try
object SpiewakPlugin extends AutoPlugin {
override def requires =
GitPlugin &&
SbtGpg &&
GitHubActionsPlugin &&
GenerativePlugin &&
MimaPlugin &&
DottyPlugin &&
CrossPlugin &&
plugins.JvmPlugin
override def trigger = allRequirements
object autoImport {
val ReleaseTag = """^v((?:\d+\.){2}\d+(?:-.*)?)$""".r
/**
* https://github.com/djspiewak/sbt-spiewak/versioning/blob/589b9ea/versioning.md
*/
lazy val baseVersion = git.baseVersion
lazy val strictSemVer = settingKey[Boolean]("Set to true to forbid breaking changes in the minor releases (strict semantic versioning; default: true)")
lazy val fatalWarningsInCI = settingKey[Boolean]("Convert compiler warnings into errors under CI builds (default: true)")
lazy val versionIntroduced = settingKey[Map[String, String]]("A map from *binary* scalaVersion -> version (e.g. '2.13') used to indicate that a particular crossScalaVersions value was introduced in a given version (default: empty)")
lazy val publishGithubUser = settingKey[String]("The github username of the main developer")
lazy val publishFullName = settingKey[String]("The full name of the main developer")
lazy val testIfRelevant = taskKey[Unit]("A wrapper around the `test` task which checks to ensure the current scalaVersion is in crossScalaVersions")
lazy val mimaReportBinaryIssuesIfRelevant = taskKey[Unit]("A wrapper around the `test` task which checks to ensure the current scalaVersion is in crossScalaVersions")
lazy val publishIfRelevant = taskKey[Unit]("A wrapper around the `publish` task which checks to ensure the current scalaVersion is in crossScalaVersions")
lazy val publishLocalIfRelevant = taskKey[Unit]("A wrapper around the `publishLocal` task which checks to ensure the current scalaVersion is in crossScalaVersions")
val noPublishSettings = Seq(
publish := {},
publishLocal := {},
publishArtifact := false,
mimaPreviousArtifacts := Set.empty,
skip in publish := true)
val dottyLibrarySettings = Seq(
libraryDependencies :=
libraryDependencies.value map { lib =>
// hack to avoid slapping dotty compat on the SJS dotty lib
if (lib.organization != "ch.epfl.lamp" && lib.name != "dotty_library")
lib.withDottyCompat(scalaVersion.value)
else
lib
})
/**
* Only required if you have Dotty versions prior to 0.27.0-RC1 in your
* crossScalaVersions. This shim will eventually be removed.
*/
def dottyJsSettings(defaultCrossScalaVersions: SettingKey[Seq[String]]) = Seq(
crossScalaVersions := {
val default = defaultCrossScalaVersions.value
if (crossProjectPlatform.value.identifier != "jvm") {
default collect {
case v @ FullScalaVersion(2, _, _, _, _) => v
case v @ FullScalaVersion(3, _, _, _, _) => v
case v @ FullScalaVersion(0, min, _, _, _) if min >= 27 => v
}
} else {
default
}
})
def filterTaskWhereRelevant(delegate: TaskKey[Unit]) =
Def.taskDyn {
val cross = crossScalaVersions.value
val ver = scalaVersion.value
if (cross.contains(ver))
Def.task(delegate.value)
else
Def.task(streams.value.log.warn(s"skipping `${delegate.key.label}` in ${name.value}: $ver is not in $cross"))
}
// why isn't this in sbt itself?
def replaceCommandAlias(name: String, contents: String): Seq[Setting[State => State]] =
Seq(GlobalScope / onLoad ~= { (f: State => State) =>
f andThen { s: State =>
BasicCommands.addAlias(BasicCommands.removeAlias(s, name), name, contents)
}
})
}
import autoImport._
private val DeprecatedReleaseTag = """^v((?:\d+\.)?\d+)$""".r
override def globalSettings = Seq(
fatalWarningsInCI := true,
versionIntroduced := Map(),
crossScalaVersions := Seq("2.13.2"),
Def.derive(scalaVersion := crossScalaVersions.value.last, default = true))
override def buildSettings =
GitPlugin.autoImport.versionWithGit ++
addCommandAlias("ci", "; project /; headerCheck; clean; testIfRelevant; mimaReportBinaryIssuesIfRelevant") ++
addCommandAlias("releaseLocal", "; reload; project /; +publishLocalIfRelevant") ++
Seq(
organizationName := publishFullName.value,
strictSemVer := true,
startYear := Some(2020),
licenses += (("Apache-2.0", url("http://www.apache.org/licenses/"))),
// disable automatic generation of the publication workflow
githubWorkflowPublishTargetBranches := Seq(),
githubWorkflowBuild := Seq(WorkflowStep.Sbt(List("ci"))),
isSnapshot := version.value endsWith "SNAPSHOT",
pomIncludeRepository := { _ => false },
developers += Developer(
publishGithubUser.value,
publishFullName.value,
s"@${publishGithubUser.value}",
url(s"https://github.com/${publishGithubUser.value}")),
git.gitTagToVersionNumber := {
val log = sLog.value
{
case ReleaseTag(version) =>
Some(version)
case DeprecatedReleaseTag(version) =>
log.warn(s"ignoring non-semver-compliant version: $version")
None
case _ =>
None
}
},
git.formattedShaVersion := {
val suffix = git.makeUncommittedSignifierSuffix(git.gitUncommittedChanges.value, git.uncommittedSignifier.value)
git.gitHeadCommit.value map { _.substring(0, 7) } map { sha =>
git.baseVersion.value + "-" + sha + suffix
}
},
git.gitUncommittedChanges := Try("git status -s".!!.trim.length > 0).getOrElse(true),
git.gitHeadCommit := Try("git rev-parse HEAD".!!.trim).toOption,
git.gitCurrentTags := Try("git tag --contains HEAD".!!.trim.split("\\s+").toList).toOption.toList.flatten)
override def projectSettings =
AutomateHeaderPlugin.projectSettings ++
Seq(
Test / testIfRelevant := filterTaskWhereRelevant(Test / test).value,
mimaReportBinaryIssuesIfRelevant := filterTaskWhereRelevant(mimaReportBinaryIssues).value,
publishIfRelevant := filterTaskWhereRelevant(publish).value,
publishLocalIfRelevant := filterTaskWhereRelevant(publishLocal).value,
libraryDependencies ++= {
if (isDotty.value)
Nil
else
Seq(compilerPlugin("org.typelevel" % "kind-projector" % "0.11.0" cross CrossVersion.full))
},
// Adapted from Rob Norris' post at https://tpolecat.github.io/2014/04/11/scalac-flags.html
scalacOptions ++= Seq(
"-deprecation",
"-encoding", "UTF-8", // yes, this is 2 args
"-feature",
"-unchecked"),
scalacOptions ++= {
scalaVersion.value match {
case FullScalaVersion(2, minor, _, _, _) if minor < 13 =>
Seq("-Yno-adapted-args", "-Ywarn-unused-import")
case _ =>
Seq.empty
}
},
scalacOptions ++= {
if (githubIsWorkflowBuild.value && !isDotty.value && fatalWarningsInCI.value)
Seq("-Xfatal-warnings")
else
Seq.empty
},
scalacOptions ++= {
val warningsNsc = Seq("-Xlint", "-Ywarn-dead-code")
val warnings211 = Seq(
"-Ywarn-numeric-widen") // In 2.10 this produces a some strange spurious error
val warnings212 = Seq("-Xlint:-unused,_")
val removed213 = Set("-Xlint:-unused,_", "-Xlint")
val warnings213 = Seq(
"-Xlint:deprecation",
"-Wunused:nowarn",
"-Wdead-code",
"-Wextra-implicit",
"-Wnumeric-widen",
"-Wunused:implicits",
"-Wunused:explicits",
"-Wunused:imports",
"-Wunused:locals",
"-Wunused:params",
"-Wunused:patvars",
"-Wunused:privates",
"-Wvalue-discard")
val warningsDotty = Seq()
scalaVersion.value match {
case FullScalaVersion(0, minor, _, _, _) if minor >= 24 =>
warningsDotty
case FullScalaVersion(3, _, _, _, _) =>
warningsDotty
case FullScalaVersion(2, minor, _, _, _) if minor >= 13 =>
(warnings211 ++ warnings212 ++ warnings213 ++ warningsNsc).filterNot(removed213)
case FullScalaVersion(2, minor, _, _, _) if minor >= 12 =>
warnings211 ++ warnings212 ++ warningsNsc
case FullScalaVersion(2, minor, _, _, _) if minor >= 11 =>
warnings211 ++ warningsNsc
case _ => Seq.empty
}
},
scalacOptions ++= {
scalaVersion.value match {
case FullScalaVersion(2, 12, _, _, _) =>
Seq("-Ypartial-unification")
case FullScalaVersion(2, 11, build, _, _) if build >= 11 =>
Seq("-Ypartial-unification")
case FullScalaVersion(2, 13, 0, MRC.Milestone(milestone), qualifier) if milestone < 4 || (milestone == 4 && qualifier.isDefined) =>
Seq("-Ypartial-unification")
case _ =>
Seq.empty
}
},
scalacOptions ++= {
val numCPUs = java.lang.Runtime.getRuntime.availableProcessors()
val settings = Seq(s"-Ybackend-parallelism", numCPUs.toString)
scalaVersion.value match {
case FullScalaVersion(2, 12, build, _, _) if build >= 5 =>
settings
// setting was introduced in 2.13.0-M4 (final)
case FullScalaVersion(2, 13, 0, MRC.Milestone(milestone), qualifier) if milestone > 4 || (milestone == 4 && !qualifier.isDefined) =>
settings
case FullScalaVersion(2, 13, _, _, _) =>
settings
case _ =>
Seq.empty
}
},
scalacOptions ++= {
if (isDotty.value)
Seq("-language:implicitConversions", "-Ykind-projector", "-source:3.0-migration")
else
Seq("-language:_")
},
Test / scalacOptions ++= {
if (isDotty.value)
Seq()
else
Seq("-Yrangepos")
},
Compile / console / scalacOptions --= Seq(
"-Xlint",
"-Ywarn-unused-import",
"-Wextra-implicit",
"-Wunused:implicits",
"-Wunused:explicits",
"-Wunused:imports",
"-Wunused:locals",
"-Wunused:params",
"-Wunused:patvars",
"-Wunused:privates"),
Test / console / scalacOptions := (scalacOptions in (Compile, console)).value,
Compile / doc / scalacOptions ++= {
val isSnapshot = git.gitCurrentTags.value.map(git.gitTagToVersionNumber.value).flatten.isEmpty
val versionOrHash =
if (!isSnapshot)
Some(s"v${version.value}")
else
git.gitHeadCommit.value
val infoOpt = scmInfo.value
versionOrHash.toSeq flatMap { vh =>
infoOpt.toSeq flatMap { info =>
val path = s"${info.browseUrl}/blob/$vh€{FILE_PATH}.scala"
Seq("-doc-source-url", path, "-sourcepath", (LocalRootProject / baseDirectory).value.getAbsolutePath)
}
}
},
scalacOptions ++= {
// Dotty doesn't understand -P for the moment (lampepfl/dotty#9783)
if (!isDotty.value && crossProjectPlatform.?.value.map(_.identifier == "js").getOrElse(false)) {
val hasVersion = git.gitCurrentTags.value.map(git.gitTagToVersionNumber.value).flatten.nonEmpty
val versionOrHash =
if (hasVersion)
Some(s"v${version.value}")
else
git.gitHeadCommit.value
val l = (LocalRootProject / baseDirectory).value.toURI.toString
val infoOpt = scmInfo.value
versionOrHash flatMap { v =>
infoOpt map { info =>
val g = s"${info.browseUrl.toString.replace("github.com", "raw.githubusercontent.com")}/$v/"
s"-P:scalajs:mapSourceURI:$l->$g"
}
}
} else {
None
}
},
libraryDependencies ++= {
scalaVersion.value match {
case FullScalaVersion(2, 10, build, _, _) if build >= 6 =>
Seq(compilerPlugin("com.milessabin" % "si2712fix-plugin" % "1.2.0" cross CrossVersion.full))
case FullScalaVersion(2, 11, 8, _, _) =>
Seq(compilerPlugin("com.milessabin" % "si2712fix-plugin" % "1.2.0" cross CrossVersion.full))
case _ =>
Seq.empty
}
},
mimaPreviousArtifacts := {
val current = version.value
val org = organization.value
val n = name.value
val TagBase = """^(\d+)\.(\d+).*"""r
val TagBase(major, minor) = baseVersion.value
val isPre = major.toInt == 0
if (sbtPlugin.value || !crossProjectPlatform.?.value.map(_.identifier == "jvm").getOrElse(true)) {
Set.empty
} else {
val tags = Try("git tag --list".!!.split("\n").map(_.trim)).getOrElse(new Array[String](0))
// in semver, we allow breakage in minor releases if major is 0, otherwise not
val Pattern = if (isPre || !strictSemVer.value)
s"^v($major\\.$minor\\.\\d+)$$".r
else
s"^v($major\\.\\d+\\.\\d+)$$".r
val versions = tags collect {
case Pattern(version) => version
}
val notCurrent = versions.filterNot(current ==)
val FullVersion = """^(\d+)\.(\d+)\.(\d+)$""".r
val reduced = versionIntroduced.value.get(CrossVersion.binaryScalaVersion(scalaVersion.value)) match {
case Some(FullVersion(boundMaj, boundMin, boundRev)) =>
// we assume you don't want more than 1000 versions per component
val boundOrd = boundMaj.toInt * 1000 * 1000 + boundMin.toInt * 1000 + boundRev.toInt * 1000
notCurrent filter {
case FullVersion(maj, min, rev) =>
(maj.toInt * 1000 * 1000 + min.toInt * 1000 + rev.toInt * 1000) >= boundOrd
}
case None =>
notCurrent
}
reduced.map(v => org % s"${n}_${CrossVersion.binaryScalaVersion(scalaVersion.value)}" % v).toSet
}
},
pomPostProcess := { node =>
import scala.xml._
import scala.xml.transform._
def stripIf(f: Node => Boolean) =
new RewriteRule {
override def transform(n: Node) =
if (f(n)) NodeSeq.Empty else n
}
val stripTestScope = stripIf(n => n.label == "dependency" && (n \ "scope").text == "test")
new RuleTransformer(stripTestScope).transform(node)(0)
},
Compile / unmanagedSourceDirectories ++= {
val major = if (isDotty.value) "-3" else "-2"
List(CrossType.Pure, CrossType.Full).flatMap(
_.sharedSrcDir(baseDirectory.value, "main").toList.map(f => file(f.getPath + major)))
},
Test / unmanagedSourceDirectories ++= {
val major = if (isDotty.value) "-3" else "-2"
List(CrossType.Pure, CrossType.Full).flatMap(
_.sharedSrcDir(baseDirectory.value, "test").toList.map(f => file(f.getPath + major)))
},
// dottydoc really doesn't work at all right now
Compile / doc / sources := {
val old = (Compile / doc / sources).value
if (isDotty.value)
Seq()
else
old
})
}