/
Defaults.scala
executable file
·4003 lines (3765 loc) · 153 KB
/
Defaults.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
/*
* sbt
* Copyright 2011 - 2018, Lightbend, Inc.
* Copyright 2008 - 2010, Mark Harrah
* Licensed under Apache License 2.0 (see LICENSE)
*/
package sbt
import java.io.{ File, PrintWriter }
import java.net.{ URI, URL, URLClassLoader }
import java.util.Optional
import java.util.concurrent.TimeUnit
import lmcoursier.CoursierDependencyResolution
import lmcoursier.definitions.{ Configuration => CConfiguration }
import org.apache.ivy.core.module.descriptor.ModuleDescriptor
import org.apache.ivy.core.module.id.ModuleRevisionId
import sbt.Def.{ Initialize, ScopedKey, Setting, SettingsDefinition }
import sbt.Keys._
import sbt.Project.{
inConfig,
inScope,
inTask,
richInitialize,
richInitializeTask,
richTaskSessionVar
}
import sbt.Scope.{ GlobalScope, ThisScope, fillTaskAxis }
import sbt.coursierint._
import sbt.internal.CommandStrings.ExportStream
import sbt.internal._
import sbt.internal.classpath.AlternativeZincUtil
import sbt.internal.inc.JavaInterfaceUtil._
import sbt.internal.inc.classpath.{ ClassLoaderCache, ClasspathFilter }
import sbt.internal.inc.{ ZincLmUtil, ZincUtil }
import sbt.internal.io.{ Source, WatchState }
import sbt.internal.librarymanagement.mavenint.{
PomExtraDependencyAttributes,
SbtPomExtraProperties
}
import sbt.internal.librarymanagement.{ CustomHttp => _, _ }
import sbt.internal.nio.{ CheckBuildSources, Globs }
import sbt.internal.server.{
Definition,
LanguageServerProtocol,
LanguageServerReporter,
ServerHandler
}
import sbt.internal.testing.TestLogger
import sbt.internal.util.Attributed.data
import sbt.internal.util.Types._
import sbt.internal.util._
import sbt.internal.util.complete._
import sbt.io.Path._
import sbt.io._
import sbt.io.syntax._
import sbt.librarymanagement.Artifact.{ DocClassifier, SourceClassifier }
import sbt.librarymanagement.Configurations.{
Compile,
CompilerPlugin,
IntegrationTest,
Provided,
Runtime,
Test,
names
}
import sbt.librarymanagement.CrossVersion.{ binarySbtVersion, binaryScalaVersion, partialVersion }
import sbt.librarymanagement._
import sbt.librarymanagement.ivy._
import sbt.librarymanagement.syntax._
import sbt.nio.FileStamp.Formats.seqPathFileStampJsonFormatter
import sbt.nio.Keys._
import sbt.nio.file.syntax._
import sbt.nio.file.{ FileTreeView, Glob, RecursiveGlob }
import sbt.nio.{ FileChanges, Watch }
import sbt.std.TaskExtra._
import sbt.testing.{ AnnotatedFingerprint, Framework, Runner, SubclassFingerprint }
import sbt.util.CacheImplicits._
import sbt.util.InterfaceUtil.{ toJavaFunction => f1 }
import sbt.util._
import sjsonnew._
import sjsonnew.support.scalajson.unsafe.Converter
import xsbti.CrossValue
import xsbti.compile.{ AnalysisContents, IncOptions, IncToolOptionsUtil }
import scala.collection.immutable.ListMap
import scala.concurrent.duration.FiniteDuration
import scala.util.control.NonFatal
import scala.xml.NodeSeq
// incremental compiler
import sbt.SlashSyntax0._
import sbt.internal.inc.{
Analysis,
AnalyzingCompiler,
FileValueCache,
Locate,
ManagedLoggedReporter,
MixedAnalyzingCompiler,
ScalaInstance
}
import xsbti.compile.{
ClassFileManagerType,
ClasspathOptionsUtil,
CompileAnalysis,
CompileOptions,
CompileOrder,
CompileResult,
CompilerCache,
Compilers,
DefinesClass,
Inputs,
MiniSetup,
PerClasspathEntryLookup,
PreviousResult,
Setup,
TransactionalManagerType
}
object Defaults extends BuildCommon {
final val CacheDirectoryName = "cache"
def configSrcSub(key: SettingKey[File]): Initialize[File] =
Def.setting {
(key in ThisScope.copy(config = Zero)).value / nameForSrc(configuration.value.name)
}
def nameForSrc(config: String) = if (config == Configurations.Compile.name) "main" else config
def prefix(config: String) = if (config == Configurations.Compile.name) "" else config + "-"
def lock(app: xsbti.AppConfiguration): xsbti.GlobalLock = LibraryManagement.lock(app)
def extractAnalysis[T](a: Attributed[T]): (T, CompileAnalysis) =
(a.data, a.metadata get Keys.analysis getOrElse Analysis.Empty)
def analysisMap[T](cp: Seq[Attributed[T]]): T => Option[CompileAnalysis] = {
val m = (for (a <- cp; an <- a.metadata get Keys.analysis) yield (a.data, an)).toMap
m.get _
}
private[sbt] def globalDefaults(ss: Seq[Setting[_]]): Seq[Setting[_]] =
Def.defaultSettings(inScope(GlobalScope)(ss))
def buildCore: Seq[Setting[_]] = thisBuildCore ++ globalCore
def thisBuildCore: Seq[Setting[_]] =
inScope(GlobalScope.copy(project = Select(ThisBuild)))(
Seq(
managedDirectory := baseDirectory.value / "lib_managed"
)
)
private[sbt] lazy val globalCore: Seq[Setting[_]] = globalDefaults(
defaultTestTasks(test) ++ defaultTestTasks(testOnly) ++ defaultTestTasks(testQuick) ++ Seq(
excludeFilter :== HiddenFileFilter,
fileInputs :== Nil,
fileInputIncludeFilter :== AllPassFilter.toNio,
fileInputExcludeFilter :== DirectoryFilter.toNio || HiddenFileFilter,
fileOutputIncludeFilter :== AllPassFilter.toNio,
fileOutputExcludeFilter :== NothingFilter.toNio,
inputFileStamper :== sbt.nio.FileStamper.Hash,
outputFileStamper :== sbt.nio.FileStamper.LastModified,
onChangedBuildSource :== sbt.nio.Keys.WarnOnSourceChanges,
clean := { () },
unmanagedFileStampCache :=
state.value.get(persistentFileStampCache).getOrElse(new sbt.nio.FileStamp.Cache),
managedFileStampCache := new sbt.nio.FileStamp.Cache,
) ++ globalIvyCore ++ globalJvmCore ++ Watch.defaults
) ++ globalSbtCore
private[sbt] lazy val globalJvmCore: Seq[Setting[_]] =
Seq(
compilerCache := state.value get Keys.stateCompilerCache getOrElse CompilerCache.fresh,
sourcesInBase :== true,
autoAPIMappings := false,
apiMappings := Map.empty,
autoScalaLibrary :== true,
managedScalaInstance :== true,
classpathEntryDefinesClass :== FileValueCache(Locate.definesClass _).get,
traceLevel in run :== 0,
traceLevel in runMain :== 0,
traceLevel in bgRun :== 0,
traceLevel in fgRun :== 0,
traceLevel in console :== Int.MaxValue,
traceLevel in consoleProject :== Int.MaxValue,
autoCompilerPlugins :== true,
scalaHome :== None,
apiURL := None,
javaHome :== None,
discoveredJavaHomes := CrossJava.discoverJavaHomes,
javaHomes :== ListMap.empty,
fullJavaHomes := CrossJava.expandJavaHomes(discoveredJavaHomes.value ++ javaHomes.value),
testForkedParallel :== false,
javaOptions :== Nil,
sbtPlugin :== false,
isMetaBuild :== false,
reresolveSbtArtifacts :== false,
crossPaths :== true,
sourcePositionMappers :== Nil,
artifactClassifier in packageSrc :== Some(SourceClassifier),
artifactClassifier in packageDoc :== Some(DocClassifier),
includeFilter :== NothingFilter,
includeFilter in unmanagedSources :== ("*.java" | "*.scala"),
includeFilter in unmanagedJars :== "*.jar" | "*.so" | "*.dll" | "*.jnilib" | "*.zip",
includeFilter in unmanagedResources :== AllPassFilter,
bgList := { bgJobService.value.jobs },
ps := psTask.value,
bgStop := bgStopTask.evaluated,
bgWaitFor := bgWaitForTask.evaluated,
bgCopyClasspath :== true,
allowZombieClassLoaders :== !SysProp.closeClassLoaders,
)
private[sbt] lazy val globalIvyCore: Seq[Setting[_]] =
Seq(
internalConfigurationMap :== Configurations.internalMap _,
credentials :== Nil,
exportJars :== false,
trackInternalDependencies :== TrackLevel.TrackAlways,
exportToInternal :== TrackLevel.TrackAlways,
useCoursier :== SysProp.defaultUseCoursier,
retrieveManaged :== false,
retrieveManagedSync :== false,
configurationsToRetrieve :== None,
scalaOrganization :== ScalaArtifacts.Organization,
scalaArtifacts :== ScalaArtifacts.Artifacts,
sbtResolver := {
val v = sbtVersion.value
if (v.endsWith("-SNAPSHOT") || v.contains("-bin-")) Classpaths.sbtMavenSnapshots
else Resolver.DefaultMavenRepository
},
sbtResolvers := {
// TODO: Remove Classpaths.typesafeReleases for sbt 2.x
// We need to keep it around for sbt 1.x to cross build plugins with sbt 0.13 - https://github.com/sbt/sbt/issues/4698
Vector(sbtResolver.value, Classpaths.sbtPluginReleases, Classpaths.typesafeReleases)
},
crossVersion :== Disabled(),
buildDependencies := Classpaths.constructBuildDependencies.value,
version :== "0.1.0-SNAPSHOT",
classpathTypes :== Set("jar", "bundle", "maven-plugin", "test-jar") ++ CustomPomParser.JarPackagings,
artifactClassifier :== None,
checksums := Classpaths.bootChecksums(appConfiguration.value),
conflictManager := ConflictManager.default,
CustomHttp.okhttpClientBuilder :== CustomHttp.defaultHttpClientBuilder,
CustomHttp.okhttpClient := CustomHttp.okhttpClientBuilder.value.build,
pomExtra :== NodeSeq.Empty,
pomPostProcess :== idFun,
pomAllRepositories :== false,
pomIncludeRepository :== Classpaths.defaultRepositoryFilter,
updateOptions := UpdateOptions(),
forceUpdatePeriod :== None,
// coursier settings
csrExtraCredentials :== Nil,
csrLogger := LMCoursier.coursierLoggerTask.value,
csrCacheDirectory :== LMCoursier.defaultCacheLocation,
csrMavenProfiles :== Set.empty,
csrReconciliations :== LMCoursier.relaxedForAllModules,
)
/** Core non-plugin settings for sbt builds. These *must* be on every build or the sbt engine will fail to run at all. */
private[sbt] lazy val globalSbtCore: Seq[Setting[_]] = globalDefaults(
Seq(
outputStrategy :== None, // TODO - This might belong elsewhere.
buildStructure := Project.structure(state.value),
settingsData := buildStructure.value.data,
aggregate in checkBuildSources :== false,
aggregate in checkBuildSources / changedInputFiles := false,
checkBuildSources / Continuous.dynamicInputs := None,
checkBuildSources / fileInputs := CheckBuildSources.buildSourceFileInputs.value,
checkBuildSources := CheckBuildSources.needReloadImpl.value,
fileCacheSize := "128M",
trapExit :== true,
connectInput :== false,
cancelable :== true,
taskCancelStrategy := { state: State =>
if (cancelable.value) TaskCancellationStrategy.Signal
else TaskCancellationStrategy.Null
},
envVars :== Map.empty,
sbtVersion := appConfiguration.value.provider.id.version,
sbtBinaryVersion := binarySbtVersion(sbtVersion.value),
// `pluginCrossBuild` scoping is based on sbt-cross-building plugin.
// The idea here is to be able to define a `sbtVersion in pluginCrossBuild`, which
// directs the dependencies of the plugin to build to the specified sbt plugin version.
sbtVersion in pluginCrossBuild := sbtVersion.value,
onLoad := idFun[State],
onUnload := idFun[State],
onUnload := { s =>
try onUnload.value(s)
finally IO.delete(taskTemporaryDirectory.value)
},
extraLoggers :== { _ =>
Nil
},
watchSources :== Nil, // Although this is deprecated, it can't be removed or it breaks += for legacy builds.
skip :== false,
taskTemporaryDirectory := { val dir = IO.createTemporaryDirectory; dir.deleteOnExit(); dir },
onComplete := {
val tempDirectory = taskTemporaryDirectory.value
() => Clean.deleteContents(tempDirectory, _ => false)
},
turbo :== SysProp.turbo,
useSuperShell := { if (insideCI.value) false else SysProp.supershell },
progressReports := {
val rs = EvaluateTask.taskTimingProgress.toVector ++ EvaluateTask.taskTraceEvent.toVector
rs map { Keys.TaskProgress(_) }
},
progressState := {
if ((ThisBuild / useSuperShell).value) Some(new ProgressState(SysProp.supershellBlankZone))
else None
},
Previous.cache := new Previous(
Def.streamsManagerKey.value,
Previous.references.value.getReferences
),
Previous.references :== new Previous.References,
concurrentRestrictions := defaultRestrictions.value,
parallelExecution :== true,
fileTreeView :== FileTreeView.default,
Continuous.dynamicInputs := Continuous.dynamicInputsImpl.value,
logBuffered :== false,
commands :== Nil,
showSuccess :== true,
showTiming :== true,
timingFormat :== Aggregation.defaultFormat,
aggregate :== true,
maxErrors :== 100,
fork :== false,
initialize :== {},
templateResolverInfos :== Nil,
forcegc :== sys.props
.get("sbt.task.forcegc")
.map(java.lang.Boolean.parseBoolean)
.getOrElse(GCUtil.defaultForceGarbageCollection),
minForcegcInterval :== GCUtil.defaultMinForcegcInterval,
interactionService :== CommandLineUIService,
autoStartServer := true,
serverHost := "127.0.0.1",
serverPort := 5000 + (Hash
.toHex(Hash(appConfiguration.value.baseDirectory.toString))
.## % 1000),
serverConnectionType := ConnectionType.Local,
serverAuthentication := {
if (serverConnectionType.value == ConnectionType.Tcp) Set(ServerAuthentication.Token)
else Set()
},
serverHandlers :== Nil,
fullServerHandlers := {
(Vector(LanguageServerProtocol.handler)
++ serverHandlers.value
++ Vector(ServerHandler.fallback))
},
insideCI :== sys.env.contains("BUILD_NUMBER") ||
sys.env.contains("CI") || SysProp.ci,
// watch related settings
pollInterval :== Watch.defaultPollInterval,
)
)
def defaultTestTasks(key: Scoped): Seq[Setting[_]] =
inTask(key)(
Seq(
tags := Seq(Tags.Test -> 1),
logBuffered := true
)
)
// TODO: This should be on the new default settings for a project.
def projectCore: Seq[Setting[_]] = Seq(
name := thisProject.value.id,
logManager := LogManager.defaults(extraLoggers.value, StandardMain.console),
onLoadMessage := (onLoadMessage or
Def.setting {
s"Set current project to ${name.value} (in build ${thisProjectRef.value.build})"
}).value
)
// Appended to JvmPlugin.projectSettings
def paths: Seq[Setting[_]] = Seq(
baseDirectory := thisProject.value.base,
target := baseDirectory.value / "target",
historyPath := (historyPath or target(t => Option(t / ".history"))).value,
sourceDirectory := baseDirectory.value / "src",
sourceManaged := crossTarget.value / "src_managed",
resourceManaged := crossTarget.value / "resource_managed",
// Adds subproject build.sbt files to the global list of build files to monitor
Scope.Global / checkBuildSources / fileInputs += baseDirectory.value.toGlob / "*.sbt"
)
lazy val configPaths = sourceConfigPaths ++ resourceConfigPaths ++ outputConfigPaths
lazy val sourceConfigPaths = Seq(
sourceDirectory := configSrcSub(sourceDirectory).value,
sourceManaged := configSrcSub(sourceManaged).value,
scalaSource := sourceDirectory.value / "scala",
javaSource := sourceDirectory.value / "java",
unmanagedSourceDirectories := {
makeCrossSources(
scalaSource.value,
javaSource.value,
scalaBinaryVersion.value,
crossPaths.value
) ++
makePluginCrossSources(
sbtPlugin.value,
scalaSource.value,
(sbtBinaryVersion in pluginCrossBuild).value,
crossPaths.value
)
},
unmanagedSources / fileInputs := {
val include = (includeFilter in unmanagedSources).value
val filter = (excludeFilter in unmanagedSources).value match {
// Hidden files are already filtered out by the FileStamps method
case NothingFilter | HiddenFileFilter => include
case exclude => include -- exclude
}
val baseSources =
if (sourcesInBase.value) Globs(baseDirectory.value.toPath, recursive = false, filter) :: Nil
else Nil
unmanagedSourceDirectories.value
.map(d => Globs(d.toPath, recursive = true, filter)) ++ baseSources
},
unmanagedSources := (unmanagedSources / inputFileStamps).value.map(_._1.toFile),
managedSourceDirectories := Seq(sourceManaged.value),
managedSources := {
val stamper = inputFileStamper.value
val cache = managedFileStampCache.value
val res = generate(sourceGenerators).value
res.foreach { f =>
cache.putIfAbsent(f.toPath, stamper)
}
res
},
managedSourcePaths / outputFileStamper := sbt.nio.FileStamper.Hash,
managedSourcePaths := managedSources.value.map(_.toPath),
sourceGenerators :== Nil,
sourceDirectories := Classpaths
.concatSettings(unmanagedSourceDirectories, managedSourceDirectories)
.value,
sources := Classpaths.concatDistinct(unmanagedSources, managedSources).value
)
lazy val resourceConfigPaths = Seq(
resourceDirectory := sourceDirectory.value / "resources",
resourceManaged := configSrcSub(resourceManaged).value,
unmanagedResourceDirectories := Seq(resourceDirectory.value),
managedResourceDirectories := Seq(resourceManaged.value),
resourceDirectories := Classpaths
.concatSettings(unmanagedResourceDirectories, managedResourceDirectories)
.value,
unmanagedResources / fileInputs := {
val include = (includeFilter in unmanagedResources).value
val filter = (excludeFilter in unmanagedResources).value match {
// Hidden files are already filtered out by the FileStamps method
case NothingFilter | HiddenFileFilter => include
case exclude => include -- exclude
}
unmanagedResourceDirectories.value.map(d => Globs(d.toPath, recursive = true, filter))
},
unmanagedResources := (unmanagedResources / inputFileStamps).value.map(_._1.toFile),
resourceGenerators :== Nil,
resourceGenerators += Def.task {
PluginDiscovery.writeDescriptors(discoveredSbtPlugins.value, resourceManaged.value)
},
managedResources := generate(resourceGenerators).value,
resources := Classpaths.concat(managedResources, unmanagedResources).value
)
// This exists for binary compatibility and probably never should have been public.
def addBaseSources: Seq[Def.Setting[Task[Seq[File]]]] = Nil
lazy val outputConfigPaths = Seq(
classDirectory := crossTarget.value / (prefix(configuration.value.name) + "classes"),
semanticdbTargetRoot := crossTarget.value / (prefix(configuration.value.name) + "meta"),
target in doc := crossTarget.value / (prefix(configuration.value.name) + "api")
)
// This is included into JvmPlugin.projectSettings
def compileBase = inTask(console)(compilersSetting :: Nil) ++ compileBaseGlobal ++ Seq(
incOptions := incOptions.value
.withClassfileManagerType(
Option(
TransactionalManagerType
.of(crossTarget.value / "classes.bak", sbt.util.Logger.Null): ClassFileManagerType
).toOptional
),
scalaInstance := scalaInstanceTask.value,
crossVersion := (if (crossPaths.value) CrossVersion.binary else CrossVersion.disabled),
sbtBinaryVersion in pluginCrossBuild := binarySbtVersion(
(sbtVersion in pluginCrossBuild).value
),
crossSbtVersions := Vector((sbtVersion in pluginCrossBuild).value),
crossTarget := makeCrossTarget(
target.value,
scalaBinaryVersion.value,
(sbtBinaryVersion in pluginCrossBuild).value,
sbtPlugin.value,
crossPaths.value
),
clean := {
val _ = clean.value
IvyActions.cleanCachedResolutionCache(ivyModule.value, streams.value.log)
},
scalaCompilerBridgeBinaryJar := None,
scalaCompilerBridgeSource := ZincLmUtil.getDefaultBridgeModule(scalaVersion.value),
)
// must be a val: duplication detected by object identity
private[this] lazy val compileBaseGlobal: Seq[Setting[_]] = globalDefaults(
Seq(
incOptions := IncOptions.of(),
classpathOptions :== ClasspathOptionsUtil.boot,
classpathOptions in console :== ClasspathOptionsUtil.repl,
compileOrder :== CompileOrder.Mixed,
javacOptions :== Nil,
scalacOptions :== Nil,
scalaVersion := appConfiguration.value.provider.scalaProvider.version,
derive(crossScalaVersions := Seq(scalaVersion.value)),
derive(compilersSetting),
derive(scalaBinaryVersion := binaryScalaVersion(scalaVersion.value))
)
)
def makeCrossSources(
scalaSrcDir: File,
javaSrcDir: File,
sv: String,
cross: Boolean
): Seq[File] = {
if (cross)
Seq(scalaSrcDir.getParentFile / s"${scalaSrcDir.name}-$sv", scalaSrcDir, javaSrcDir)
else
Seq(scalaSrcDir, javaSrcDir)
}
def makePluginCrossSources(
isPlugin: Boolean,
scalaSrcDir: File,
sbtBinaryV: String,
cross: Boolean
): Seq[File] = {
if (cross && isPlugin)
Vector(scalaSrcDir.getParentFile / s"${scalaSrcDir.name}-sbt-$sbtBinaryV")
else Vector()
}
def makeCrossTarget(t: File, sv: String, sbtv: String, plugin: Boolean, cross: Boolean): File = {
val scalaBase = if (cross) t / ("scala-" + sv) else t
if (plugin) scalaBase / ("sbt-" + sbtv) else scalaBase
}
def compilersSetting = {
compilers := {
val st = state.value
val g = BuildPaths.getGlobalBase(st)
val zincDir = BuildPaths.getZincDirectory(st, g)
val app = appConfiguration.value
val launcher = app.provider.scalaProvider.launcher
val dr = scalaCompilerBridgeDependencyResolution.value
val scalac =
scalaCompilerBridgeBinaryJar.value match {
case Some(jar) =>
AlternativeZincUtil.scalaCompiler(
scalaInstance = scalaInstance.value,
classpathOptions = classpathOptions.value,
compilerBridgeJar = jar,
classLoaderCache = st.get(BasicKeys.classLoaderCache)
)
case _ =>
ZincLmUtil.scalaCompiler(
scalaInstance = scalaInstance.value,
classpathOptions = classpathOptions.value,
globalLock = launcher.globalLock,
componentProvider = app.provider.components,
secondaryCacheDir = Option(zincDir),
dependencyResolution = dr,
compilerBridgeSource = scalaCompilerBridgeSource.value,
scalaJarsTarget = zincDir,
classLoaderCache = st.get(BasicKeys.classLoaderCache),
log = streams.value.log
)
}
val compilers = ZincUtil.compilers(
instance = scalaInstance.value,
classpathOptions = classpathOptions.value,
javaHome = javaHome.value,
scalac
)
val classLoaderCache = state.value.classLoaderCache
if (java.lang.Boolean.getBoolean("sbt.disable.interface.classloader.cache")) compilers
else {
compilers.withScalac(
compilers.scalac match {
case x: AnalyzingCompiler => x.withClassLoaderCache(classLoaderCache)
case x => x
}
)
}
}
}
def defaultCompileSettings: Seq[Setting[_]] =
globalDefaults(enableBinaryCompileAnalysis := true)
lazy val configTasks: Seq[Setting[_]] = docTaskSettings(doc) ++ inTask(compile)(
compileInputsSettings
) ++ configGlobal ++ defaultCompileSettings ++ compileAnalysisSettings ++ Seq(
compileOutputs := {
import scala.collection.JavaConverters._
val classFiles =
manipulateBytecode.value.analysis.readStamps.getAllProductStamps.keySet.asScala
classFiles.toSeq.map(_.toPath) :+ compileAnalysisFileTask.value.toPath
},
compileOutputs := compileOutputs.triggeredBy(compile).value,
clean := (compileOutputs / clean).value,
compile := compileTask.value,
internalDependencyConfigurations := InternalDependencies.configurations.value,
manipulateBytecode := compileIncremental.value,
compileIncremental := (compileIncrementalTask tag (Tags.Compile, Tags.CPU)).value,
printWarnings := printWarningsTask.value,
compileAnalysisFilename := {
// Here, if the user wants cross-scala-versioning, we also append it
// to the analysis cache, so we keep the scala versions separated.
val binVersion = scalaBinaryVersion.value
val extra =
if (crossPaths.value) s"_$binVersion"
else ""
s"inc_compile$extra.zip"
},
externalHooks := {
import sjsonnew.BasicJsonProtocol.mapFormat
val currentInputs =
(unmanagedSources / inputFileStamps).value ++ (managedSourcePaths / outputFileStamps).value
val sv = scalaVersion.value
val previousInputs = compileSourceFileInputs.previous.flatMap(_.get(sv))
val inputChanges = previousInputs
.map(sbt.nio.Settings.changedFiles(_, currentInputs))
.getOrElse(FileChanges.noPrevious(currentInputs.map(_._1)))
val currentOutputs = (dependencyClasspathFiles / outputFileStamps).value
val previousOutputs = compileBinaryFileInputs.previous.flatMap(_.get(sv))
val outputChanges = previousOutputs
.map(sbt.nio.Settings.changedFiles(_, currentOutputs))
.getOrElse(FileChanges.noPrevious(currentOutputs.map(_._1)))
ExternalHooks.default.value(inputChanges, outputChanges, fileTreeView.value)
},
compileSourceFileInputs := {
import sjsonnew.BasicJsonProtocol.mapFormat
compile.value // ensures the inputFileStamps previous value is only set if compile succeeds.
val version = scalaVersion.value
val versions = crossScalaVersions.value.toSet + version
val prev: Map[String, Seq[(java.nio.file.Path, sbt.nio.FileStamp)]] =
compileSourceFileInputs.previous.map(_.filterKeys(versions)).getOrElse(Map.empty)
prev + (version ->
((unmanagedSources / inputFileStamps).value ++ (managedSourcePaths / outputFileStamps).value))
},
compileSourceFileInputs := compileSourceFileInputs.triggeredBy(compile).value,
compileBinaryFileInputs := {
import sjsonnew.BasicJsonProtocol.mapFormat
compile.value // ensures the inputFileStamps previous value is only set if compile succeeds.
val version = scalaVersion.value
val versions = crossScalaVersions.value.toSet + version
val prev: Map[String, Seq[(java.nio.file.Path, sbt.nio.FileStamp)]] =
compileBinaryFileInputs.previous.map(_.filterKeys(versions)).getOrElse(Map.empty)
prev + (version -> (dependencyClasspathFiles / outputFileStamps).value)
},
compileBinaryFileInputs := compileBinaryFileInputs.triggeredBy(compile).value,
incOptions := { incOptions.value.withExternalHooks(externalHooks.value) },
compileIncSetup := compileIncSetupTask.value,
console := consoleTask.value,
collectAnalyses := Definition.collectAnalysesTask.map(_ => ()).value,
consoleQuick := consoleQuickTask.value,
discoveredMainClasses := (compile map discoverMainClasses storeAs discoveredMainClasses xtriggeredBy compile).value,
discoveredSbtPlugins := discoverSbtPluginNames.value,
// This fork options, scoped to the configuration is used for tests
forkOptions := forkOptionsTask.value,
selectMainClass := mainClass.value orElse askForMainClass(discoveredMainClasses.value),
mainClass in run := (selectMainClass in run).value,
mainClass := pickMainClassOrWarn(discoveredMainClasses.value, streams.value.log),
runMain := foregroundRunMainTask.evaluated,
run := foregroundRunTask.evaluated,
fgRun := runTask(fullClasspath, mainClass in run, runner in run).evaluated,
fgRunMain := runMainTask(fullClasspath, runner in run).evaluated,
copyResources := copyResourcesTask.value,
// note that we use the same runner and mainClass as plain run
mainBgRunMainTaskForConfig(This),
mainBgRunTaskForConfig(This)
) ++ inTask(run)(runnerSettings ++ newRunnerSettings)
private[this] lazy val configGlobal = globalDefaults(
Seq(
initialCommands :== "",
cleanupCommands :== "",
asciiGraphWidth :== 40
)
)
lazy val projectTasks: Seq[Setting[_]] = Seq(
cleanFiles := cleanFilesTask.value,
cleanKeepFiles := Vector.empty,
cleanKeepGlobs := historyPath.value.map(_.toGlob).toSeq,
clean := Def.taskDyn(Clean.task(resolvedScoped.value.scope, full = true)).value,
consoleProject := consoleProjectTask.value,
transitiveDynamicInputs := SettingsGraph.task.value,
) ++ sbt.internal.DeprecatedContinuous.taskDefinitions
def generate(generators: SettingKey[Seq[Task[Seq[File]]]]): Initialize[Task[Seq[File]]] =
generators { _.join.map(_.flatten) }
@deprecated(
"The watchTransitiveSourcesTask is used only for legacy builds and will be removed in a future version of sbt.",
"1.3.0"
)
def watchTransitiveSourcesTask: Initialize[Task[Seq[Source]]] =
watchTransitiveSourcesTaskImpl(watchSources)
private def watchTransitiveSourcesTaskImpl(
key: TaskKey[Seq[Source]]
): Initialize[Task[Seq[Source]]] = {
import ScopeFilter.Make.{ inDependencies => inDeps, _ }
val selectDeps = ScopeFilter(inAggregates(ThisProject) || inDeps(ThisProject))
val allWatched = (key ?? Nil).all(selectDeps)
Def.task { allWatched.value.flatten }
}
def transitiveUpdateTask: Initialize[Task[Seq[UpdateReport]]] = {
import ScopeFilter.Make.{ inDependencies => inDeps, _ }
val selectDeps = ScopeFilter(inDeps(ThisProject, includeRoot = false))
val allUpdates = update.?.all(selectDeps)
// If I am a "build" (a project inside project/) then I have a globalPluginUpdate.
Def.task { allUpdates.value.flatten ++ globalPluginUpdate.?.value }
}
@deprecated("This is no longer used to implement continuous execution", "1.3.0")
def watchSetting: Initialize[Watched] =
Def.setting {
val getService = watchService.value
val interval = pollInterval.value
val _antiEntropy = watchAntiEntropy.value
val base = thisProjectRef.value
val msg = watchingMessage.?.value.getOrElse(Watched.defaultWatchingMessage)
val trigMsg = triggeredMessage.?.value.getOrElse(Watched.defaultTriggeredMessage)
new Watched {
val scoped = watchTransitiveSources in base
val key = scoped.scopedKey
override def antiEntropy: FiniteDuration = _antiEntropy
override def pollInterval: FiniteDuration = interval
override def watchingMessage(s: WatchState) = msg(s)
override def triggeredMessage(s: WatchState) = trigMsg(s)
override def watchService() = getService()
override def watchSources(s: State) =
EvaluateTask(Project structure s, key, s, base) match {
case Some((_, Value(ps))) => ps
case Some((_, Inc(i))) => throw i
case None => sys.error("key not found: " + Def.displayFull(key))
}
}
}
def scalaInstanceTask: Initialize[Task[ScalaInstance]] = Def.taskDyn {
// if this logic changes, ensure that `unmanagedScalaInstanceOnly` and `update` are changed
// appropriately to avoid cycles
scalaHome.value match {
case Some(h) => scalaInstanceFromHome(h)
case None =>
val scalaProvider = appConfiguration.value.provider.scalaProvider
val version = scalaVersion.value
if (version == scalaProvider.version) // use the same class loader as the Scala classes used by sbt
Def.task {
val allJars = scalaProvider.jars
val libraryJars = allJars.filter(_.getName == "scala-library.jar")
allJars.filter(_.getName == "scala-compiler.jar") match {
case Array(compilerJar) if libraryJars.nonEmpty =>
val cache = state.value.classLoaderCache
mkScalaInstance(version, allJars, libraryJars, compilerJar, cache)
case _ => ScalaInstance(version, scalaProvider)
}
} else
scalaInstanceFromUpdate
}
}
// Returns the ScalaInstance only if it was not constructed via `update`
// This is necessary to prevent cycles between `update` and `scalaInstance`
private[sbt] def unmanagedScalaInstanceOnly: Initialize[Task[Option[ScalaInstance]]] =
Def.taskDyn {
if (scalaHome.value.isDefined) Def.task(Some(scalaInstance.value)) else Def.task(None)
}
private[this] def noToolConfiguration(autoInstance: Boolean): String = {
val pre = "Missing Scala tool configuration from the 'update' report. "
val post =
if (autoInstance)
"'scala-tool' is normally added automatically, so this may indicate a bug in sbt or you may be removing it from ivyConfigurations, for example."
else
"Explicitly define scalaInstance or scalaHome or include Scala dependencies in the 'scala-tool' configuration."
pre + post
}
def scalaInstanceFromUpdate: Initialize[Task[ScalaInstance]] = Def.task {
val toolReport = update.value.configuration(Configurations.ScalaTool) getOrElse
sys.error(noToolConfiguration(managedScalaInstance.value))
def files(id: String) =
for {
m <- toolReport.modules if m.module.name == id;
(art, file) <- m.artifacts if art.`type` == Artifact.DefaultType
} yield file
def file(id: String) = files(id).headOption getOrElse sys.error(s"Missing ${id}.jar")
val allJars = toolReport.modules.flatMap(_.artifacts.map(_._2))
val libraryJar = file(ScalaArtifacts.LibraryID)
val compilerJar = file(ScalaArtifacts.CompilerID)
mkScalaInstance(
scalaVersion.value,
allJars,
Array(libraryJar),
compilerJar,
state.value.classLoaderCache
)
}
private[this] def mkScalaInstance(
version: String,
allJars: Seq[File],
libraryJars: Array[File],
compilerJar: File,
classLoaderCache: ClassLoaderCache,
): ScalaInstance = {
val allJarsDistinct = allJars.distinct
val libraryLoader = classLoaderCache(libraryJars.toList)
class ScalaLoader
extends URLClassLoader(allJarsDistinct.map(_.toURI.toURL).toArray, libraryLoader)
val fullLoader = classLoaderCache.cachedCustomClassloader(
allJarsDistinct.toList,
() => new ScalaLoader
)
new ScalaInstance(
version,
fullLoader,
libraryLoader,
libraryJars,
compilerJar,
allJarsDistinct.toArray,
Some(version)
)
}
def scalaInstanceFromHome(dir: File): Initialize[Task[ScalaInstance]] = Def.task {
val dummy = ScalaInstance(dir)(state.value.classLoaderCache.apply)
Seq(dummy.loader, dummy.loaderLibraryOnly).foreach {
case a: AutoCloseable => a.close()
case _ =>
}
mkScalaInstance(
dummy.version,
dummy.allJars,
dummy.libraryJars,
dummy.compilerJar,
state.value.classLoaderCache
)
}
private[this] def testDefaults =
Defaults.globalDefaults(
Seq(
testFrameworks :== {
import sbt.TestFrameworks._
Seq(ScalaCheck, Specs2, Specs, ScalaTest, JUnit)
},
testListeners :== Nil,
testOptions :== Nil,
testResultLogger :== TestResultLogger.Default,
testFilter in testOnly :== (selectedFilter _)
)
)
lazy val testTasks
: Seq[Setting[_]] = testTaskOptions(test) ++ testTaskOptions(testOnly) ++ testTaskOptions(
testQuick
) ++ testDefaults ++ Seq(
testLoader := ClassLoaders.testTask.value,
loadedTestFrameworks := {
val loader = testLoader.value
val log = streams.value.log
testFrameworks.value.flatMap(f => f.create(loader, log).map(x => (f, x)).toIterable).toMap
},
definedTests := detectTests.value,
definedTestNames := (definedTests map (_.map(_.name).distinct) storeAs definedTestNames triggeredBy compile).value,
testFilter in testQuick := testQuickFilter.value,
executeTests := (
Def.taskDyn {
allTestGroupsTask(
(streams in test).value,
loadedTestFrameworks.value,
testLoader.value,
(testGrouping in test).value,
(testExecution in test).value,
(fullClasspath in test).value,
testForkedParallel.value,
(javaOptions in test).value,
(classLoaderLayeringStrategy).value,
projectId = s"${thisProject.value.id} / ",
)
}
).value,
// ((streams in test, loadedTestFrameworks, testLoader, testGrouping in test, testExecution in test, fullClasspath in test, javaHome in test, testForkedParallel, javaOptions in test) flatMap allTestGroupsTask).value,
testResultLogger in (Test, test) :== TestResultLogger.SilentWhenNoTests, // https://github.com/sbt/sbt/issues/1185
test := {
val trl = (testResultLogger in (Test, test)).value
val taskName = Project.showContextKey(state.value).show(resolvedScoped.value)
try trl.run(streams.value.log, executeTests.value, taskName)
finally close(testLoader.value)
},
testOnly := {
try inputTests(testOnly).evaluated
finally close(testLoader.value)
},
testQuick := {
try inputTests(testQuick).evaluated
finally close(testLoader.value)
}
)
private def close(sbtLoader: ClassLoader): Unit = sbtLoader match {
case u: AutoCloseable => u.close()
case c: ClasspathFilter => c.close()
case _ =>
}
/**
* A scope whose task axis is set to Zero.
*/
lazy val TaskZero: Scope = ThisScope.copy(task = Zero)
lazy val TaskGlobal: Scope = TaskZero
/**
* A scope whose configuration axis is set to Zero.
*/
lazy val ConfigZero: Scope = ThisScope.copy(config = Zero)
lazy val ConfigGlobal: Scope = ConfigZero
def testTaskOptions(key: Scoped): Seq[Setting[_]] =
inTask(key)(
Seq(
testListeners := {
TestLogger.make(
streams.value.log,
closeableTestLogger(
streamsManager.value,
test in resolvedScoped.value.scope,
logBuffered.value
)
) +:
new TestStatusReporter(succeededFile(streams.in(test).value.cacheDirectory)) +:
testListeners.in(TaskZero).value
},
testOptions := Tests.Listeners(testListeners.value) +: (testOptions in TaskZero).value,
testExecution := testExecutionTask(key).value
)
) ++ inScope(GlobalScope)(
Seq(
derive(testGrouping := singleTestGroupDefault.value)
)
)
private[this] def closeableTestLogger(manager: Streams, baseKey: Scoped, buffered: Boolean)(
tdef: TestDefinition
): TestLogger.PerTest = {
val scope = baseKey.scope
val extra = scope.extra match { case Select(x) => x; case _ => AttributeMap.empty }
val key = ScopedKey(scope.copy(extra = Select(testExtra(extra, tdef))), baseKey.key)
val s = manager(key)
new TestLogger.PerTest(s.log, () => s.close(), buffered)
}
def testExtra(extra: AttributeMap, tdef: TestDefinition): AttributeMap = {
val mod = tdef.fingerprint match {
case f: SubclassFingerprint => f.isModule
case f: AnnotatedFingerprint => f.isModule
case _ => false
}
extra.put(name.key, tdef.name).put(isModule, mod)
}
def singleTestGroup(key: Scoped): Initialize[Task[Seq[Tests.Group]]] =
inTask(key, singleTestGroupDefault)
def singleTestGroupDefault: Initialize[Task[Seq[Tests.Group]]] = Def.task {
val tests = definedTests.value
val fk = fork.value
val opts = forkOptions.value
Seq(new Tests.Group("<default>", tests, if (fk) Tests.SubProcess(opts) else Tests.InProcess))
}
def forkOptionsTask: Initialize[Task[ForkOptions]] =
Def.task {
ForkOptions(
javaHome = javaHome.value,
outputStrategy = outputStrategy.value,
// bootJars is empty by default because only jars on the user's classpath should be on the boot classpath
bootJars = Vector(),
workingDirectory = Some(baseDirectory.value),
runJVMOptions = javaOptions.value.toVector,
connectInput = connectInput.value,
envVars = envVars.value
)
}
def testExecutionTask(task: Scoped): Initialize[Task[Tests.Execution]] =
Def.task {
new Tests.Execution(
(testOptions in task).value,
(parallelExecution in task).value,
(tags in task).value
)
}