-
Notifications
You must be signed in to change notification settings - Fork 384
/
ScalaJSPluginInternal.scala
727 lines (591 loc) · 25.4 KB
/
ScalaJSPluginInternal.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
/*
* Scala.js (https://www.scala-js.org/)
*
* Copyright EPFL.
*
* Licensed under Apache License 2.0
* (https://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package org.scalajs.sbtplugin
import scala.annotation.tailrec
// Import Future explicitly to avoid collision with sbt.Future.
import scala.concurrent.{Future, _}
import scala.concurrent.duration._
import scala.util.{Failure, Success}
import java.util.concurrent.atomic.AtomicReference
import sbt._
import sbt.Keys._
import sbt.complete.DefaultParsers._
import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._
import org.scalajs.linker.interface._
import org.scalajs.linker.interface.unstable.IRFileImpl
import org.scalajs.jsenv._
import org.scalajs.ir.IRVersionNotSupportedException
import org.scalajs.ir.Printers.IRTreePrinter
import org.scalajs.testing.adapter.{TestAdapter, HTMLRunnerBuilder, TestAdapterInitializer}
import Loggers._
import sjsonnew.BasicJsonProtocol._
/** Implementation details of `ScalaJSPlugin`. */
private[sbtplugin] object ScalaJSPluginInternal {
import ScalaJSPlugin.autoImport.{ModuleKind => _, _}
@tailrec
final private def registerResource[T <: AnyRef](
l: AtomicReference[List[T]], r: T): r.type = {
val prev = l.get()
if (l.compareAndSet(prev, r :: prev)) r
else registerResource(l, r)
}
private val allocatedIRCaches =
new AtomicReference[List[IRFileCache.Cache]](Nil)
private[sbtplugin] def freeAllIRCaches(): Unit =
allocatedIRCaches.getAndSet(Nil).foreach(_.free())
private val createdTestAdapters =
new AtomicReference[List[TestAdapter]](Nil)
private def newTestAdapter(jsEnv: JSEnv, input: Seq[Input],
config: TestAdapter.Config): TestAdapter = {
registerResource(createdTestAdapters, new TestAdapter(jsEnv, input, config))
}
private[sbtplugin] def closeAllTestAdapters(): Unit =
createdTestAdapters.getAndSet(Nil).foreach(_.close())
private def enhanceIRVersionNotSupportedException[A](body: => A): A = {
try {
body
} catch {
case e: IRVersionNotSupportedException =>
throw new IRVersionNotSupportedException(e.version, e.supported,
s"${e.getMessage}\nYou may need to upgrade the Scala.js sbt " +
s"plugin to version ${e.version} or later.",
e)
}
}
private def linkerOutputDirectory(v: Attributed[Report]): File = {
v.get(scalaJSLinkerOutputDirectory.key).getOrElse {
throw new MessageOnlyException(
"Linking report was not attributed with output directory. " +
"Please report this as s Scala.js bug.")
}
}
private def await[T](log: Logger)(body: ExecutionContext => Future[T]): T = {
val ec = ExecutionContext.fromExecutor(
ExecutionContext.global, t => log.trace(t))
Await.result(body(ec), Duration.Inf)
}
private val scalajspParser = {
loadForParser(scalaJSClassNamesOnClasspath) { (_, names) =>
val examples = sbt.complete.FixedSetExamples(names.getOrElse(Nil))
OptSpace ~> StringBasic.examples(examples)
}
}
/** Patches the IncOptions so that .sjsir files are pruned, backed up and
* restored as needed.
*/
def scalaJSPatchIncOptions(incOptions: IncOptions): IncOptions = {
val sjsirFileManager = new SJSIRFileManager
val newExternalHooks =
incOptions.externalHooks.withExternalClassFileManager(sjsirFileManager)
incOptions.withExternalHooks(newExternalHooks)
}
/** Settings for the production key (e.g. fastLinkJS) of a given stage */
private def scalaJSStageSettings(stage: Stage,
key: TaskKey[Attributed[Report]],
legacyKey: TaskKey[Attributed[File]]): Seq[Setting[_]] = Seq(
scalaJSLinkerBox in key := new CacheBox,
scalaJSLinker in legacyKey := {
val config = (scalaJSLinkerConfig in key).value
val box = (scalaJSLinkerBox in key).value
val linkerImpl = (scalaJSLinkerImpl in key).value
box.ensure(linkerImpl.clearableLinker(config))
},
scalaJSLinker in key := (scalaJSLinker in legacyKey).value,
// Have `clean` reset the state of the incremental linker
clean in (This, Zero, This) := {
val _ = (clean in (This, Zero, This)).value
(scalaJSLinkerBox in key).value.foreach(_.clear())
()
},
usesScalaJSLinkerTag in legacyKey := {
val projectPart = thisProject.value.id
val configPart = configuration.value.name
val stagePart = stage match {
case Stage.FastOpt => "fastopt"
case Stage.FullOpt => "fullopt"
}
Tags.Tag(s"uses-scalajs-linker-$projectPart-$configPart-$stagePart")
},
usesScalaJSLinkerTag in key := (usesScalaJSLinkerTag in legacyKey).value,
// Prevent this linker from being used concurrently
concurrentRestrictions in Global +=
Tags.limit((usesScalaJSLinkerTag in key).value, 1),
scalaJSModuleInitializersFingerprints in key :=
scalaJSModuleInitializers.value.map(ModuleInitializer.fingerprint),
scalaJSLinkerConfigFingerprint in key :=
StandardConfig.fingerprint((scalaJSLinkerConfig in key).value),
moduleName in key := (moduleName in legacyKey).value,
scalaJSLinkerConfig in key := (scalaJSLinkerConfig in legacyKey).value,
key := Def.taskDyn {
/* It is very important that we evaluate all of those `.value`s from
* here, and not from within the `Def.task { ... }`, otherwise the
* relevant dependencies will not show up in `inspect tree`. We use a
* `Def.taskDyn` only to be able to tag the inner task with a tag that
* is setting-dependent. But otherwise, the task does not have actually
* dynamic dependencies, so `inspect tree` is happy with it.
*/
val s = streams.value
val irInfo = (scalaJSIR in key).value
val moduleInitializers = scalaJSModuleInitializers.value
val reportFile = s.cacheDirectory / "linking-report.bin"
val outputDir = (scalaJSLinkerOutputDirectory in key).value
val linker = (scalaJSLinker in key).value
val linkerImpl = (scalaJSLinkerImpl in key).value
val usesLinkerTag = (usesScalaJSLinkerTag in key).value
val configChanged = {
def moduleInitializersChanged = (scalaJSModuleInitializersFingerprints in key)
.previous
.exists(_ != (scalaJSModuleInitializersFingerprints in key).value)
def linkerConfigChanged = (scalaJSLinkerConfigFingerprint in key)
.previous
.exists(_ != (scalaJSLinkerConfigFingerprint in key).value)
moduleInitializersChanged || linkerConfigChanged
}
def reportIncompatible =
Report.deserialize(IO.readBytes(reportFile)).isEmpty
if (reportFile.exists() && (configChanged || reportIncompatible)) {
reportFile.delete() // triggers re-linking through FileFunction.cached
}
Def.task {
val log = s.log
val realFiles = irInfo.get(scalaJSSourceFiles).get
val ir = irInfo.data
FileFunction.cached(s.cacheDirectory, FilesInfo.lastModified,
FilesInfo.exists) { _ => // We don't need the files
val stageName = stage match {
case Stage.FastOpt => "Fast"
case Stage.FullOpt => "Full"
}
log.info(s"$stageName optimizing $outputDir")
IO.createDirectory(outputDir)
val out = linkerImpl.outputDirectory(outputDir.toPath)
val report = try {
enhanceIRVersionNotSupportedException {
val tlog = sbtLogger2ToolsLogger(log)
await(log)(linker.link(ir, moduleInitializers, out, tlog)(_))
}
} catch {
case e: LinkingException =>
throw new MessageOnlyException(e.getMessage)
}
IO.write(reportFile, Report.serialize(report))
IO.listFiles(outputDir).toSet + reportFile
} (realFiles.toSet)
val report = Report.deserialize(IO.readBytes(reportFile)).getOrElse {
throw new MessageOnlyException("failed to deserialize report after " +
"linking. Please report this as s Scala.js bug.")
}
Attributed.blank(report)
.put(scalaJSLinkerOutputDirectory.key, outputDir)
}.tag(usesLinkerTag, ScalaJSTags.Link)
}.value,
legacyKey := {
val linkingResult = key.value
val linkerImpl = (scalaJSLinkerImpl in key).value
val report = linkingResult.data
val outDir =
linkerImpl.outputDirectory(linkerOutputDirectory(linkingResult).toPath())
val outputJSFile = (artifactPath in legacyKey).value
val outputSourceMapFile = new File(outputJSFile.getPath + ".map")
IO.createDirectory(outputJSFile.getParentFile)
// Dummy class to silence deprecation warnings.
abstract class Converter {
def convert(): Unit
}
object Converter extends Converter {
@deprecated("Deprecate to silence warnings", "never/always")
def convert(): Unit = {
val legacyOutput = {
def relURI(path: String) = new URI(null, null, path, null)
LinkerOutput(linkerImpl.outputFile(outputJSFile.toPath()))
.withSourceMap(linkerImpl.outputFile(outputSourceMapFile.toPath()))
.withSourceMapURI(relURI(outputSourceMapFile.getName()))
.withJSFileURI(relURI(outputJSFile.getName()))
}
await(streams.value.log) { eci =>
implicit val ec = eci
ReportToLinkerOutputAdapter.convert(report, outDir, legacyOutput).recover {
case e: ReportToLinkerOutputAdapter.UnsupportedLinkerOutputException =>
throw new MessageOnlyException(
"The linker produced a result not supported by the legacy " +
s"task ${legacyKey.key}. Did you mean to invoke ${key.key} " +
"instead? " + e.getMessage())
}
}
}
}
(Converter: Converter).convert()
/* We always need to supply a module kind, but if we do not have an
* output module, we do not know the module kind.
* Therefore, we do what we used to do in the older implementation: We
* take it from the config itself.
*/
val linkerConfig = (scalaJSLinkerConfig in legacyKey).value
val moduleKind = report.publicModules.headOption
.fold(linkerConfig.moduleKind)(_.moduleKind)
Attributed.blank(outputJSFile)
.put(scalaJSSourceMap, outputSourceMapFile)
.put(scalaJSModuleKind, moduleKind)
}
)
val scalaJSConfigSettings: Seq[Setting[_]] = Seq(
incOptions ~= scalaJSPatchIncOptions
) ++ (
scalaJSStageSettings(Stage.FastOpt, fastLinkJS, fastOptJS) ++
scalaJSStageSettings(Stage.FullOpt, fullLinkJS, fullOptJS)
) ++ (
Seq(fastOptJS, fullOptJS).map { key =>
moduleName in key := {
val configSuffix = configuration.value match {
case Compile => ""
case config => "-" + config.name
}
moduleName.value + configSuffix
}
}
) ++ Seq(
// Note: this cache is not cleared by the sbt's clean task.
scalaJSIRCacheBox := new CacheBox,
scalaJSIR := {
val linkerImpl = (scalaJSLinkerImpl in scalaJSIR).value
val globalIRCache = (scalaJSGlobalIRCache in scalaJSIR).value
val cache = scalaJSIRCacheBox.value
.ensure(registerResource(allocatedIRCaches, globalIRCache.newCache))
val classpath = Attributed.data(fullClasspath.value)
val log = streams.value.log
val tlog = sbtLogger2ToolsLogger(log)
val (irFiles, paths) = enhanceIRVersionNotSupportedException {
tlog.time("Update IR cache") {
await(log) { eci =>
implicit val ec = eci
for {
(irContainers, paths) <- linkerImpl.irContainers(classpath.map(_.toPath))
irFiles <- cache.cached(irContainers)
} yield (irFiles, paths)
}
}
}
Attributed
.blank[Seq[IRFile]](irFiles)
.put(scalaJSSourceFiles, paths.map(_.toFile))
},
scalaJSClassNamesOnClasspath := Def.task {
val none = Future.successful(None)
await(streams.value.log) { eci =>
implicit val ec = eci
Future.traverse(scalaJSIR.value.data) { ir =>
IRFileImpl.fromIRFile(ir)
.entryPointsInfo
.map(i => Some(i.className.nameString))
.fallbackTo(none)
}
}.flatten
}.storeAs(scalaJSClassNamesOnClasspath).triggeredBy(scalaJSIR).value,
scalajsp := {
val name = scalajspParser.parsed
enhanceIRVersionNotSupportedException {
val log = streams.value.log
val stdout = new java.io.PrintWriter(System.out)
val tree = await(log) { eci =>
implicit val ec = eci
Future.traverse(scalaJSIR.value.data) { irFile =>
val ir = IRFileImpl.fromIRFile(irFile)
ir.entryPointsInfo.map { i =>
if (i.className.nameString == name) Success(Some(ir))
else Success(None)
}.recover { case t => Failure(t) }
}.flatMap { irs =>
irs.collectFirst {
case Success(Some(f)) => f.tree
}.getOrElse {
val t = new MessageOnlyException(s"class $name not found on classpath")
irs.collect { case Failure(st) => t.addSuppressed(st) }
throw t
}
}
}
new IRTreePrinter(stdout).print(tree)
stdout.flush()
}
},
scalaJSLinkerOutputDirectory in fastLinkJS :=
((crossTarget in fastLinkJS).value /
((moduleName in fastLinkJS).value + "-fastopt")),
scalaJSLinkerOutputDirectory in fullLinkJS :=
((crossTarget in fullLinkJS).value /
((moduleName in fullLinkJS).value + "-opt")),
artifactPath in fastOptJS :=
((crossTarget in fastOptJS).value /
((moduleName in fastOptJS).value + "-fastopt.js")),
artifactPath in fullOptJS :=
((crossTarget in fullOptJS).value /
((moduleName in fullOptJS).value + "-opt.js")),
scalaJSLinkerConfig in fullOptJS ~= { prevConfig =>
val useClosure = prevConfig.moduleKind != ModuleKind.ESModule
prevConfig
.withSemantics(_.optimized)
.withClosureCompiler(useClosure)
.withCheckIR(true) // for safety, fullOpt is slow anyways.
},
scalaJSLinkerResult := Def.settingDyn {
scalaJSStage.value match {
case Stage.FastOpt => fastLinkJS
case Stage.FullOpt => fullLinkJS
}
}.value,
scalaJSLinkedFile := Def.settingDyn {
scalaJSStage.value match {
case Stage.FastOpt => fastOptJS
case Stage.FullOpt => fullOptJS
}
}.value,
console := console.dependsOn(Def.task {
streams.value.log.warn("Scala REPL doesn't work with Scala.js. You " +
"are running a JVM REPL. JavaScript things won't work.")
}).value,
/* Do not inherit jsEnvInput from the parent configuration.
* Instead, always derive it straight from the Zero configuration scope.
*/
jsEnvInput := (jsEnvInput in (This, Zero, This)).value,
// Add the Scala.js linked file to the Input for the JSEnv.
jsEnvInput += {
val linkingResult = scalaJSLinkerResult.value
val report = linkingResult.data
val mainModule = report.publicModules.find(_.moduleID == "main").getOrElse {
throw new MessageOnlyException(
"Cannot determine `jsEnvInput`: Linking result does not have a " +
"module named `main`. Set jsEnvInput manually?\n" +
s"Full report:\n$report")
}
val path =
(linkerOutputDirectory(linkingResult) / mainModule.jsFileName).toPath
mainModule.moduleKind match {
case ModuleKind.NoModule => Input.Script(path)
case ModuleKind.ESModule => Input.ESModule(path)
case ModuleKind.CommonJSModule => Input.CommonJSModule(path)
}
},
scalaJSMainModuleInitializer := {
mainClass.value.map { mainCl =>
ModuleInitializer.mainMethodWithArgs(mainCl, "main")
}
},
/* Do not inherit scalaJSModuleInitializers from the parent configuration.
* Instead, always derive them straight from the Zero configuration
* scope.
*/
scalaJSModuleInitializers :=
(scalaJSModuleInitializers in (This, Zero, This)).value,
scalaJSModuleInitializers ++= {
val mainClasses = discoveredMainClasses.value
if (scalaJSUseMainModuleInitializer.value) {
Seq(scalaJSMainModuleInitializer.value.getOrElse {
if (mainClasses.isEmpty) {
throw new MessageOnlyException(
"No main module initializer was specified, but " +
"scalaJSUseMainModuleInitializer was set to true. " +
"You can explicitly specify it either with " +
"`mainClass := Some(...)` or with " +
"`scalaJSMainModuleInitializer := Some(...)`")
} else {
throw new MessageOnlyException(
s"Multiple main classes (${mainClasses.mkString(", ")}) " +
"were found. " +
"You can explicitly specify the one you want with " +
"`mainClass := Some(...)` or with " +
"`scalaJSMainModuleInitializer := Some(...)`")
}
})
} else {
Seq.empty
}
},
run := {
if (!scalaJSUseMainModuleInitializer.value) {
throw new MessageOnlyException("`run` is only supported with " +
"scalaJSUseMainModuleInitializer := true")
}
val log = streams.value.log
val env = jsEnv.value
val className = mainClass.value.getOrElse("<unknown class>")
log.info(s"Running $className. Hit any key to interrupt.")
log.debug(s"with JSEnv ${env.name}")
val input = jsEnvInput.value
val config = RunConfig().withLogger(sbtLogger2ToolsLogger(log))
Run.runInterruptible(env, input, config)
},
runMain := {
throw new MessageOnlyException("`runMain` is not supported in Scala.js")
}
)
val scalaJSCompileSettings: Seq[Setting[_]] = (
scalaJSConfigSettings
)
val scalaJSTestSettings: Seq[Setting[_]] = (
scalaJSConfigSettings
) ++ Seq(
/* Always default to false for scalaJSUseMainModuleInitializer in testing
* configurations, even if it is true in the Global configuration scope.
*/
scalaJSUseMainModuleInitializer := false,
// Use test module initializer by default.
scalaJSUseTestModuleInitializer := true,
scalaJSModuleInitializers ++= {
val useMain = scalaJSUseMainModuleInitializer.value
val useTest = scalaJSUseTestModuleInitializer.value
val configName = configuration.value.name
if (useTest) {
if (useMain) {
throw new MessageOnlyException("You may only set one of " +
s"`$configName / scalaJSUseMainModuleInitializer` " +
s"`$configName / scalaJSUseTestModuleInitializer` true")
}
Seq(
ModuleInitializer.mainMethod(
TestAdapterInitializer.ModuleClassName,
TestAdapterInitializer.MainMethodName)
)
} else {
Seq.empty
}
},
loadedTestFrameworks := {
val configName = configuration.value.name
val input = jsEnvInput.value
if (fork.value) {
throw new MessageOnlyException(
s"`$configName / test` tasks in a Scala.js project require " +
s"`$configName / fork := false`.")
}
if (!scalaJSUseTestModuleInitializer.value) {
throw new MessageOnlyException(
s"You may only use `$configName / test` tasks in a Scala.js project if " +
s"`$configName / scalaJSUseTestModuleInitializer := true`.")
}
if (input.isEmpty) {
throw new MessageOnlyException(
s"`$configName / test` got called but `$configName / jsEnvInput` is empty. " +
"This is not allowed, since running tests requires the generated Scala.js code. " +
s"If you want to call `$configName / test` but not have it do anything, " +
s"set `$configName / test` := {}`.")
}
val frameworks = testFrameworks.value
val env = jsEnv.value
val frameworkNames = frameworks.map(_.implClassNames.toList).toList
val logger = sbtLogger2ToolsLogger(streams.value.log)
val config = TestAdapter.Config()
.withLogger(logger)
val adapter = newTestAdapter(env, input, config)
val frameworkAdapters = adapter.loadFrameworks(frameworkNames)
frameworks.zip(frameworkAdapters).collect {
case (tf, Some(adapter)) => (tf, adapter)
}.toMap
},
// Override default to avoid triggering a test:fastLinkJS in a test:compile
// without losing autocompletion.
definedTestNames := {
definedTests.map(_.map(_.name).distinct)
.storeAs(definedTestNames).triggeredBy(loadedTestFrameworks).value
},
scalaJSTestHTMLArtifactDirectory := {
val stageSuffix = scalaJSStage.value match {
case Stage.FastOpt => "fastopt"
case Stage.FullOpt => "opt"
}
val config = configuration.value.name
((crossTarget in testHtml).value /
((moduleName in testHtml).value + s"-$stageSuffix-$config-html"))
},
artifactPath in testHtml :=
scalaJSTestHTMLArtifactDirectory.value / "index.html",
testHtml := {
val log = streams.value.log
val output = (artifactPath in testHtml).value
val artifactDirectory = scalaJSTestHTMLArtifactDirectory.value
val title = name.value + " - tests"
val input = (jsEnvInput in testHtml).value
val frameworks = (loadedTestFrameworks in testHtml).value.toList
val frameworkImplClassNames =
frameworks.map(_._1.implClassNames.toList)
val taskDefs = for (td <- (definedTests in testHtml).value) yield {
new sbt.testing.TaskDef(td.name, td.fingerprint,
td.explicitlySpecified, td.selectors)
}
IO.createDirectory(artifactDirectory)
HTMLRunnerBuilder.write(output.toPath(), artifactDirectory.toPath(),
title, input, frameworkImplClassNames, taskDefs.toList)
if (input.exists(_.isInstanceOf[Input.ESModule])) {
log.info(s"Wrote HTML test runner to $output. You must serve it " +
"through an HTTP server (e.g. `python3 -m http.server`), since " +
"it loads at least one ESModule.")
} else {
log.info(s"Wrote HTML test runner. Point your browser to ${output.toURI}")
}
Attributed.blank(output)
}
)
private def isScala3(scalaV: String): Boolean =
scalaV.startsWith("3.")
private val scalaJSProjectBaseSettings = Seq(
platformDepsCrossVersion := ScalaJSCrossVersion.binary,
crossVersion := ScalaJSCrossVersion.binary,
scalaJSModuleInitializers := Seq(),
scalaJSUseMainModuleInitializer := false,
jsEnvInput := Nil,
/* Add core library dependencies (and compiler plugin), depending on the
* Scala version (2.x versus 3.x).
*/
libraryDependencies := {
val prev = libraryDependencies.value
val scalaOrg = scalaOrganization.value
val scalaV = scalaVersion.value
if (isScala3(scalaV)) {
/* Remove scala3-library (non _sjs1) in case sbt-dotty was applied
* before sbt-scalajs.
*/
val filteredPrev = prev.filterNot { dep =>
dep.organization == scalaOrg && dep.name == "scala3-library"
}
filteredPrev ++ Seq(
scalaOrg %% "scala3-library_sjs1" % scalaV,
/* scala3-library_sjs1 depends on some version of scalajs-library_2.13,
* but we bump it to be at least scalaJSVersion.
*/
"org.scala-js" % "scalajs-library_2.13" % scalaJSVersion,
"org.scala-js" % "scalajs-test-bridge_2.13" % scalaJSVersion % "test"
)
} else {
prev ++ Seq(
compilerPlugin("org.scala-js" % "scalajs-compiler" % scalaJSVersion cross CrossVersion.full),
"org.scala-js" %% "scalajs-library" % scalaJSVersion,
"org.scala-js" %% "scalajs-test-bridge" % scalaJSVersion % "test"
)
}
},
/* Add the `-scalajs` compiler flag if this is Scala 3, and it is not
* already present (that could happen if sbt-dotty is used and is applied
* before sbt-scalajs).
*/
scalacOptions := {
val prev = scalacOptions.value
if (isScala3(scalaVersion.value) && !prev.contains("-scalajs"))
prev :+ "-scalajs"
else
prev
}
)
val scalaJSProjectSettings: Seq[Setting[_]] = (
scalaJSProjectBaseSettings ++
inConfig(Compile)(scalaJSCompileSettings) ++
inConfig(Test)(scalaJSTestSettings)
)
}