forked from scala-cli/scala-js-cli
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbuild.mill.scala
More file actions
452 lines (390 loc) · 14.4 KB
/
build.mill.scala
File metadata and controls
452 lines (390 loc) · 14.4 KB
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
//| mvnDeps:
//| - io.github.alexarchambault.mill::mill-native-image::0.2.3
//| - io.github.alexarchambault.mill::mill-native-image-upload:0.2.3
//| - com.goyeau::mill-scalafix::0.6.0
//| - com.lumidion::sonatype-central-client-requests:0.6.0
//| - io.get-coursier:coursier-launcher_2.13:2.1.25-M19
package build
import io.github.alexarchambault.millnativeimage.NativeImage
import io.github.alexarchambault.millnativeimage.upload.Upload
import mill.*
import mill.api.{BuildCtx, Task}
import mill.javalib.testrunner.TestResult
import mill.scalalib.*
import mill.util.{Tasks, VcsVersion}
import scala.annotation.unused
import scala.concurrent.duration.*
import scala.util.Properties.isWin
import com.goyeau.mill.scalafix.ScalafixModule
import com.lumidion.sonatype.central.client.core.{PublishingType, SonatypeCredentials}
object Versions {
def scala213 = "2.13.18"
def scalaJsVersion = "1.21.0"
def jsoniterVersion = "2.38.9"
def scalaJsImportMapVersion = "0.1.1"
def graalVmVersion = "22.3.1"
def munitVersion = "1.3.0"
def osLibVersion = "0.11.8"
def pprintVersion = "0.9.6"
def coursierVersion = "2.1.25-M19"
def scoptVersion = "4.1.0"
def ubuntuVersion = "24.04"
}
trait ScalaJsCliModule extends ScalaModule with ScalafixModule {
override def scalacOptions: T[Seq[String]] =
super.scalacOptions() ++ Seq("-Wunused", "-deprecation")
def scalaVersion: T[String] = Versions.scala213
}
object cli extends Cli
trait Cli extends ScalaJsCliModule with ScalaJsCliPublishModule {
def artifactName: T[String] = "scalajs" + super.artifactName()
def mvnDeps: T[Seq[Dep]] = super.mvnDeps() ++ Seq(
mvn"org.scala-js::scalajs-linker:${Versions.scalaJsVersion}",
mvn"com.github.scopt::scopt:${Versions.scoptVersion}",
mvn"com.lihaoyi::os-lib:${Versions.osLibVersion}",
mvn"com.github.plokhotnyuk.jsoniter-scala::jsoniter-scala-core:${Versions.jsoniterVersion}", // This is the java8 version of jsoniter, according to scala-cli build
mvn"com.github.plokhotnyuk.jsoniter-scala::jsoniter-scala-macros:${Versions.jsoniterVersion}", // This is the java8 version of jsoniter, according to scala-cli build
mvn"com.armanbilge::scalajs-importmap:${Versions.scalaJsImportMapVersion}"
)
def mainClass: T[Option[String]] = Some("org.scalajs.cli.Scalajsld")
def transitiveJars: T[Seq[PathRef]] = Task {
Task.traverse(transitiveModuleDeps)(_.jar)()
}
def jarClassPath: T[Seq[PathRef]] = Task {
val cp = runClasspath() ++ transitiveJars()
cp.filter(ref => os.exists(ref.path) && !os.isDir(ref.path))
}
def standaloneLauncher: T[PathRef] = Task {
val cachePath = os.Path(coursier.cache.FileCache().location, BuildCtx.workspaceRoot)
def urlOf(path: os.Path): Option[String] =
if path.startsWith(cachePath) then {
val segments = path.relativeTo(cachePath).segments
val url = segments.head + "://" + segments.tail.mkString("/")
Some(url)
}
else None
import coursier.launcher.{
BootstrapGenerator,
ClassPathEntry,
Parameters,
Preamble
}
val cp = jarClassPath().map(_.path)
val mainClass0 = mainClass().getOrElse(sys.error("No main class"))
val dest = Task.ctx().dest / (if isWin then "launcher.bat" else "launcher")
val preamble = Preamble()
.withOsKind(isWin)
.callsItself(isWin)
val entries = cp.map { path =>
urlOf(path) match {
case None =>
val content = os.read.bytes(path)
val name = path.last
ClassPathEntry.Resource(name, os.mtime(path), content)
case Some(url) => ClassPathEntry.Url(url)
}
}
val loaderContent = coursier.launcher.ClassLoaderContent(entries)
val params = Parameters.Bootstrap(Seq(loaderContent), mainClass0)
.withDeterministic(true)
.withPreamble(preamble)
BootstrapGenerator.generate(params, dest.toNIO)
PathRef(dest)
}
}
trait ScalaJsCliNativeImage extends ScalaJsCliModule with NativeImage {
override def generateNativeImageWithFileSystemChecker: Boolean = false
def nativeImageClassPath: T[Seq[PathRef]] = Task {
runClasspath()
}
def nativeImageOptions: T[Seq[String]] = Task {
super.nativeImageOptions() ++ Seq(
"--no-fallback",
"-H:IncludeResources=org/scalajs/linker/backend/emitter/.*.sjsir",
"-H:IncludeResources=com/google/javascript/jscomp/js/polyfills.txt",
"-H:IncludeResourceBundles=com.google.javascript.jscomp.parsing.ParserConfig"
)
}
def nativeImagePersist: Boolean = System.getenv("CI") != null
def graalVmVersion: String = Versions.graalVmVersion
def nativeImageGraalVmJvmId: T[String] = s"graalvm-java17:$graalVmVersion"
def nativeImageName: T[String] = "scala-js-ld"
def moduleDeps: Seq[JavaModule] = Seq(cli)
def compileMvnDeps: T[Seq[Dep]] =
super.compileMvnDeps() ++ Seq(mvn"org.graalvm.nativeimage:svm:$graalVmVersion")
def nativeImageMainClass: T[String] = "org.scalajs.cli.Scalajsld"
def nameSuffix = ""
@unused
def copyToArtifacts(directory: String = "artifacts/"): Command[Unit] = Task.Command {
val _ = Upload.copyLauncher0(
nativeLauncher = nativeImage().path,
directory = directory,
name = "scala-js-ld",
compress = true,
workspace = BuildCtx.workspaceRoot,
suffix = nameSuffix
)
}
}
object native extends ScalaJsCliNativeImage
def native0: native.type = native
def csVersion: String = Versions.coursierVersion
trait ScalaJsCliStaticNativeImage extends ScalaJsCliNativeImage {
def nameSuffix = "-static"
def buildHelperImage: T[Unit] = Task {
os.proc("docker", "build", "-t", "scala-cli-base-musl:latest", ".")
.call(cwd = BuildCtx.workspaceRoot / "musl-image", stdout = os.Inherit)
()
}
def nativeImageDockerParams: T[Option[NativeImage.DockerParams]] = Task {
buildHelperImage()
Some(
NativeImage.linuxStaticParams(
dockerImage = "scala-cli-base-musl:latest",
csUrl =
s"https://github.com/coursier/coursier/releases/download/v$csVersion/cs-x86_64-pc-linux.gz"
)
)
}
def writeNativeImageScript(scriptDest: String, imageDest: String = ""): Command[Unit] =
Task.Command {
buildHelperImage()
super.writeNativeImageScript(scriptDest, imageDest)()
}
}
object `native-static` extends ScalaJsCliStaticNativeImage
trait ScalaJsCliMostlyStaticNativeImage extends ScalaJsCliNativeImage {
def nameSuffix = "-mostly-static"
def nativeImageDockerParams: T[Option[NativeImage.DockerParams]] = Some(
NativeImage.linuxMostlyStaticParams(
dockerImage = s"ubuntu:${Versions.ubuntuVersion}",
csUrl =
s"https://github.com/coursier/coursier/releases/download/v$csVersion/cs-x86_64-pc-linux.gz"
)
)
}
object `native-mostly-static` extends ScalaJsCliMostlyStaticNativeImage
@unused
object tests extends ScalaJsCliModule {
@unused
object test extends ScalaTests with TestModule.Munit {
def mvnDeps: T[Seq[Dep]] = super.mvnDeps() ++ Seq(
mvn"org.scalameta::munit:${Versions.munitVersion}",
mvn"com.lihaoyi::os-lib:${Versions.osLibVersion}",
mvn"com.lihaoyi::pprint:${Versions.pprintVersion}"
)
override def testForked(args: String*): Command[(msg: String, results: Seq[TestResult])] =
jvm(args*)
private def testExtraArgs(launcher: os.Path): Seq[String] = Seq(
s"-Dtest.scala-js-cli.path=$launcher",
s"-Dtest.scala-js-cli.scala-js-version=${Versions.scalaJsVersion}"
)
@unused
def jvm(args: String*): Command[(msg: String, results: Seq[TestResult])] = Task.Command {
testTask(
args = Task.Anon(args ++ testExtraArgs(cli.standaloneLauncher().path)),
globSelectors = Task.Anon(Seq.empty[String])
)()
}
@unused
def native(args: String*): Command[(msg: String, results: Seq[TestResult])] = Task.Command {
testTask(
args = Task.Anon(args ++ testExtraArgs(native0.nativeImage().path)),
globSelectors = Task.Anon(Seq.empty[String])
)()
}
@unused
def nativeStatic(args: String*): Command[(msg: String, results: Seq[TestResult])] =
Task.Command {
testTask(
args = Task.Anon(args ++ testExtraArgs(`native-static`.nativeImage().path)),
globSelectors = Task.Anon(Seq.empty[String])
)()
}
@unused
def nativeMostlyStatic(args: String*): Command[(msg: String, results: Seq[TestResult])] =
Task.Command {
testTask(
args = Task.Anon(args ++ testExtraArgs(`native-mostly-static`.nativeImage().path)),
globSelectors = Task.Anon(Seq.empty[String])
)()
}
}
}
def ghOrg = "virtuslab"
def ghName = "scala-js-cli"
def publishOrg = "org.virtuslab.scala-cli"
trait ScalaJsCliPublishModule extends SonatypeCentralPublishModule {
import mill.scalalib.publish.*
def pomSettings: T[PomSettings] = PomSettings(
description = artifactName(),
organization = publishOrg,
url = s"https://github.com/$ghOrg/$ghName",
licenses = Seq(License.`BSD-3-Clause`),
versionControl = VersionControl.github(ghOrg, ghName),
developers = Seq(
Developer("alexarchambault", "Alex Archambault", "https://github.com/alexarchambault"),
Developer("sjrd", "Sébastien Doeraene", "https://github.com/sjrd"),
Developer("gzm0", "Tobias Schlatter", "https://github.com/gzm0"),
Developer("nicolasstucki", "Nicolas Stucki", "https://github.com/nicolasstucki")
)
)
def publishVersion: T[String] = finalPublishVersion()
}
def computePublishVersion(state: VcsVersion.State, simple: Boolean): String =
if state.commitsSinceLastTag > 0 then
if simple then {
val versionOrEmpty = state.lastTag
.filter(_ != "latest")
.filter(_ != "nightly")
.map(_.stripPrefix("v"))
.map(_.takeWhile(c => c == '.' || c.isDigit))
.flatMap { tag =>
if simple then {
val idx = tag.lastIndexOf(".")
if idx >= 0 then
Some(tag.take(idx + 1) + (tag.drop(idx + 1).toInt + 1).toString + "-SNAPSHOT")
else None
}
else {
val idx = tag.indexOf("-")
if idx >= 0 then Some(tag.take(idx) + "+" + tag.drop(idx + 1) + "-SNAPSHOT") else None
}
}
.getOrElse("0.0.1-SNAPSHOT")
Some(versionOrEmpty)
.filter(_.nonEmpty)
.getOrElse(state.format())
}
else {
val rawVersion = os
.proc("git", "describe", "--tags")
.call()
.out
.text()
.trim
.stripPrefix("v")
.replace("latest", "0.0.0")
.replace("nightly", "0.0.0")
val idx = rawVersion.indexOf("-")
if idx >= 0 then rawVersion.take(idx) + "-" + rawVersion.drop(idx + 1) + "-SNAPSHOT"
else rawVersion
}
else
state.lastTag
.getOrElse(state.format())
.stripPrefix("v")
def finalPublishVersion: T[String] = {
val isCI = System.getenv("CI") != null
if isCI then
Task(persistent = true) {
val state = VcsVersion.vcsState()
computePublishVersion(state, simple = false)
}
else
Task {
val state = VcsVersion.vcsState()
computePublishVersion(state, simple = true)
}
}
object ci extends Module {
@unused
def publishSonatype(tasks: Tasks[PublishModule.PublishData]): Command[Unit] =
Task.Command {
val publishVersion = finalPublishVersion
System.err.println(s"Publish version: $publishVersion")
val bundleName = s"$publishOrg-$ghName-$publishVersion"
System.err.println(s"Publishing bundle: $bundleName")
publishSonatype0(
data = Task.sequence(tasks.value)(),
log = Task.ctx().log,
workspace = BuildCtx.workspaceRoot,
env = Task.env,
bundleName = bundleName
)
}
private def publishSonatype0(
data: Seq[PublishModule.PublishData],
log: mill.api.Logger,
workspace: os.Path,
env: Map[String, String],
bundleName: String
): Unit = {
val credentials = SonatypeCredentials(
username = sys.env("SONATYPE_USERNAME"),
password = sys.env("SONATYPE_PASSWORD")
)
val pgpPassword = sys.env("PGP_PASSPHRASE")
val timeout = 10.minutes
val artifacts = data.map { case PublishModule.PublishData(a, s) =>
(s.map { case (p, f) => (p.path, f) }, a)
}
val isRelease = {
val versions = artifacts.map(_._2.version).toSet
val set = versions.map(!_.endsWith("-SNAPSHOT"))
assert(
set.size == 1,
s"Found both snapshot and non-snapshot versions: ${versions.toVector.sorted.mkString(", ")}"
)
set.head
}
val publisher = new SonatypeCentralPublisher(
credentials = credentials,
gpgArgs = Seq(
"--detach-sign",
"--batch=true",
"--yes",
"--pinentry-mode",
"loopback",
"--passphrase",
pgpPassword,
"--armor",
"--use-agent"
),
readTimeout = timeout.toMillis.toInt,
connectTimeout = timeout.toMillis.toInt,
log = log,
workspace = workspace,
env = env,
awaitTimeout = timeout.toMillis.toInt
)
val publishingType = if isRelease then PublishingType.AUTOMATIC else PublishingType.USER_MANAGED
val finalBundleName = if bundleName.nonEmpty then Some(bundleName) else None
publisher.publishAll(
publishingType = publishingType,
singleBundleName = finalBundleName,
artifacts = artifacts*
)
}
@unused
def upload(directory: String = "artifacts/"): Command[Unit] = Task.Command {
val version = finalPublishVersion()
val path = os.Path(directory, BuildCtx.workspaceRoot)
val launchers = os.list(path).filter(os.isFile(_)).map { path =>
path -> path.last
}
val ghToken = Option(System.getenv("UPLOAD_GH_TOKEN")).getOrElse {
sys.error("UPLOAD_GH_TOKEN not set")
}
val (tag, overwriteAssets) =
if version.endsWith("-SNAPSHOT") then ("launchers", true) else ("v" + version, false)
Upload.upload(
ghOrg = ghOrg,
ghProj = ghName,
ghToken = ghToken,
tag = tag,
dryRun = false,
overwrite = overwriteAssets
)(launchers*)
// when we release `0.13.0.1` we should also update native launchers in tag `0.13.0`
if version != Versions.scalaJsVersion && !version.endsWith("-SNAPSHOT") then
Upload.upload(
ghOrg = ghOrg,
ghProj = ghName,
ghToken = ghToken,
tag = s"v${Versions.scalaJsVersion}",
dryRun = false,
overwrite = true
)(launchers*)
}
}