/
Defaults.scala
4710 lines (4409 loc) · 179 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 2023, Scala center
* Copyright 2011 - 2022, 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 }
import java.nio.file.{ Paths, Path => NioPath }
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 org.apache.logging.log4j.core.{ Appender => XAppender }
import org.scalasbt.ipcsocket.Win32SecurityLevel
import sbt.Def.{ Initialize, ScopedKey, Setting, SettingsDefinition }
import sbt.Keys._
import sbt.OptionSyntax._
import sbt.Project.{
inConfig,
inScope,
inTask,
richInitialize,
richInitializeTask,
richTaskSessionVar,
sbtRichTaskPromise
}
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.{ ClasspathFilter, ClasspathUtil }
import sbt.internal.inc.{ CompileOutput, MappedFileConverter, Stamps, ZincLmUtil, ZincUtil }
import sbt.internal.io.{ Source, WatchState }
import sbt.internal.librarymanagement.mavenint.{
PomExtraDependencyAttributes,
SbtPomExtraProperties
}
import sbt.internal.librarymanagement._
import sbt.internal.nio.{ CheckBuildSources, Globs }
import sbt.internal.server.{
BspCompileProgress,
BspCompileTask,
BuildServerProtocol,
BuildServerReporter,
Definition,
LanguageServerProtocol,
ServerHandler,
VirtualTerminal
}
import sbt.internal.testing.TestLogger
import sbt.internal.util.Attributed.data
import sbt.internal.util.Types._
import sbt.internal.util.{ Terminal => ITerminal, _ }
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
}
import sbt.librarymanagement.CrossVersion.{ binarySbtVersion, binaryScalaVersion, partialVersion }
import sbt.librarymanagement._
import sbt.librarymanagement.ivy._
import sbt.librarymanagement.syntax._
import sbt.nio.FileStamp
import sbt.nio.Keys._
import sbt.nio.file.syntax._
import sbt.nio.file.{ FileTreeView, Glob, RecursiveGlob }
import sbt.nio.Watch
import sbt.std.TaskExtra._
import sbt.testing.{ AnnotatedFingerprint, Framework, Runner, SubclassFingerprint }
import sbt.util.CacheImplicits._
import sbt.util.InterfaceUtil.{ t2, toJavaFunction => f1 }
import sbt.util._
import sjsonnew._
import sjsonnew.support.scalajson.unsafe.Converter
import xsbti.compile.TastyFiles
import xsbti.{ FileConverter, Position }
import scala.annotation.nowarn
import scala.collection.immutable.ListMap
import scala.concurrent.duration._
import scala.util.control.NonFatal
import scala.xml.NodeSeq
// incremental compiler
import sbt.SlashSyntax0._
import sbt.internal.inc.{
Analysis,
AnalyzingCompiler,
ManagedLoggedReporter,
MixedAnalyzingCompiler,
ScalaInstance
}
import xsbti.{ CrossValue, VirtualFile, VirtualFileRef }
import xsbti.compile.{
AnalysisContents,
ClassFileManagerType,
ClasspathOptionsUtil,
CompileAnalysis,
CompileOptions,
CompileOrder,
CompileResult,
CompileProgress,
CompilerCache,
Compilers,
DefinesClass,
IncOptions,
IncToolOptionsUtil,
Inputs,
MiniSetup,
PerClasspathEntryLookup,
PreviousResult,
Setup,
TransactionalManagerType
}
object Defaults extends BuildCommon {
final val CacheDirectoryName = "cache"
def configSrcSub(key: SettingKey[File]): Initialize[File] =
Def.setting {
(ThisScope.copy(config = Zero) / key).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 :== SysProp.onChangedBuildSource,
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 := { (file: File) =>
sys.error("use classpathEntryDefinesClassVF instead")
},
extraIncOptions :== Seq("JAVA_CLASS_VERSION" -> sys.props("java.class.version")),
allowMachinePath :== true,
reportAbsolutePath := true,
run / traceLevel :== 0,
runMain / traceLevel :== 0,
bgRun / traceLevel :== 0,
fgRun / traceLevel :== 0,
console / traceLevel :== Int.MaxValue,
consoleProject / traceLevel :== Int.MaxValue,
autoCompilerPlugins :== true,
scalaHome :== None,
apiURL := None,
releaseNotesURL := 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,
packageSrc / artifactClassifier :== Some(SourceClassifier),
packageDoc / artifactClassifier :== Some(DocClassifier),
includeFilter :== NothingFilter,
unmanagedSources / includeFilter :== ("*.java" | "*.scala"),
unmanagedJars / includeFilter :== "*.jar" | "*.so" | "*.dll" | "*.jnilib" | "*.zip",
unmanagedResources / includeFilter :== AllPassFilter,
bgList := { bgJobService.value.jobs },
ps := psTask.value,
bgStop := bgStopTask.evaluated,
bgWaitFor := bgWaitForTask.evaluated,
bgCopyClasspath :== true,
closeClassLoaders :== SysProp.closeClassLoaders,
allowZombieClassLoaders :== true,
packageTimestamp :== Package.defaultTimestamp,
) ++ BuildServerProtocol.globalSettings
private[sbt] lazy val globalIvyCore: Seq[Setting[_]] =
Seq(
internalConfigurationMap :== Configurations.internalMap _,
credentials :== SysProp.sbtCredentialsEnv.toList,
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",
versionScheme :== None,
classpathTypes :== Set("jar", "bundle", "maven-plugin", "test-jar") ++ CustomPomParser.JarPackagings,
artifactClassifier :== None,
checksums := Classpaths.bootChecksums(appConfiguration.value),
conflictManager := ConflictManager.default,
pomExtra :== NodeSeq.Empty,
pomPostProcess :== idFun,
pomAllRepositories :== false,
pomIncludeRepository :== Classpaths.defaultRepositoryFilter,
updateOptions := UpdateOptions(),
forceUpdatePeriod :== None,
// coursier settings
csrExtraCredentials :== Nil,
csrLogger := LMCoursier.coursierLoggerTask.value,
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,
checkBuildSources / aggregate :== false,
checkBuildSources / changedInputFiles / aggregate := 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.
pluginCrossBuild / sbtVersion := sbtVersion.value,
onLoad := idFun[State],
onUnload := idFun[State],
onUnload := { s =>
try onUnload.value(s)
finally IO.delete(taskTemporaryDirectory.value)
},
// extraLoggers is deprecated
SettingKey[ScopedKey[_] => Seq[XAppender]]("extraLoggers") :== { _ =>
Nil
},
extraAppenders := {
val f = SettingKey[ScopedKey[_] => Seq[XAppender]]("extraLoggers").value
s =>
f(s).map {
case a: Appender => a
case a => new ConsoleAppenderFromLog4J(a.getName, a)
}
},
useLog4J :== SysProp.useLog4J,
watchSources :== Nil, // Although this is deprecated, it can't be removed or it breaks += for legacy builds.
skip :== false,
taskTemporaryDirectory := {
val base = BuildPaths.globalTaskDirectoryStandard(appConfiguration.value.baseDirectory)
val dir = IO.createUniqueDirectory(base)
ShutdownHooks.add(() => IO.delete(dir))
dir
},
onComplete := {
val tempDirectory = taskTemporaryDirectory.value
() => Clean.deleteContents(tempDirectory, _ => false)
},
turbo :== SysProp.turbo,
usePipelining :== SysProp.pipelining,
exportPipelining := usePipelining.value,
useSuperShell := { if (insideCI.value) false else ITerminal.console.isSupershellEnabled },
superShellThreshold :== SysProp.supershellThreshold,
superShellMaxTasks :== SysProp.supershellMaxTasks,
superShellSleep :== SysProp.supershellSleep.millis,
progressReports := {
val rs = EvaluateTask.taskTimingProgress.toVector ++ EvaluateTask.taskTraceEvent.toVector
rs map { Keys.TaskProgress(_) }
},
// progressState is deprecated
SettingKey[Option[ProgressState]]("progressState") := 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,
templateDescriptions :== TemplateCommandUtil.defaultTemplateDescriptions,
templateRunLocal := templateRunLocalInputTask(runLocalTemplate).evaluated,
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",
serverIdleTimeout := Some(new FiniteDuration(7, TimeUnit.DAYS)),
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,
windowsServerSecurityLevel := Win32SecurityLevel.OWNER_DACL, // allows any owner logon session to access the server
serverUseJni := BootServerSocket.requiresJNI || SysProp.serverUseJni,
fullServerHandlers := Nil,
insideCI :== sys.env.contains("BUILD_NUMBER") ||
sys.env.contains("CI") || SysProp.ci,
// watch related settings
pollInterval :== Watch.defaultPollInterval,
canonicalInput :== true,
echoInput :== true,
terminal := state.value.get(terminalKey).getOrElse(Terminal(ITerminal.get)),
InstallSbtn.installSbtn := InstallSbtn.installSbtnImpl.evaluated,
InstallSbtn.installSbtn / aggregate := false,
) ++ LintUnused.lintSettings
++ DefaultBackgroundJobService.backgroundJobServiceSettings
++ RemoteCache.globalSettings
)
private[sbt] lazy val buildLevelJvmSettings: Seq[Setting[_]] = Seq(
exportPipelining := usePipelining.value,
rootPaths := {
val app = appConfiguration.value
val base = app.baseDirectory.getCanonicalFile
val boot = app.provider.scalaProvider.launcher.bootDirectory
val ih = app.provider.scalaProvider.launcher.ivyHome
val coursierCache = csrCacheDirectory.value
val javaHome = Paths.get(sys.props("java.home"))
Map(
"BASE" -> base.toPath,
"SBT_BOOT" -> boot.toPath,
"CSR_CACHE" -> coursierCache.toPath,
"IVY_HOME" -> ih.toPath,
"JAVA_HOME" -> javaHome,
)
},
fileConverter := MappedFileConverter(rootPaths.value, allowMachinePath.value),
sourcePositionMappers := Nil, // Never set a default sourcePositionMapper, see #6352! Whatever you are trying to solve, do it in the foldMappers method.
// The virtual file value cache needs to be global or sbt will run out of direct byte buffer memory.
classpathDefinesClassCache := VirtualFileValueCache.definesClassCache(fileConverter.value),
fullServerHandlers := {
Seq(
LanguageServerProtocol.handler(fileConverter.value),
BuildServerProtocol.handler(
loadedBuild.value,
bspFullWorkspace.value,
sbtVersion.value,
semanticdbEnabled.value,
semanticdbVersion.value
),
VirtualTerminal.handler,
) ++ serverHandlers.value :+ ServerHandler.fallback
},
timeWrappedStamper := Stamps
.timeWrapBinaryStamps(Stamps.uncachedStamps(fileConverter.value), fileConverter.value),
reusableStamper := {
val converter = fileConverter.value
val unmanagedCache = unmanagedFileStampCache.value
val managedCache = managedFileStampCache.value
val backing = timeWrappedStamper.value
new xsbti.compile.analysis.ReadStamps {
def getAllLibraryStamps()
: java.util.Map[xsbti.VirtualFileRef, xsbti.compile.analysis.Stamp] =
backing.getAllLibraryStamps()
def getAllProductStamps()
: java.util.Map[xsbti.VirtualFileRef, xsbti.compile.analysis.Stamp] =
backing.getAllProductStamps()
def getAllSourceStamps()
: java.util.Map[xsbti.VirtualFileRef, xsbti.compile.analysis.Stamp] =
new java.util.HashMap[xsbti.VirtualFileRef, xsbti.compile.analysis.Stamp]
def library(fr: xsbti.VirtualFileRef): xsbti.compile.analysis.Stamp = backing.library(fr)
def product(fr: xsbti.VirtualFileRef): xsbti.compile.analysis.Stamp = backing.product(fr)
def source(fr: xsbti.VirtualFile): xsbti.compile.analysis.Stamp = {
val path = converter.toPath(fr)
unmanagedCache
.get(path)
.orElse(managedCache.getOrElseUpdate(path, sbt.nio.FileStamper.Hash))
.map(_.stamp)
.getOrElse(backing.source(fr))
}
}
},
)
private[sbt] def toAbsoluteSource(fc: FileConverter)(pos: Position): Position = {
val newPath: Option[NioPath] = pos
.sourcePath()
.asScala
.flatMap { path =>
try {
Some(fc.toPath(VirtualFileRef.of(path)))
} catch {
// catch all to trap wierd path injected by compiler, users, or plugins
case NonFatal(_) => None
}
}
newPath
.map { path =>
new Position {
override def line(): Optional[Integer] = pos.line()
override def lineContent(): String = pos.lineContent()
override def offset(): Optional[Integer] = pos.offset()
override def pointer(): Optional[Integer] = pos.pointer()
override def pointerSpace(): Optional[String] = pos.pointerSpace()
override def sourcePath(): Optional[String] = Optional.of(path.toAbsolutePath.toString)
override def sourceFile(): Optional[File] =
(try {
Some(path.toFile.getAbsoluteFile)
} catch {
case NonFatal(_) => None
}).toOptional
override def startOffset(): Optional[Integer] = pos.startOffset()
override def endOffset(): Optional[Integer] = pos.endOffset()
override def startLine(): Optional[Integer] = pos.startLine()
override def startColumn(): Optional[Integer] = pos.startColumn()
override def endLine(): Optional[Integer] = pos.endLine()
override def endColumn(): Optional[Integer] = pos.endColumn()
}
}
.getOrElse(pos)
}
// csrCacheDirectory is scoped to ThisBuild to allow customization.
private[sbt] lazy val buildLevelIvySettings: Seq[Setting[_]] = Seq(
csrCacheDirectory := {
if (useCoursier.value) LMCoursier.defaultCacheLocation
else Classpaths.dummyCoursierDirectory(appConfiguration.value)
},
)
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(extraAppenders.value, ConsoleOut.terminalOut),
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",
// Use a different history path for jline3 because the jline2 format is
// incompatible. By sbt 1.4.0, we should consider revering this to t / ".history"
// and possibly rewriting the jline2 history in a jline3 compatible format if the
// history file is incompatible. For now, just use a different file to facilitate
// going back and forth between 1.3.x and 1.4.x.
historyPath := (historyPath or target(t => Option(t / ".history3"))).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 / pollInterval :==
new FiniteDuration(Int.MinValue, TimeUnit.MILLISECONDS),
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 := {
val isDotty = ScalaInstance.isDotty(scalaVersion.value)
val epochVersion = if (isDotty) "3" else "2"
makeCrossSources(
scalaSource.value,
javaSource.value,
scalaBinaryVersion.value,
epochVersion,
crossPaths.value
) ++
makePluginCrossSources(
sbtPlugin.value,
scalaSource.value,
(pluginCrossBuild / sbtBinaryVersion).value,
crossPaths.value
)
},
unmanagedSources / fileInputs := {
val include = (unmanagedSources / includeFilter).value
val filter = (unmanagedSources / excludeFilter).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 = (unmanagedResources / includeFilter).value
val filter = (unmanagedResources / excludeFilter).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[Setting[_]] = Seq(
classDirectory := crossTarget.value / (prefix(configuration.value.name) + "classes"),
backendOutput := {
val converter = fileConverter.value
val dir = classDirectory.value
converter.toVirtualFile(dir.toPath)
},
earlyOutput / artifactPath := configArtifactPathSetting(artifact, "early").value,
earlyOutput := {
val converter = fileConverter.value
val jar = (earlyOutput / artifactPath).value
converter.toVirtualFile(jar.toPath)
},
semanticdbTargetRoot := crossTarget.value / (prefix(configuration.value.name) + "meta"),
compileAnalysisTargetRoot := crossTarget.value / (prefix(configuration.value.name) + "zinc"),
earlyCompileAnalysisTargetRoot := crossTarget.value / (prefix(configuration.value.name) + "early-zinc"),
doc / target := crossTarget.value / (prefix(configuration.value.name) + "api")
)
// This is included into JvmPlugin.projectSettings
def compileBase = inTask(console)(compilersSetting :: Nil) ++ compileBaseGlobal ++ Seq(
useScalaReplJLine :== false,
scalaInstanceTopLoader := {
val topLoader = if (!useScalaReplJLine.value) {
// the JLineLoader contains the SbtInterfaceClassLoader
classOf[org.jline.terminal.Terminal].getClassLoader
} else classOf[Compilers].getClassLoader // the SbtInterfaceClassLoader
// Scala 2.10 shades jline in the console so we need to make sure that it loads a compatible
// jansi version. Because of the shading, console does not work with the thin client for 2.10.x.
if (scalaVersion.value.startsWith("2.10.")) new ClassLoader(topLoader) {
override protected def loadClass(name: String, resolve: Boolean): Class[_] = {
if (name.startsWith("org.fusesource")) throw new ClassNotFoundException(name)
super.loadClass(name, resolve)
}
}
else topLoader
},
scalaInstance := scalaInstanceTask.value,
crossVersion := (if (crossPaths.value) CrossVersion.binary else CrossVersion.disabled),
pluginCrossBuild / sbtBinaryVersion := binarySbtVersion(
(pluginCrossBuild / sbtVersion).value
),
// Use (sbtVersion in pluginCrossBuild) to pick the sbt module to depend from the plugin.
// Because `sbtVersion in pluginCrossBuild` can be scoped to project level,
// this setting needs to be set here too.
pluginCrossBuild / sbtDependency := {
val app = appConfiguration.value
val id = app.provider.id
val sv = (pluginCrossBuild / sbtVersion).value
val scalaV = (pluginCrossBuild / scalaVersion).value
val binVersion = (pluginCrossBuild / scalaBinaryVersion).value
val cross = id.crossVersionedValue match {
case CrossValue.Disabled => Disabled()
case CrossValue.Full => CrossVersion.full
case CrossValue.Binary => CrossVersion.binary
}
val base = ModuleID(id.groupID, id.name, sv).withCrossVersion(cross)
CrossVersion(scalaV, binVersion)(base).withCrossVersion(Disabled())
},
crossSbtVersions := Vector((pluginCrossBuild / sbtVersion).value),
crossTarget := makeCrossTarget(
target.value,
scalaVersion.value,
scalaBinaryVersion.value,
(pluginCrossBuild / sbtBinaryVersion).value,
sbtPlugin.value,
crossPaths.value
),
cleanIvy := IvyActions.cleanCachedResolutionCache(ivyModule.value, streams.value.log),
clean := clean.dependsOn(cleanIvy).value,
scalaCompilerBridgeBinaryJar := Def.settingDyn {
val sv = scalaVersion.value
if (ScalaArtifacts.isScala3(sv) || VersionNumber(sv)
.matchesSemVer(SemanticSelector(s"=2.13 >=${ZincLmUtil.scala2SbtBridgeStart}")))
fetchBridgeBinaryJarTask(sv)
else Def.task[Option[File]](None)
}.value,
scalaCompilerBridgeSource := ZincLmUtil.getDefaultBridgeSourceModule(scalaVersion.value),
auxiliaryClassFiles ++= {
if (ScalaArtifacts.isScala3(scalaVersion.value)) List(TastyFiles.instance)
else Nil
},
consoleProject / scalaCompilerBridgeBinaryJar := None,
consoleProject / scalaCompilerBridgeSource := ZincLmUtil.getDefaultBridgeSourceModule(
appConfiguration.value.provider.scalaProvider.version
),
)
// must be a val: duplication detected by object identity
private[this] lazy val compileBaseGlobal: Seq[Setting[_]] = globalDefaults(
Seq(
auxiliaryClassFiles :== Nil,
incOptions := IncOptions.of(),
classpathOptions :== ClasspathOptionsUtil.boot,
console / classpathOptions :== 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,
epochVersion: String,
cross: Boolean
): Seq[File] = {
if (cross)
Seq(
scalaSrcDir,
scalaSrcDir.getParentFile / s"${scalaSrcDir.name}-$sv",
scalaSrcDir.getParentFile / s"${scalaSrcDir.name}-$epochVersion",
javaSrcDir,
).distinct
else
Seq(scalaSrcDir, javaSrcDir)
}
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()
}
@deprecated("Use constructor with scalaVersion and scalaBinaryVersion", "1.5.0")
def makeCrossTarget(t: File, bv: String, sbtv: String, plugin: Boolean, cross: Boolean): File = {
val scalaBase = if (cross) t / ("scala-" + bv) else t
if (plugin) scalaBase / ("sbt-" + sbtv) else scalaBase
}
def makeCrossTarget(
t: File,
scalaVersion: String,
scalaBinaryVersion: String,
sbtv: String,
plugin: Boolean,
cross: Boolean
): File = {
val scalaSuffix =
if (ScalaArtifacts.isScala3(scalaVersion)) scalaVersion else scalaBinaryVersion
val scalaBase = if (cross) t / ("scala-" + scalaSuffix) else t
if (plugin) scalaBase / ("sbt-" + sbtv) else scalaBase
}
private def fetchBridgeBinaryJarTask(scalaVersion: String): Initialize[Task[Option[File]]] =
Def.task {
val bridgeJar = ZincLmUtil.fetchDefaultBridgeModule(
scalaVersion,
dependencyResolution.value,
updateConfiguration.value,
(update / unresolvedWarningConfiguration).value,
streams.value.log
)
Some(bridgeJar)
}
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.map(_.toPath),
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) ++
inTask(compileJava)(
Seq(
compileInputs := {
val opts = (compileJava / compileOptions).value
(compile / compileInputs).value.withOptions(opts)
},
compileOptions := {
val opts = (compile / compileOptions).value
val cp0 = dependencyVirtualClasspath.value
val cp = backendOutput.value +: data(cp0)
opts.withClasspath(cp.toArray)
}
)
) ++
configGlobal ++ defaultCompileSettings ++ compileAnalysisSettings ++ Seq(
compileOutputs := {
import scala.collection.JavaConverters._
val c = fileConverter.value
val classFiles =
manipulateBytecode.value.analysis.readStamps.getAllProductStamps.keySet.asScala
(classFiles.toSeq map { x =>
c.toPath(x)
}) :+ compileAnalysisFile.value.toPath
},
compileOutputs := compileOutputs.triggeredBy(compile).value,
tastyFiles := Def.taskIf {
if (ScalaArtifacts.isScala3(scalaVersion.value)) {
val _ = compile.value
val tastyFiles = classDirectory.value.**("*.tasty").get
tastyFiles.map(_.getAbsoluteFile)
} else Nil
}.value,
clean := (compileOutputs / clean).value,
earlyOutputPing := Def.promise[Boolean],
compileProgress := {
val s = streams.value
val promise = earlyOutputPing.value
val mn = moduleName.value
val c = configuration.value
new CompileProgress {
override def afterEarlyOutput(isSuccess: Boolean): Unit = {
if (isSuccess) s.log.debug(s"[$mn / $c] early output is success")
else s.log.debug(s"[$mn / $c] early output can't be made because of macros")
promise.complete(Value(isSuccess))
}
}
},
compileEarly := compileEarlyTask.value,
compile := compileTask.value,
compileScalaBackend := compileScalaBackendTask.value,
compileJava := compileJavaTask.value,
compileSplit := {
// conditional task
if (incOptions.value.pipelining) compileJava.value
else compileScalaBackend.value
},
internalDependencyConfigurations := InternalDependencies.configurations.value,
manipulateBytecode := compileSplit.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"
},
earlyCompileAnalysisFile := {
earlyCompileAnalysisTargetRoot.value / compileAnalysisFilename.value
},
compileAnalysisFile := {
compileAnalysisTargetRoot.value / compileAnalysisFilename.value
},
externalHooks := IncOptions.defaultExternal,
zincCompilationListeners := Seq.empty,
incOptions := {
val old = incOptions.value
val extHooks = externalHooks.value
val newExtHooks = extHooks.withInvalidationProfiler(
() => new DefaultRunProfiler(zincCompilationListeners.value)
)
old
.withAuxiliaryClassFiles(auxiliaryClassFiles.value.toArray)
.withExternalHooks(newExtHooks)
.withClassfileManagerType(
Option(
TransactionalManagerType
.of( // https://github.com/sbt/sbt/issues/1673
crossTarget.value / s"${prefix(configuration.value.name)}classes.bak",
streams.value.log
): ClassFileManagerType
).toOptional
)
.withPipelining(usePipelining.value)
},
scalacOptions := {
val old = scalacOptions.value
val converter = fileConverter.value
if (exportPipelining.value)
Vector("-Ypickle-java", "-Ypickle-write", converter.toPath(earlyOutput.value).toString) ++ old
else old
},
scalacOptions := {
val old = scalacOptions.value
if (sbtPlugin.value && VersionNumber(scalaVersion.value)
.matchesSemVer(SemanticSelector("=2.12 >=2.12.13")))
old ++ Seq("-Wconf:cat=unused-nowarn:s", "-Xsource:3")
else old
},
persistJarClasspath :== true,
classpathEntryDefinesClassVF := {
(if (persistJarClasspath.value) classpathDefinesClassCache.value
else VirtualFileValueCache.definesClassCache(fileConverter.value)).get
},
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