forked from VirtusLab/scala-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Build.scala
1272 lines (1150 loc) · 39.1 KB
/
Build.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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package scala.build
import ch.epfl.scala.bsp4j
import com.swoval.files.FileTreeViews.Observer
import com.swoval.files.{PathWatcher, PathWatchers}
import dependency.ScalaParameters
import java.io.File
import java.nio.file.FileSystemException
import java.util.concurrent.{ScheduledExecutorService, ScheduledFuture}
import scala.annotation.tailrec
import scala.build.EitherCps.{either, value}
import scala.build.Inputs.VirtualScript.VirtualScriptNameRegex
import scala.build.Ops.*
import scala.build.actionable.ActionablePreprocessor
import scala.build.compiler.{ScalaCompiler, ScalaCompilerMaker}
import scala.build.errors.*
import scala.build.internal.resource.ResourceMapper
import scala.build.internal.{Constants, CustomCodeWrapper, MainClass, Util}
import scala.build.options.ScalaVersionUtil.asVersion
import scala.build.options.*
import scala.build.options.validation.ValidationException
import scala.build.postprocessing.*
import scala.collection.mutable.ListBuffer
import scala.concurrent.duration.DurationInt
import scala.util.control.NonFatal
import scala.util.{Properties, Try}
trait Build {
def inputs: Inputs
def options: BuildOptions
def scope: Scope
def outputOpt: Option[os.Path]
def success: Boolean
def diagnostics: Option[Seq[(Either[String, os.Path], bsp4j.Diagnostic)]]
def successfulOpt: Option[Build.Successful]
}
object Build {
final case class Successful(
inputs: Inputs,
options: BuildOptions,
scalaParams: Option[ScalaParameters],
scope: Scope,
sources: Sources,
artifacts: Artifacts,
project: Project,
output: os.Path,
diagnostics: Option[Seq[(Either[String, os.Path], bsp4j.Diagnostic)]],
generatedSources: Seq[GeneratedSource],
isPartial: Boolean
) extends Build {
def success: Boolean = true
def successfulOpt: Some[this.type] = Some(this)
def outputOpt: Some[os.Path] = Some(output)
def dependencyClassPath: Seq[os.Path] = sources.resourceDirs ++ artifacts.classPath
def fullClassPath: Seq[os.Path] = Seq(output) ++ dependencyClassPath
def foundMainClasses(): Seq[String] =
MainClass.find(output) ++ options.classPathOptions.extraClassPath.flatMap(MainClass.find)
def retainedMainClass(
mainClasses: Seq[String],
commandString: String,
logger: Logger
): Either[MainClassError, String] = {
val defaultMainClassOpt = sources.defaultMainClass
.filter(name => mainClasses.contains(name))
def foundMainClass =
mainClasses match {
case Seq() => Left(new NoMainClassFoundError)
case Seq(mainClass) => Right(mainClass)
case _ =>
inferredMainClass(mainClasses, logger).left.flatMap { mainClasses =>
options.interactive
.chooseOne(
"Found several main classes. Which would you like to run?",
mainClasses.toList
)
.toRight {
SeveralMainClassesFoundError(
::(mainClasses.head, mainClasses.tail.toList),
commandString,
Nil
)
}
}
}
defaultMainClassOpt match {
case Some(cls) => Right(cls)
case None => foundMainClass
}
}
private def inferredMainClass(
mainClasses: Seq[String],
logger: Logger
): Either[Seq[String], String] = {
val scriptInferredMainClasses =
sources.inMemory.map(im => im.originalPath.map(_._1))
.flatMap {
case Right(originalRelPath) if originalRelPath.toString.endsWith(".sc") =>
Some {
originalRelPath
.toString
.replace(".", "_")
.replace("/", ".")
}
case Left(VirtualScriptNameRegex(name)) => Some(s"${name}_sc")
case _ => None
}
val filteredMainClasses =
mainClasses.filter(!scriptInferredMainClasses.contains(_))
if (filteredMainClasses.length == 1) {
val pickedMainClass = filteredMainClasses.head
if (scriptInferredMainClasses.nonEmpty) {
val firstScript = scriptInferredMainClasses.head
val scriptsString = scriptInferredMainClasses.mkString(", ")
logger.message(
s"Running $pickedMainClass. Also detected script main classes: $scriptsString"
)
logger.message(
s"You can run any one of them by passing option --main-class, i.e. --main-class $firstScript"
)
logger.message(
"All available main classes can always be listed by passing option --list-main-classes"
)
}
Right(pickedMainClass)
}
else
Left(mainClasses)
}
def retainedMainClassOpt(
mainClasses: Seq[String],
logger: Logger
): Option[String] = {
val defaultMainClassOpt = sources.defaultMainClass
.filter(name => mainClasses.contains(name))
def foundMainClass =
mainClasses match {
case Seq() => None
case Seq(mainClass) => Some(mainClass)
case _ => inferredMainClass(mainClasses, logger).toOption
}
defaultMainClassOpt.orElse(foundMainClass)
}
def crossKey: CrossKey = {
val optKey = scalaParams.map { params =>
BuildOptions.CrossKey(
params.scalaVersion,
options.platform.value
)
}
CrossKey(optKey, scope)
}
}
final case class Failed(
inputs: Inputs,
options: BuildOptions,
scope: Scope,
sources: Sources,
artifacts: Artifacts,
project: Project,
diagnostics: Option[Seq[(Either[String, os.Path], bsp4j.Diagnostic)]]
) extends Build {
def success: Boolean = false
def successfulOpt: None.type = None
def outputOpt: None.type = None
}
final case class Cancelled(
inputs: Inputs,
options: BuildOptions,
scope: Scope,
reason: String
) extends Build {
def success: Boolean = false
def successfulOpt: None.type = None
def outputOpt: None.type = None
def diagnostics: None.type = None
}
def updateInputs(
inputs: Inputs,
options: BuildOptions,
testOptions: Option[BuildOptions] = None
): Inputs = {
// If some options are manually overridden, append a hash of the options to the project name
// Using options, not options0 - only the command-line options are taken into account. No hash is
// appended for options from the sources.
val optionsHash = options.hash
val testOptionsHash = testOptions.flatMap(_.hash)
inputs.copy(
baseProjectName =
inputs.baseProjectName
+ optionsHash.map("_" + _).getOrElse("")
+ testOptionsHash.map("_" + _).getOrElse("")
)
}
private def build(
inputs: Inputs,
options: BuildOptions,
logger: Logger,
buildClient: BloopBuildClient,
compiler: ScalaCompiler,
docCompilerOpt: Option[ScalaCompiler],
crossBuilds: Boolean,
buildTests: Boolean,
partial: Option[Boolean],
actionableDiagnostics: Option[Boolean]
): Either[BuildException, Builds] = either {
// allInputs contains elements from using directives
val (crossSources, allInputs) = value {
CrossSources.forInputs(
inputs,
Sources.defaultPreprocessors(
options.scriptOptions.codeWrapper.getOrElse(CustomCodeWrapper),
options.archiveCache,
options.internal.javaClassNameVersionOpt,
() => options.javaHome().value.javaCommand
),
logger
)
}
val sharedOptions = crossSources.sharedOptions(options)
val crossOptions = sharedOptions.crossOptions
def doPostProcess(build: Build, inputs: Inputs, scope: Scope): Unit = build match {
case build: Build.Successful =>
for (sv <- build.project.scalaCompiler.map(_.scalaVersion))
postProcess(
build.generatedSources,
inputs.generatedSrcRoot(scope),
build.output,
logger,
inputs.workspace,
updateSemanticDbs = true,
scalaVersion = sv
).left.foreach(_.foreach(logger.message(_)))
case _ =>
}
final case class NonCrossBuilds(
main: Build,
testOpt: Option[Build],
docOpt: Option[Build],
testDocOpt: Option[Build]
)
def doBuild(
overrideOptions: BuildOptions
): Either[BuildException, NonCrossBuilds] = either {
val baseOptions = overrideOptions.orElse(sharedOptions)
val scopedSources = value(crossSources.scopedSources(baseOptions))
val mainSources = scopedSources.sources(Scope.Main, baseOptions)
val mainOptions = mainSources.buildOptions
val testSources = scopedSources.sources(Scope.Test, baseOptions)
val testOptions = testSources.buildOptions
val inputs0 = updateInputs(
allInputs,
mainOptions, // update hash in inputs with options coming from the CLI or cross-building, not from the sources
Some(testOptions)
)
def doBuildScope(
options: BuildOptions,
sources: Sources,
scope: Scope,
actualCompiler: ScalaCompiler = compiler
): Either[BuildException, Build] =
either {
val sources0 = sources.withVirtualDir(inputs0, scope, options)
val generatedSources = sources0.generateSources(inputs0.generatedSrcRoot(scope))
val res = build(
inputs0,
sources0,
generatedSources,
options,
scope,
logger,
buildClient,
actualCompiler,
buildTests,
partial,
actionableDiagnostics
)
value(res)
}
val mainBuild = value(doBuildScope(mainOptions, mainSources, Scope.Main))
val mainDocBuildOpt = docCompilerOpt match {
case None => None
case Some(docCompiler) =>
Some(value(doBuildScope(
mainOptions,
mainSources,
Scope.Main,
actualCompiler = docCompiler
)))
}
def testBuildOpt(doc: Boolean = false): Either[BuildException, Option[Build]] = either {
if (buildTests) {
val actualCompilerOpt =
if (doc) docCompilerOpt
else Some(compiler)
actualCompilerOpt match {
case None => None
case Some(actualCompiler) =>
val testBuild = value {
mainBuild match {
case s: Build.Successful =>
val extraTestOptions = BuildOptions(
classPathOptions = ClassPathOptions(
extraClassPath = Seq(s.output)
)
)
val testOptions0 = extraTestOptions.orElse(testOptions)
doBuildScope(
testOptions0,
testSources,
Scope.Test,
actualCompiler = actualCompiler
)
case _ =>
Right(Build.Cancelled(
inputs,
sharedOptions,
Scope.Test,
"Parent build failed or cancelled"
))
}
}
Some(testBuild)
}
}
else None
}
val testBuildOpt0 = value(testBuildOpt())
doPostProcess(mainBuild, inputs0, Scope.Main)
for (testBuild <- testBuildOpt0)
doPostProcess(testBuild, inputs0, Scope.Test)
val docTestBuildOpt0 = value(testBuildOpt(doc = true))
NonCrossBuilds(mainBuild, testBuildOpt0, mainDocBuildOpt, docTestBuildOpt0)
}
def buildScopes(): Either[BuildException, Builds] =
either {
val nonCrossBuilds = value(doBuild(BuildOptions()))
val (extraMainBuilds, extraTestBuilds, extraDocBuilds, extraDocTestBuilds) =
if (crossBuilds) {
val extraBuilds = value {
val maybeBuilds = crossOptions.map(doBuild)
maybeBuilds
.sequence
.left.map(CompositeBuildException(_))
}
(
extraBuilds.map(_.main),
extraBuilds.flatMap(_.testOpt),
extraBuilds.flatMap(_.docOpt),
extraBuilds.flatMap(_.testDocOpt)
)
}
else
(Nil, Nil, Nil, Nil)
Builds(
Seq(nonCrossBuilds.main) ++ nonCrossBuilds.testOpt.toSeq,
Seq(extraMainBuilds, extraTestBuilds),
nonCrossBuilds.docOpt.toSeq ++ nonCrossBuilds.testDocOpt.toSeq,
Seq(extraDocBuilds, extraDocTestBuilds)
)
}
val builds = value(buildScopes())
ResourceMapper.copyResourceToClassesDir(builds.main)
for (testBuild <- builds.get(Scope.Test))
ResourceMapper.copyResourceToClassesDir(testBuild)
if (actionableDiagnostics.getOrElse(false)) {
val projectOptions = builds.get(Scope.Test).getOrElse(builds.main).options
projectOptions.logActionableDiagnostics(logger)
}
builds
}
private def build(
inputs: Inputs,
sources: Sources,
generatedSources: Seq[GeneratedSource],
options: BuildOptions,
scope: Scope,
logger: Logger,
buildClient: BloopBuildClient,
compiler: ScalaCompiler,
buildTests: Boolean,
partial: Option[Boolean],
actionableDiagnostics: Option[Boolean]
): Either[BuildException, Build] = either {
val build0 = value {
buildOnce(
inputs,
sources,
generatedSources,
options,
scope,
logger,
buildClient,
compiler,
partial
)
}
build0 match {
case successful: Successful =>
if (options.jmhOptions.runJmh.getOrElse(false) && scope == Scope.Main)
value {
val res = jmhBuild(
inputs,
successful,
logger,
successful.options.javaHome().value.javaCommand,
buildClient,
compiler,
buildTests,
actionableDiagnostics = actionableDiagnostics
)
res.flatMap {
case Some(b) => Right(b)
case None => Left(new JmhBuildFailedError)
}
}
else
build0
case _ => build0
}
}
def classesRootDir(root: os.Path, projectName: String): os.Path =
root / Constants.workspaceDirName / projectName / "classes"
def classesDir(root: os.Path, projectName: String, scope: Scope, suffix: String = ""): os.Path =
classesRootDir(root, projectName) / s"${scope.name}$suffix"
def resourcesRegistry(
root: os.Path,
projectName: String,
scope: Scope
): os.Path =
root / Constants.workspaceDirName / projectName / s"resources-${scope.name}"
def scalaNativeSupported(
options: BuildOptions,
inputs: Inputs,
logger: Logger
): Either[BuildException, Option[ScalaNativeCompatibilityError]] =
either {
val scalaParamsOpt = value(options.scalaParams)
scalaParamsOpt.flatMap { scalaParams =>
val scalaVersion = scalaParams.scalaVersion
val nativeVersionMaybe = options.scalaNativeOptions.numeralVersion
def snCompatError =
Left(
new ScalaNativeCompatibilityError(
scalaVersion,
options.scalaNativeOptions.finalVersion
)
)
def warnIncompatibleNativeOptions(numeralVersion: SNNumeralVersion) =
if (
numeralVersion < SNNumeralVersion(0, 4, 4)
&& options.scalaNativeOptions.embedResources.isDefined
)
logger.diagnostic(
"This Scala Version cannot embed resources, regardless of the options used."
)
val numeralOrError: Either[ScalaNativeCompatibilityError, SNNumeralVersion] =
nativeVersionMaybe match {
case Some(snNumeralVer) =>
if (snNumeralVer < SNNumeralVersion(0, 4, 1) && Properties.isWin)
snCompatError
else if (scalaVersion.startsWith("3.0"))
snCompatError
else if (scalaVersion.startsWith("3"))
if (snNumeralVer >= SNNumeralVersion(0, 4, 3)) Right(snNumeralVer)
else snCompatError
else if (scalaVersion.startsWith("2.13"))
Right(snNumeralVer)
else if (scalaVersion.startsWith("2.12"))
if (
inputs.sourceFiles().forall {
case _: Inputs.AnyScript => snNumeralVer >= SNNumeralVersion(0, 4, 3)
case _ => true
}
) Right(snNumeralVer)
else snCompatError
else snCompatError
case None => snCompatError
}
numeralOrError match {
case Left(compatError) => Some(compatError)
case Right(snNumeralVersion) =>
warnIncompatibleNativeOptions(snNumeralVersion)
None
}
}
}
def build(
inputs: Inputs,
options: BuildOptions,
compilerMaker: ScalaCompilerMaker,
docCompilerMakerOpt: Option[ScalaCompilerMaker],
logger: Logger,
crossBuilds: Boolean,
buildTests: Boolean,
partial: Option[Boolean],
actionableDiagnostics: Option[Boolean]
): Either[BuildException, Builds] = {
val buildClient = BloopBuildClient.create(
logger,
keepDiagnostics = options.internal.keepDiagnostics
)
val classesDir0 = classesRootDir(inputs.workspace, inputs.projectName)
compilerMaker.withCompiler(
inputs.workspace / Constants.workspaceDirName,
classesDir0,
buildClient,
logger
) { compiler =>
docCompilerMakerOpt match {
case None =>
build(
inputs = inputs,
options = options,
logger = logger,
buildClient = buildClient,
compiler = compiler,
docCompilerOpt = None,
crossBuilds = crossBuilds,
buildTests = buildTests,
partial = partial,
actionableDiagnostics = actionableDiagnostics
)
case Some(docCompilerMaker) =>
docCompilerMaker.withCompiler(
inputs.workspace / Constants.workspaceDirName,
classesDir0, // ???
buildClient,
logger
) { docCompiler =>
build(
inputs = inputs,
options = options,
logger = logger,
buildClient = buildClient,
compiler = compiler,
docCompilerOpt = Some(docCompiler),
crossBuilds = crossBuilds,
buildTests = buildTests,
partial = partial,
actionableDiagnostics = actionableDiagnostics
)
}
}
}
}
def validate(
logger: Logger,
options: BuildOptions
): Either[BuildException, Unit] = {
val (errors, otherDiagnostics) = options.validate.partition(_.severity == Severity.Error)
logger.log(otherDiagnostics)
if (errors.nonEmpty)
Left(CompositeBuildException(errors.map(new ValidationException(_))))
else
Right(())
}
def watch(
inputs: Inputs,
options: BuildOptions,
compilerMaker: ScalaCompilerMaker,
docCompilerMakerOpt: Option[ScalaCompilerMaker],
logger: Logger,
crossBuilds: Boolean,
buildTests: Boolean,
partial: Option[Boolean],
actionableDiagnostics: Option[Boolean],
postAction: () => Unit = () => ()
)(action: Either[BuildException, Builds] => Unit): Watcher = {
val buildClient = BloopBuildClient.create(
logger,
keepDiagnostics = options.internal.keepDiagnostics
)
val threads = BuildThreads.create()
val classesDir0 = classesRootDir(inputs.workspace, inputs.projectName)
val compiler = compilerMaker.create(
inputs.workspace / Constants.workspaceDirName,
classesDir0,
buildClient,
logger
)
val docCompilerOpt = docCompilerMakerOpt.map(_.create(
inputs.workspace / Constants.workspaceDirName,
classesDir0,
buildClient,
logger
))
var res: Either[BuildException, Builds] = null
def run(): Unit = {
try {
res = build(
inputs,
options,
logger,
buildClient,
compiler,
docCompilerOpt,
crossBuilds = crossBuilds,
buildTests = buildTests,
partial = partial,
actionableDiagnostics = actionableDiagnostics
)
action(res)
}
catch {
case NonFatal(e) =>
Util.printException(e)
}
postAction()
}
run()
val watcher = new Watcher(ListBuffer(), threads.fileWatcher, run(), compiler.shutdown())
def doWatch(): Unit = {
val elements: Seq[Inputs.Element] =
if (res == null) inputs.elements
else
res.map { builds =>
val mainElems = builds.main.inputs.elements
val testElems = builds.get(Scope.Test).map(_.inputs.elements).getOrElse(Nil)
(mainElems ++ testElems).distinct
}.getOrElse(inputs.elements)
for (elem <- elements) {
val depth = elem match {
case _: Inputs.SingleFile => -1
case _ => Int.MaxValue
}
val eventFilter: PathWatchers.Event => Boolean = elem match {
case d: Inputs.Directory =>
// Filtering event for directories, to ignore those related to the .bloop directory in particular
event =>
val p = os.Path(event.getTypedPath.getPath.toAbsolutePath)
val relPath = p.relativeTo(d.path)
val isHidden = relPath.segments.exists(_.startsWith("."))
def isScalaFile = relPath.last.endsWith(".sc") || relPath.last.endsWith(".scala")
def isJavaFile = relPath.last.endsWith(".java")
!isHidden && (isScalaFile || isJavaFile)
case _ => _ => true
}
val watcher0 = watcher.newWatcher()
elem match {
case d: Inputs.OnDisk =>
watcher0.register(d.path.toNIO, depth)
case _: Inputs.Virtual =>
}
watcher0.addObserver {
onChangeBufferedObserver { event =>
if (eventFilter(event))
watcher.schedule()
}
}
}
}
try doWatch()
catch {
case NonFatal(e) =>
watcher.dispose()
throw e
}
watcher
}
def releaseFlag(
options: BuildOptions,
compilerJvmVersionOpt: Option[Positioned[Int]],
logger: Logger
): Option[Int] = {
lazy val javaHome = options.javaHome()
if (compilerJvmVersionOpt.exists(javaHome.value.version > _.value)) {
logger.log(List(Diagnostic(
Diagnostic.Messages.bloopTooOld,
Severity.Warning,
javaHome.positions ++ compilerJvmVersionOpt.map(_.positions).getOrElse(Nil)
)))
None
}
else if (compilerJvmVersionOpt.exists(_.value == 8))
None
else if (
options.scalaOptions.scalacOptions.values.exists(
_.headOption.exists(_.value.value == "-release")
)
)
None
else
Some(javaHome.value.version)
}
/** Builds a Bloop project.
*
* @param inputs
* inputs to be included in the project
* @param sources
* sources to be included in the project
* @param generatedSources
* sources generated by Scala CLI as part of the build
* @param options
* build options
* @param compilerJvmVersionOpt
* compiler JVM version (optional)
* @param scope
* build scope for which the project is to be created
* @param logger
* logger
* @param maybeRecoverOnError
* a function handling [[BuildException]] instances, possibly recovering them; returns None on
* recovery, Some(e: BuildException) otherwise
* @return
* a bloop [[Project]]
*/
def buildProject(
inputs: Inputs,
sources: Sources,
generatedSources: Seq[GeneratedSource],
options: BuildOptions,
compilerJvmVersionOpt: Option[Positioned[Int]],
scope: Scope,
logger: Logger,
maybeRecoverOnError: BuildException => Option[BuildException] = e => Some(e)
): Either[BuildException, Project] = either {
val allSources = sources.paths.map(_._1) ++ generatedSources.map(_.generated)
val classesDir0 = classesDir(inputs.workspace, inputs.projectName, scope)
val scaladocDir = classesDir(inputs.workspace, inputs.projectName, scope, suffix = "-doc")
val artifacts = value(options.artifacts(logger, scope, maybeRecoverOnError))
val generateSemanticDbs = options.scalaOptions.generateSemanticDbs.getOrElse(false)
val releaseFlagVersion = releaseFlag(options, compilerJvmVersionOpt, logger).map(_.toString)
val scalaCompilerParamsOpt = artifacts.scalaOpt match {
case Some(scalaArtifacts) =>
val params = value(options.scalaParams).getOrElse {
sys.error(
"Should not happen (inconsistency between Scala parameters in BuildOptions and ScalaArtifacts)"
)
}
val pluginScalacOptions = scalaArtifacts.compilerPlugins.distinct.map {
case (_, _, path) =>
ScalacOpt(s"-Xplugin:$path")
}
val semanticDbScalacOptions =
if (generateSemanticDbs)
if (params.scalaVersion.startsWith("2."))
Seq(
"-Yrangepos",
"-P:semanticdb:failures:warning",
"-P:semanticdb:synthetics:on",
s"-P:semanticdb:sourceroot:${inputs.workspace}"
).map(ScalacOpt(_))
else
Seq(
"-Xsemanticdb",
"-sourceroot",
inputs.workspace.toString
).map(ScalacOpt(_))
else Nil
val sourceRootScalacOptions =
if (params.scalaVersion.startsWith("2.")) Nil
else Seq("-sourceroot", inputs.workspace.toString).map(ScalacOpt(_))
val scalaJsScalacOptions =
if (options.platform.value == Platform.JS && !params.scalaVersion.startsWith("2."))
Seq(ScalacOpt("-scalajs"))
else Nil
val scalacReleaseV =
// the -release flag is not supported for Scala 2.12.x < 2.12.5
if params.scalaVersion.asVersion < "2.12.5".asVersion then Nil
else
releaseFlagVersion
.map(v => List("-release", v).map(ScalacOpt(_)))
.getOrElse(Nil)
val scalapyOptions =
if (
params.scalaVersion.startsWith("2.13.") &&
options.notForBloopOptions.python.getOrElse(false)
)
Seq(ScalacOpt("-Yimports:java.lang,scala,scala.Predef,me.shadaj.scalapy"))
else Nil
val scalacOptions =
options.scalaOptions.scalacOptions.map(_.value) ++
pluginScalacOptions ++
semanticDbScalacOptions ++
sourceRootScalacOptions ++
scalaJsScalacOptions ++
scalacReleaseV ++
scalapyOptions
val compilerParams = ScalaCompilerParams(
scalaVersion = params.scalaVersion,
scalaBinaryVersion = params.scalaBinaryVersion,
scalacOptions = scalacOptions.toSeq.map(_.value),
compilerClassPath = scalaArtifacts.compilerClassPath
)
Some(compilerParams)
case None =>
None
}
val javacOptions = {
val semanticDbJavacOptions =
// FIXME Should this be in scalaOptions, now that we use it for javac stuff too?
if (generateSemanticDbs) {
// from https://github.com/scalameta/metals/blob/04405c0401121b372ea1971c361e05108fb36193/metals/src/main/scala/scala/meta/internal/metals/JavaInteractiveSemanticdb.scala#L137-L146
val compilerPackages = Seq(
"com.sun.tools.javac.api",
"com.sun.tools.javac.code",
"com.sun.tools.javac.model",
"com.sun.tools.javac.tree",
"com.sun.tools.javac.util"
)
val exports = compilerPackages.flatMap { pkg =>
Seq("-J--add-exports", s"-Jjdk.compiler/$pkg=ALL-UNNAMED")
}
Seq(
// does the path need to be escaped somehow?
s"-Xplugin:semanticdb -sourceroot:${inputs.workspace} -targetroot:javac-classes-directory"
) ++ exports
}
else
Nil
val javacReleaseV = releaseFlagVersion.map(v => List("--release", v)).getOrElse(Nil)
javacReleaseV ++ semanticDbJavacOptions ++ options.javaOptions.javacOptions
}
// `test` scope should contains class path to main scope
val mainClassesPath =
if (scope == Scope.Test)
List(classesDir(inputs.workspace, inputs.projectName, Scope.Main))
else Nil
value(validate(logger, options))
val fullClassPath = artifacts.compileClassPath ++
mainClassesPath ++
artifacts.javacPluginDependencies.map(_._3) ++
artifacts.extraJavacPlugins
val project = Project(
directory = inputs.workspace / Constants.workspaceDirName,
workspace = inputs.workspace,
classesDir = classesDir0,
scaladocDir = scaladocDir,
scalaCompiler = scalaCompilerParamsOpt,
scalaJsOptions =
if (options.platform.value == Platform.JS) Some(options.scalaJsOptions.config(logger))
else None,
scalaNativeOptions =
if (options.platform.value == Platform.Native)
Some(options.scalaNativeOptions.bloopConfig())
else None,
projectName = inputs.scopeProjectName(scope),
classPath = fullClassPath,
resolution = Some(Project.resolution(artifacts.detailedArtifacts)),
sources = allSources,
resourceDirs = sources.resourceDirs,
scope = scope,
javaHomeOpt = Option(options.javaHomeLocation().value),
javacOptions = javacOptions
)
project
}
def prepareBuild(
inputs: Inputs,
sources: Sources,
generatedSources: Seq[GeneratedSource],
options: BuildOptions,
compilerJvmVersionOpt: Option[Positioned[Int]],
scope: Scope,
compiler: ScalaCompiler,
logger: Logger,
buildClient: BloopBuildClient,
maybeRecoverOnError: BuildException => Option[BuildException] = e => Some(e)
): Either[BuildException, (os.Path, Option[ScalaParameters], Artifacts, Project, Boolean)] =
either {
val options0 =
if (sources.hasJava && !sources.hasScala)
options.copy(
scalaOptions = options.scalaOptions.copy(
scalaVersion = options.scalaOptions.scalaVersion.orElse {
Some(MaybeScalaVersion.none)
}
)
)
else
options
val params = value(options0.scalaParams)
val scopeParams =
if (scope == Scope.Main) Nil
else Seq(scope.name)
buildClient.setProjectParams(scopeParams ++ value(options0.projectParams))
val classesDir0 = classesDir(inputs.workspace, inputs.projectName, scope)
val artifacts = value(options0.artifacts(logger, scope, maybeRecoverOnError))
value(validate(logger, options0))
val project = value {
buildProject(
inputs,
sources,
generatedSources,
options0,
compilerJvmVersionOpt,
scope,
logger,
maybeRecoverOnError
)
}
val projectChanged = compiler.prepareProject(project, logger)
if (compiler.usesClassDir && projectChanged && os.isDir(classesDir0)) {
logger.debug(s"Clearing $classesDir0")
os.list(classesDir0).foreach { p =>
logger.debug(s"Removing $p")
try os.remove.all(p)
catch {
case ex: FileSystemException =>
logger.debug(s"Ignoring $ex while cleaning up $p")
}
}
}
(classesDir0, params, artifacts, project, projectChanged)