-
Notifications
You must be signed in to change notification settings - Fork 26
/
Defaults.scala
1100 lines (1002 loc) · 56.2 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 -- Simple Build Tool
* Copyright 2011 Mark Harrah
*/
package sbt
import Build.data
import Scope.{fillTaskAxis, GlobalScope, ThisScope}
import compiler.Discovery
import Project.{inConfig, Initialize, inScope, inTask, ScopedKey, Setting, SettingsDefinition}
import Artifact.{DocClassifier, SourceClassifier}
import Configurations.{Compile, CompilerPlugin, IntegrationTest, names, Provided, Runtime, Test}
import complete._
import std.TaskExtra._
import inc.{FileValueCache, Locate}
import org.scalatools.testing.{AnnotatedFingerprint, SubclassFingerprint}
import scala.xml.{Node => XNode,NodeSeq}
import org.apache.ivy.core.module.{descriptor, id}
import descriptor.ModuleDescriptor, id.ModuleRevisionId
import java.io.File
import java.net.URL
import java.util.concurrent.Callable
import sbinary.DefaultProtocol.StringFormat
import Cache.seqFormat
import Types._
import Path._
import Keys._
object Defaults extends BuildCommon
{
def configSrcSub(key: ScopedSetting[File]): Initialize[File] = (key in ThisScope.copy(config = Global), configuration) { (src, conf) => src / nameForSrc(conf.name) }
def nameForSrc(config: String) = if(config == "compile") "main" else config
def prefix(config: String) = if(config == "compile") "" else config + "-"
def lock(app: xsbti.AppConfiguration): xsbti.GlobalLock = app.provider.scalaProvider.launcher.globalLock
def extractAnalysis[T](a: Attributed[T]): (T, inc.Analysis) =
(a.data, a.metadata get Keys.analysis getOrElse inc.Analysis.Empty)
def analysisMap[T](cp: Seq[Attributed[T]]): Map[T, inc.Analysis] =
(cp map extractAnalysis).toMap
def buildCore: Seq[Setting[_]] = thisBuildCore ++ globalCore
def thisBuildCore: Seq[Setting[_]] = inScope(GlobalScope.copy(project = Select(ThisBuild)))(Seq(
managedDirectory <<= baseDirectory(_ / "lib_managed")
))
def globalCore: Seq[Setting[_]] = inScope(GlobalScope)(Seq(
taskTemporaryDirectory := IO.createTemporaryDirectory,
onComplete <<= taskTemporaryDirectory { dir => () => IO.delete(dir); IO.createDirectory(dir) },
parallelExecution :== true,
sbtVersion in GlobalScope <<= appConfiguration { _.provider.id.version },
sbtResolver in GlobalScope <<= sbtVersion { sbtV => if(sbtV endsWith "-SNAPSHOT") Classpaths.typesafeSnapshots else Classpaths.typesafeResolver },
pollInterval :== 500,
logBuffered :== false,
autoScalaLibrary :== true,
onLoad :== idFun[State],
onUnload :== idFun[State],
definesClass :== FileValueCache(Locate.definesClass _ ).get,
trapExit :== false,
trapExit in run :== true,
logBuffered in testOnly :== true,
logBuffered in test :== true,
traceLevel in console :== Int.MaxValue,
traceLevel in consoleProject :== Int.MaxValue,
autoCompilerPlugins :== true,
internalConfigurationMap :== Configurations.internalMap _,
initialize :== (),
credentials :== Nil,
scalaHome :== None,
javaHome :== None,
extraLoggers :== { _ => Nil },
skip :== false,
version :== "0.1",
outputStrategy :== None,
exportJars :== false,
fork :== false,
javaOptions :== Nil,
sbtPlugin :== false,
crossPaths :== true,
classpathTypes :== Set("jar", "bundle"),
aggregate :== Aggregation.Enabled,
maxErrors :== 100,
showTiming :== true,
timingFormat :== Aggregation.defaultFormat,
showSuccess :== true,
commands :== Nil,
retrieveManaged :== false,
buildStructure <<= state map Project.structure,
settings <<= buildStructure map ( _.data ),
artifactClassifier :== None,
artifactClassifier in packageSrc :== Some(SourceClassifier),
artifactClassifier in packageDoc :== Some(DocClassifier),
checksums :== IvySbt.DefaultChecksums,
pomExtra :== NodeSeq.Empty,
pomPostProcess :== idFun,
pomAllRepositories :== false,
pomIncludeRepository :== Classpaths.defaultRepositoryFilter
))
def projectCore: Seq[Setting[_]] = Seq(
name <<= thisProject(_.id),
logManager <<= extraLoggers(LogManager.defaults),
runnerTask
)
def paths = Seq(
baseDirectory <<= thisProject(_.base),
target <<= baseDirectory / "target",
defaultExcludes in GlobalScope :== (".*" - ".") || HiddenFileFilter,
historyPath <<= target(t => Some(t / ".history")),
sourceDirectory <<= baseDirectory / "src",
sourceFilter in GlobalScope :== ("*.java" | "*.scala"),
sourceManaged <<= crossTarget / "src_managed",
resourceManaged <<= crossTarget / "resource_managed",
cacheDirectory <<= target / "cache"
)
lazy val configPaths = sourceConfigPaths ++ resourceConfigPaths ++ outputConfigPaths
lazy val sourceConfigPaths = Seq(
sourceDirectory <<= configSrcSub( sourceDirectory),
sourceManaged <<= configSrcSub(sourceManaged),
scalaSource <<= sourceDirectory / "scala",
javaSource <<= sourceDirectory / "java",
unmanagedSourceDirectories <<= Seq(scalaSource, javaSource).join,
unmanagedSources <<= collectFiles(unmanagedSourceDirectories, sourceFilter, defaultExcludes in unmanagedSources),
managedSourceDirectories <<= Seq(sourceManaged).join,
managedSources <<= generate(sourceGenerators),
sourceGenerators :== Nil,
sourceDirectories <<= Classpaths.concatSettings(unmanagedSourceDirectories, managedSourceDirectories),
sources <<= Classpaths.concat(unmanagedSources, managedSources)
)
lazy val resourceConfigPaths = Seq(
resourceDirectory <<= sourceDirectory / "resources",
resourceManaged <<= configSrcSub(resourceManaged),
unmanagedResourceDirectories <<= Seq(resourceDirectory).join,
managedResourceDirectories <<= Seq(resourceManaged).join,
resourceDirectories <<= Classpaths.concatSettings(unmanagedResourceDirectories, managedResourceDirectories),
unmanagedResources <<= (unmanagedResourceDirectories, defaultExcludes in unmanagedResources) map unmanagedResourcesTask,
resourceGenerators :== Nil,
resourceGenerators <+= (definedSbtPlugins, resourceManaged) map writePluginsDescriptor,
managedResources <<= generate(resourceGenerators),
resources <<= Classpaths.concat(managedResources, unmanagedResources)
)
lazy val outputConfigPaths = Seq(
cacheDirectory <<= (cacheDirectory, configuration) { _ / _.name },
classDirectory <<= (crossTarget, configuration) { (outDir, conf) => outDir / (prefix(conf.name) + "classes") },
docDirectory <<= (crossTarget, configuration) { (outDir, conf) => outDir / (prefix(conf.name) + "api") }
)
def addBaseSources = Seq(
unmanagedSources <<= (unmanagedSources, baseDirectory, sourceFilter, defaultExcludes in unmanagedSources) map {
(srcs,b,f,excl) => (srcs +++ b * (f -- excl)).get
}
)
def compileBase = inTask(console)(compilersSetting :: Nil) ++ Seq(
classpathOptions in GlobalScope :== ClasspathOptions.boot,
classpathOptions in GlobalScope in console :== ClasspathOptions.repl,
compileOrder in GlobalScope :== CompileOrder.Mixed,
compilersSetting,
javacOptions in GlobalScope :== Nil,
scalacOptions in GlobalScope :== Nil,
scalaInstance <<= scalaInstanceSetting,
scalaVersion in GlobalScope <<= appConfiguration( _.provider.scalaProvider.version),
crossScalaVersions in GlobalScope <<= Seq(scalaVersion).join,
crossTarget <<= (target, scalaVersion, sbtVersion, sbtPlugin, crossPaths)(makeCrossTarget),
cacheDirectory <<= crossTarget / "cache"
)
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 <<= (scalaInstance, appConfiguration, streams, classpathOptions, javaHome) map { (si, app, s, co, jh) => Compiler.compilers(si, co, jh)(app, s.log) }
lazy val configTasks = Seq(
initialCommands in GlobalScope :== "",
compile <<= compileTask,
compileInputs <<= compileInputsTask,
compileIncSetup <<= compileIncSetupTask,
console <<= consoleTask,
consoleQuick <<= consoleQuickTask,
discoveredMainClasses <<= TaskData.write(compile map discoverMainClasses) triggeredBy compile,
definedSbtPlugins <<= discoverPlugins,
inTask(run)(runnerTask :: Nil).head,
selectMainClass <<= discoveredMainClasses map selectRunMain,
mainClass in run <<= (selectMainClass in run).identity,
mainClass <<= discoveredMainClasses map selectPackageMain,
run <<= runTask(fullClasspath, mainClass in run, runner in run),
runMain <<= runMainTask(fullClasspath, runner in run),
scaladocOptions <<= scalacOptions.identity,
doc <<= docTask,
copyResources <<= copyResourcesTask
)
lazy val projectTasks: Seq[Setting[_]] = Seq(
cleanFiles <<= Seq(managedDirectory, target).join,
cleanKeepFiles <<= historyPath(_.toList),
clean <<= (cleanFiles, cleanKeepFiles) map doClean,
consoleProject <<= consoleProjectTask,
watchSources <<= watchSourcesTask,
watchTransitiveSources <<= watchTransitiveSourcesTask,
watch <<= watchSetting
)
def generate(generators: ScopedSetting[Seq[Task[Seq[File]]]]): Initialize[Task[Seq[File]]] = generators {_.join.map(_.flatten) }
def inAllConfigurations[T](key: ScopedTask[T]): Initialize[Task[Seq[T]]] = (state, thisProjectRef) flatMap { (state, ref) =>
val structure = Project structure state
val configurations = Project.getProject(ref, structure).toList.flatMap(_.configurations)
configurations.flatMap { conf =>
key in (ref, conf) get structure.data
} join
}
def watchTransitiveSourcesTask: Initialize[Task[Seq[File]]] =
(state, thisProjectRef) flatMap { (s, base) =>
inAllDependencies(base, watchSources.task, Project structure s).join.map(_.flatten)
}
def watchSourcesTask: Initialize[Task[Seq[File]]] =
Seq(unmanagedSources, unmanagedResources).map(inAllConfigurations).join { _.join.map(_.flatten.flatten.distinct) }
def watchSetting: Initialize[Watched] = (pollInterval, thisProjectRef) { (interval, base) =>
new Watched {
val scoped = watchTransitiveSources in base
val key = ScopedKey(scoped.scope, scoped.key)
override def pollInterval = interval
override def watchPaths(s: State) = EvaluateTask.evaluateTask(Project structure s, key, s, base) match {
case Some(Value(ps)) => ps
case Some(Inc(i)) => throw i
case None => error("key not found: " + Project.displayFull(key))
}
}
}
def scalaInstanceSetting = (appConfiguration, scalaVersion, scalaHome) map { (app, version, home) =>
val launcher = app.provider.scalaProvider.launcher
home match {
case None => ScalaInstance(version, launcher)
case Some(h) => ScalaInstance(h, launcher)
}
}
def unmanagedResourcesTask(dirs: Seq[File], excl: FileFilter) =
dirs.descendentsExcept("*",excl).get
lazy val testTasks: Seq[Setting[_]] = testTaskOptions(test) ++ testTaskOptions(testOnly) ++ Seq(
testLoader <<= (fullClasspath, scalaInstance, taskTemporaryDirectory) map { (cp, si, temp) => TestFramework.createTestLoader(data(cp), si, IO.createUniqueDirectory(temp)) },
testFrameworks in GlobalScope :== {
import sbt.TestFrameworks._
Seq(ScalaCheck, Specs2, Specs, ScalaTest, ScalaCheckCompat, ScalaTestCompat, SpecsCompat, JUnit)
},
loadedTestFrameworks <<= (testFrameworks, streams, testLoader) map { (frameworks, s, loader) =>
frameworks.flatMap(f => f.create(loader, s.log).map( x => (f,x)).toIterable).toMap
},
definedTests <<= TaskData.writeRelated(detectTests)(_.map(_.name).distinct) triggeredBy compile,
testListeners in GlobalScope :== Nil,
testOptions in GlobalScope :== Nil,
executeTests <<= (streams in test, loadedTestFrameworks, parallelExecution in test, testOptions in test, testLoader, definedTests, resolvedScoped, state) flatMap {
(s, frameworkMap, par, options, loader, discovered, scoped, st) =>
implicit val display = Project.showContextKey(st)
Tests(frameworkMap, loader, discovered, options, par, noTestsMessage(ScopedKey(scoped.scope, test.key)), s.log)
},
test <<= (executeTests, streams) map { (results, s) => Tests.showResults(s.log, results) },
testOnly <<= testOnlyTask
)
private[this] def noTestsMessage(scoped: ScopedKey[_])(implicit display: Show[ScopedKey[_]]): String =
"No tests to run for " + display(scoped)
lazy val TaskGlobal: Scope = ThisScope.copy(task = Global)
def testTaskOptions(key: Scoped): Seq[Setting[_]] = inTask(key)( Seq(
testListeners <<= (streams, resolvedScoped, streamsManager, logBuffered, testListeners in TaskGlobal) map { (s, sco, sm, buff, ls) =>
TestLogger(s.log, testLogger(sm, test in sco.scope), buff) +: ls
},
testOptions <<= (testOptions in TaskGlobal, testListeners) map { (options, ls) => Tests.Listeners(ls) +: options }
) )
def testLogger(manager: Streams, baseKey: Scoped)(tdef: TestDefinition): Logger =
{
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)
manager(key).log
}
def buffered(log: Logger): Logger = new BufferedLogger(FullLogger(log))
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 testOnlyTask =
InputTask( TaskData(definedTests)(testOnlyParser)(Nil) ) { result =>
(streams, loadedTestFrameworks, parallelExecution in testOnly, testOptions in testOnly, testLoader, definedTests, resolvedScoped, result, state) flatMap {
case (s, frameworks, par, opts, loader, discovered, scoped, (tests, frameworkOptions), st) =>
val filter = selectedFilter(tests)
val modifiedOpts = Tests.Filter(filter) +: Tests.Argument(frameworkOptions : _*) +: opts
implicit val display = Project.showContextKey(st)
Tests(frameworks, loader, discovered, modifiedOpts, par, noTestsMessage(scoped), s.log) map { results =>
Tests.showResults(s.log, results)
}
}
}
def selectedFilter(args: Seq[String]): String => Boolean =
{
val filters = args map GlobFilter.apply
s => filters.isEmpty || filters.exists { _ accept s }
}
def detectTests: Initialize[Task[Seq[TestDefinition]]] = (loadedTestFrameworks, compile, streams) map { (frameworkMap, analysis, s) =>
Tests.discover(frameworkMap.values.toSeq, analysis, s.log)._1
}
lazy val packageBase: Seq[Setting[_]] = Seq(
artifact <<= moduleName(n => Artifact(n)),
packageOptions in GlobalScope :== Nil,
artifactName in GlobalScope :== ( Artifact.artifactName _ )
)
lazy val packageConfig: Seq[Setting[_]] = Seq(
packageOptions in packageBin <<= (packageOptions, mainClass in packageBin, name, version, homepage, organization, organizationName) map { (p, main, name, ver, h, org, orgName) =>
p ++ main.map(Package.MainClass.apply) :+ Package.addSpecManifestAttributes(name, ver, orgName) :+ Package.addImplManifestAttributes(name, ver, h, org, orgName) },
packageOptions in packageSrc <<= (packageOptions, name, version, organizationName) map { _ :+ Package.addSpecManifestAttributes(_, _, _) }
) ++
packageTasks(packageBin, packageBinTask) ++
packageTasks(packageSrc, packageSrcTask) ++
packageTasks(packageDoc, packageDocTask)
private[this] val allSubpaths = (dir: File) => (dir.*** --- dir) x (relativeTo(dir)|flat)
def packageBinTask = products map { ps => ps flatMap { p => allSubpaths(p) } }
def packageDocTask = doc map allSubpaths
def packageSrcTask = concatMappings(resourceMappings, sourceMappings)
private type Mappings = Initialize[Task[Seq[(File, String)]]]
def concatMappings(as: Mappings, bs: Mappings) = (as zipWith bs)( (a,b) => (a :^: b :^: KNil) map { case a :+: b :+: HNil => a ++ b } )
// drop base directories, since there are no valid mappings for these
def sourceMappings = (unmanagedSources, unmanagedSourceDirectories, baseDirectory) map { (srcs, sdirs, base) =>
( (srcs --- sdirs --- base) x (relativeTo(sdirs)|relativeTo(base)|flat)) toSeq
}
def resourceMappings = relativeMappings(unmanagedResources, unmanagedResourceDirectories)
def relativeMappings(files: ScopedTaskable[Seq[File]], dirs: ScopedTaskable[Seq[File]]): Initialize[Task[Seq[(File, String)]]] =
(files, dirs) map { (rs, rdirs) =>
(rs --- rdirs) x (relativeTo(rdirs)|flat) toSeq
}
def collectFiles(dirs: ScopedTaskable[Seq[File]], filter: ScopedTaskable[FileFilter], excludes: ScopedTaskable[FileFilter]): Initialize[Task[Seq[File]]] =
(dirs, filter, excludes) map { (d,f,excl) => d.descendentsExcept(f,excl).get }
def artifactPathSetting(art: ScopedSetting[Artifact]) = (crossTarget, projectID, art, scalaVersion in artifactName, artifactName) { (t, module, a, sv, toString) => t / toString(sv, module, a) asFile }
def artifactSetting = ((artifact, artifactClassifier).identity zipWith configuration.?) { case ((a,classifier),cOpt) =>
val cPart = cOpt flatMap { c => if(c == Compile) None else Some(c.name) }
val combined = cPart.toList ++ classifier.toList
if(combined.isEmpty) a.copy(classifier = None, configurations = cOpt.toList) else {
val classifierString = combined mkString "-"
val confs = cOpt.toList flatMap { c => artifactConfigurations(a, c, classifier) }
a.copy(classifier = Some(classifierString), `type` = Artifact.classifierType(classifierString), configurations = confs)
}
}
def artifactConfigurations(base: Artifact, scope: Configuration, classifier: Option[String]): Iterable[Configuration] =
if(base.configurations.isEmpty)
classifier match {
case Some(c) => Artifact.classifierConf(c) :: Nil
case None => scope :: Nil
}
else
base.configurations
def pairID[A,B] = (a: A, b: B) => (a,b)
def packageTasks(key: TaskKey[File], mappingsTask: Initialize[Task[Seq[(File,String)]]]) =
inTask(key)( Seq(
key in TaskGlobal <<= packageTask,
packageConfiguration <<= packageConfigurationTask,
mappings <<= mappingsTask,
packagedArtifact <<= (artifact, key) map pairID,
artifact <<= artifactSetting,
cacheDirectory <<= cacheDirectory / key.key.label,
artifactPath <<= artifactPathSetting(artifact)
))
def packageTask: Initialize[Task[File]] =
(packageConfiguration, cacheDirectory, streams) map { (config, cacheDir, s) =>
Package(config, cacheDir, s.log)
config.jar
}
def packageConfigurationTask: Initialize[Task[Package.Configuration]] =
(mappings, artifactPath, packageOptions) map { (srcs, path, options) =>
new Package.Configuration(srcs, path, options)
}
def selectRunMain(classes: Seq[String]): Option[String] =
sbt.SelectMainClass(Some(SimpleReader readLine _), classes)
def selectPackageMain(classes: Seq[String]): Option[String] =
sbt.SelectMainClass(None, classes)
def doClean(clean: Seq[File], preserve: Seq[File]): Unit =
IO.withTemporaryDirectory { temp =>
val mappings = preserve.filter(_.exists).zipWithIndex map { case (f, i) => (f, new File(temp, i.toHexString)) }
IO.move(mappings)
IO.delete(clean)
IO.move(mappings.map(_.swap))
}
def runMainTask(classpath: ScopedTask[Classpath], scalaRun: ScopedTask[ScalaRun]): Initialize[InputTask[Unit]] =
{
import DefaultParsers._
InputTask( TaskData(discoveredMainClasses)(runMainParser)(Nil) ) { result =>
(classpath, scalaRun, streams, result) map { case (cp, runner, s, (mainClass, args)) =>
toError(runner.run(mainClass, data(cp), args, s.log))
}
}
}
def runTask(classpath: ScopedTask[Classpath], mainClassTask: ScopedTask[Option[String]], scalaRun: ScopedTask[ScalaRun]): Initialize[InputTask[Unit]] =
inputTask { result =>
(classpath, mainClassTask, scalaRun, streams, result) map { (cp, main, runner, s, args) =>
val mainClass = main getOrElse error("No main class detected.")
toError(runner.run(mainClass, data(cp), args, s.log))
}
}
def runnerTask = runner <<= runnerInit
def runnerInit: Initialize[Task[ScalaRun]] =
(taskTemporaryDirectory, scalaInstance, baseDirectory, javaOptions, outputStrategy, fork, javaHome, trapExit) map { (tmp, si, base, options, strategy, forkRun, javaHomeDir, trap) =>
if(forkRun) {
new ForkRun( ForkOptions(scalaJars = si.jars, javaHome = javaHomeDir, outputStrategy = strategy,
runJVMOptions = options, workingDirectory = Some(base)) )
} else
new Run(si, trap, tmp)
}
def docTask: Initialize[Task[File]] =
(cacheDirectory, compileInputs, streams, docDirectory, configuration, scaladocOptions) map { (cache, in, s, target, config, options) =>
val d = new Scaladoc(in.config.maxErrors, in.compilers.scalac)
val cp = in.config.classpath.toList - in.config.classesDirectory
d.cached(cache / "doc", nameForSrc(config.name), in.config.sources, cp, target, options, s.log)
target
}
def mainRunTask = run <<= runTask(fullClasspath in Runtime, mainClass in run, runner in run)
def mainRunMainTask = runMain <<= runMainTask(fullClasspath in Runtime, runner in run)
def discoverMainClasses(analysis: inc.Analysis): Seq[String] =
Discovery.applications(Tests.allDefs(analysis)) collect { case (definition, discovered) if(discovered.hasMain) => definition.name }
def consoleProjectTask = (state, streams, initialCommands in consoleProject) map { (state, s, extra) => ConsoleProject(state, extra)(s.log); println() }
def consoleTask: Initialize[Task[Unit]] = consoleTask(fullClasspath, console)
def consoleQuickTask = consoleTask(externalDependencyClasspath, consoleQuick)
def consoleTask(classpath: TaskKey[Classpath], task: TaskKey[_]): Initialize[Task[Unit]] = (compilers in task, classpath, scalacOptions in task, initialCommands in task, streams) map {
(cs, cp, options, initCommands, s) =>
(new Console(cs.scalac))(data(cp), options, initCommands, s.log).foreach(msg => error(msg))
println()
}
def compileTask = (compileInputs, streams) map { (i,s) => Compiler(i,s.log) }
def compileIncSetupTask =
(dependencyClasspath, cacheDirectory, skip in compile, definesClass) map { (cp, cacheDir, skip, definesC) =>
Compiler.IncSetup(analysisMap(cp), definesC, skip, cacheDir / "compile")
}
def compileInputsTask =
(dependencyClasspath, sources, compilers, javacOptions, scalacOptions, classDirectory, compileOrder, compileIncSetup, streams) map {
(cp, srcs, cs, javacOpts, scalacOpts, classes, order, incSetup, s) =>
val classpath = classes +: data(cp)
Compiler.inputs(classpath, srcs, classes, scalacOpts, javacOpts, 100, order)(cs, incSetup, s.log)
}
def sbtPluginExtra(m: ModuleID, sbtV: String, scalaV: String): ModuleID = m.extra(CustomPomParser.SbtVersionKey -> sbtV, CustomPomParser.ScalaVersionKey -> scalaV).copy(crossVersion = false)
def writePluginsDescriptor(plugins: Set[String], dir: File): List[File] =
{
val descriptor: File = dir / "sbt" / "sbt.plugins"
if(plugins.isEmpty)
{
IO.delete(descriptor)
Nil
}
else
{
IO.writeLines(descriptor, plugins.toSeq.sorted)
descriptor :: Nil
}
}
def discoverPlugins: Initialize[Task[Set[String]]] = (compile, sbtPlugin, streams) map { (analysis, isPlugin, s) => if(isPlugin) discoverSbtPlugins(analysis, s.log) else Set.empty }
def discoverSbtPlugins(analysis: inc.Analysis, log: Logger): Set[String] =
{
val pluginClass = classOf[Plugin].getName
val discovery = Discovery(Set(pluginClass), Set.empty)( Tests allDefs analysis )
discovery collect { case (df, disc) if (disc.baseClasses contains pluginClass) && disc.isModule => df.name } toSet;
}
def copyResourcesTask =
(classDirectory, cacheDirectory, resources, resourceDirectories, streams) map { (target, cache, resrcs, dirs, s) =>
val cacheFile = cache / "copy-resources"
val mappings = (resrcs --- dirs) x (rebase(dirs, target) | flat(target))
s.log.debug("Copy resource mappings: " + mappings.mkString("\n\t","\n\t",""))
Sync(cacheFile)( mappings )
mappings
}
def runMainParser: (State, Seq[String]) => Parser[(String, Seq[String])] =
{
import DefaultParsers._
(state, mainClasses) => Space ~> token(NotSpace examples mainClasses.toSet) ~ spaceDelimited("<arg>")
}
def testOnlyParser: (State, Seq[String]) => Parser[(Seq[String],Seq[String])] =
{ (state, tests) =>
import DefaultParsers._
val selectTests = distinctParser(tests.toSet, true)
val options = (token(Space) ~> token("--") ~> spaceDelimited("<option>")) ?? Nil
selectTests ~ options
}
def distinctParser(exs: Set[String], raw: Boolean): Parser[Seq[String]] =
{
import DefaultParsers._
val base = token(Space) ~> token(NotSpace - "--" examples exs)
val recurse = base flatMap { ex =>
val (matching, notMatching) = exs.partition( GlobFilter(ex).accept _ )
distinctParser(notMatching, raw) map { result => if(raw) ex +: result else matching.toSeq ++ result }
}
recurse ?? Nil
}
def inAllDependencies[T](base: ProjectRef, key: ScopedSetting[T], structure: Load.BuildStructure): Seq[T] =
{
def deps(ref: ProjectRef): Seq[ProjectRef] =
Project.getProject(ref, structure).toList.flatMap { p =>
p.dependencies.map(_.project) ++ p.aggregate
}
inAllDeps(base, deps, key, structure.data)
}
def inAllDeps[T](base: ProjectRef, deps: ProjectRef => Seq[ProjectRef], key: ScopedSetting[T], data: Settings[Scope]): Seq[T] =
inAllProjects(Dag.topologicalSort(base)(deps), key, data)
def inAllProjects[T](allProjects: Seq[Reference], key: ScopedSetting[T], data: Settings[Scope]): Seq[T] =
allProjects.flatMap { p => key in p get data }
val CompletionsID = "completions"
def noAggregation = Seq(run, console, consoleQuick, consoleProject)
lazy val disableAggregation = noAggregation map disableAggregate
def disableAggregate(k: Scoped) =
aggregate in Scope.GlobalScope.copy(task = Select(k.key)) :== false
lazy val baseTasks: Seq[Setting[_]] = projectTasks ++ packageBase
lazy val baseClasspaths: Seq[Setting[_]] = Classpaths.publishSettings ++ Classpaths.baseSettings
lazy val configSettings: Seq[Setting[_]] = Classpaths.configSettings ++ configTasks ++ configPaths ++ packageConfig ++ Classpaths.compilerPluginConfig
lazy val compileSettings: Seq[Setting[_]] = configSettings ++ (mainRunMainTask +: mainRunTask +: addBaseSources)
lazy val testSettings: Seq[Setting[_]] = configSettings ++ testTasks
lazy val itSettings: Seq[Setting[_]] = inConfig(IntegrationTest)(testSettings)
lazy val defaultConfigs: Seq[Setting[_]] = inConfig(Compile)(compileSettings) ++ inConfig(Test)(testSettings) ++ inConfig(Runtime)(Classpaths.configSettings)
// settings that are not specific to a configuration
lazy val projectBaseSettings: Seq[Setting[_]] = projectCore ++ paths ++ baseClasspaths ++ baseTasks ++ compileBase ++ disableAggregation
lazy val defaultSettings: Seq[Setting[_]] = projectBaseSettings ++ defaultConfigs
}
object Classpaths
{
import Path._
import Keys._
import Scope.ThisScope
import Defaults._
import Attributed.{blank, blankSeq}
def concatDistinct[T](a: ScopedTaskable[Seq[T]], b: ScopedTaskable[Seq[T]]): Initialize[Task[Seq[T]]] = (a,b) map { (x,y) => (x ++ y).distinct }
def concat[T](a: ScopedTaskable[Seq[T]], b: ScopedTaskable[Seq[T]]): Initialize[Task[Seq[T]]] = (a,b) map ( _ ++ _)
def concatSettings[T](a: ScopedSetting[Seq[T]], b: ScopedSetting[Seq[T]]): Initialize[Seq[T]] = (a,b)(_ ++ _)
lazy val configSettings: Seq[Setting[_]] = Seq(
externalDependencyClasspath <<= concat(unmanagedClasspath, managedClasspath),
dependencyClasspath <<= concat(internalDependencyClasspath, externalDependencyClasspath),
fullClasspath <<= concatDistinct(exportedProducts, dependencyClasspath),
internalDependencyClasspath <<= internalDependencies,
unmanagedClasspath <<= unmanagedDependencies,
products <<= makeProducts,
productDirectories <<= compileInputs map (_.config.classesDirectory :: Nil),
exportedProducts <<= exportProductsTask,
classpathConfiguration <<= (internalConfigurationMap, configuration)( _ apply _ ),
managedClasspath <<= (classpathConfiguration, classpathTypes, update) map managedJars,
unmanagedJars <<= (configuration, unmanagedBase, classpathFilter, defaultExcludes in unmanagedJars) map { (config, base, filter, excl) =>
(base * (filter -- excl) +++ (base / config.name).descendentsExcept(filter, excl)).classpath
}
)
def defaultPackageKeys = Seq(packageBin, packageSrc, packageDoc)
lazy val defaultPackages: Seq[ScopedTask[File]] =
for(task <- defaultPackageKeys; conf <- Seq(Compile, Test)) yield (task in conf)
lazy val defaultArtifactTasks: Seq[ScopedTask[File]] = makePom +: defaultPackages
def packaged(pkgTasks: Seq[ScopedTask[File]]): Initialize[Task[Map[Artifact, File]]] =
enabledOnly(packagedArtifact.task, pkgTasks).map(_.join.map(_.toMap))
def artifactDefs(pkgTasks: Seq[ScopedTask[File]]): Initialize[Seq[Artifact]] =
enabledOnly(artifact, pkgTasks)
def enabledOnly[T](key: ScopedSetting[T], pkgTasks: Seq[ScopedTask[File]]): Initialize[Seq[T]] =
( forallIn(key, pkgTasks) zipWith forallIn(publishArtifact, pkgTasks) ) ( _ zip _ collect { case (a, true) => a } )
def forallIn[T](key: ScopedSetting[T], pkgTasks: Seq[ScopedTask[_]]): Initialize[Seq[T]] =
pkgTasks.map( pkg => key in pkg.scope in pkg ).join
val publishSettings: Seq[Setting[_]] = Seq(
publishMavenStyle in GlobalScope :== true,
publishArtifact in GlobalScope in Compile :== true,
publishArtifact in GlobalScope in Test:== false,
artifacts <<= artifactDefs(defaultArtifactTasks),
packagedArtifacts <<= packaged(defaultArtifactTasks),
makePom <<= (ivyModule, makePomConfiguration, streams) map { (module, config, s) => IvyActions.makePom(module, config, s.log); config.file },
packagedArtifact in makePom <<= (artifact in makePom, makePom) map pairID,
deliver <<= deliverTask(deliverConfiguration),
deliverLocal <<= deliverTask(deliverLocalConfiguration),
publish <<= publishTask(publishConfiguration, deliver),
publishLocal <<= publishTask(publishLocalConfiguration, deliverLocal)
)
val baseSettings: Seq[Setting[_]] = sbtClassifiersTasks ++ Seq(
conflictWarning in GlobalScope :== ConflictWarning.default("global"),
conflictWarning <<= (thisProjectRef, conflictWarning) { (ref, cw) => cw.copy(label = Project.display(ref)) },
unmanagedBase <<= baseDirectory / "lib",
normalizedName <<= name(StringUtilities.normalize),
description <<= description or name.identity,
homepage in GlobalScope :== None,
licenses in GlobalScope :== Nil,
organization <<= organization or normalizedName.identity,
organizationName in GlobalScope <<= organizationName or organization.identity,
organizationHomepage in GlobalScope <<= organizationHomepage or homepage.identity,
projectInfo <<= (name, description, homepage, licenses, organizationName, organizationHomepage) apply ModuleInfo,
classpathFilter in GlobalScope :== "*.jar" | "*.so" | "*.dll",
externalResolvers <<= (externalResolvers.task.? zipWith resolvers.identity) {
case (Some(delegated), Seq()) => delegated
case (_, rs) => task { Resolver.withDefaultResolvers(rs) }
},
fullResolvers <<= (projectResolver,externalResolvers,sbtPlugin,sbtResolver) map { (pr,rs,isPlugin,sr) =>
val base = pr +: rs
if(isPlugin) sr +: base else base
},
offline in GlobalScope :== false,
moduleName <<= normalizedName.identity,
defaultConfiguration in GlobalScope :== Some(Configurations.Compile),
defaultConfigurationMapping in GlobalScope <<= defaultConfiguration{ case Some(d) => "*->" + d.name; case None => "*->*" },
ivyPaths <<= (baseDirectory, appConfiguration) { (base, app) => new IvyPaths(base, bootIvyHome(app)) },
otherResolvers <<= publishTo(_.toList),
projectResolver <<= projectResolverTask,
projectDependencies <<= projectDependenciesTask,
libraryDependencies in GlobalScope :== Nil,
libraryDependencies <++= (autoScalaLibrary, sbtPlugin, scalaVersion) apply autoLibraryDependency,
allDependencies <<= (projectDependencies,libraryDependencies,sbtPlugin,sbtDependency) map { (projDeps, libDeps, isPlugin, sbtDep) =>
val base = projDeps ++ libDeps
if(isPlugin) sbtDep.copy(configurations = Some(Provided.name)) +: base else base
},
ivyLoggingLevel in GlobalScope :== UpdateLogging.Quiet,
ivyXML in GlobalScope :== NodeSeq.Empty,
ivyValidate in GlobalScope :== false,
ivyScala <<= ivyScala or (scalaHome, scalaVersion, scalaVersion in update) { (sh,v,vu) =>
Some(new IvyScala(v, Nil, filterImplicit = true, checkExplicit = true, overrideScalaVersion = sh.isEmpty, substituteCross = x => IvySbt.substituteCross(x, vu)))
},
moduleConfigurations in GlobalScope :== Nil,
publishTo in GlobalScope :== None,
artifactPath in makePom <<= artifactPathSetting(artifact in makePom),
publishArtifact in makePom <<= publishMavenStyle.identity,
artifact in makePom <<= moduleName(Artifact.pom),
projectID <<= (organization,moduleName,version,artifacts,crossPaths){ (org,module,version,as,crossEnabled) =>
ModuleID(org, module, version).cross(crossEnabled).artifacts(as : _*)
},
projectID <<= pluginProjectID,
resolvers in GlobalScope :== Nil,
projectDescriptors <<= depMap,
retrievePattern in GlobalScope :== Resolver.defaultRetrievePattern,
updateConfiguration <<= (retrieveConfiguration, ivyLoggingLevel)((conf,level) => new UpdateConfiguration(conf, false, level) ),
retrieveConfiguration <<= (managedDirectory, retrievePattern, retrieveManaged) { (libm, pattern, enabled) => if(enabled) Some(new RetrieveConfiguration(libm, pattern)) else None },
ivyConfiguration <<= mkIvyConfiguration,
ivyConfigurations <<= (autoCompilerPlugins, internalConfigurationMap, thisProject) { (auto, internalMap, project) =>
(project.configurations ++ project.configurations.map(internalMap) ++ (if(auto) CompilerPlugin :: Nil else Nil)).distinct
},
ivyConfigurations ++= Configurations.auxiliary,
moduleSettings <<= moduleSettings0,
makePomConfiguration <<= (artifactPath in makePom, projectInfo, pomExtra, pomPostProcess, pomIncludeRepository, pomAllRepositories) {
(file, minfo, extra, process, include, all) => new MakePomConfiguration(file, minfo, None, extra, process, include, all)
},
deliverLocalConfiguration <<= (crossTarget, ivyLoggingLevel) map { (outDir, level) => deliverConfig( outDir, logging = level ) },
deliverConfiguration <<= deliverLocalConfiguration.identity,
publishConfiguration <<= (packagedArtifacts, publishTo, publishMavenStyle, deliver, checksums in publish, ivyLoggingLevel) map { (arts, publishTo, mavenStyle, ivyFile, checks, level) =>
publishConfig(arts, if(mavenStyle) None else Some(ivyFile), resolverName = getPublishTo(publishTo).name, checksums = checks, logging = level)
},
publishLocalConfiguration <<= (packagedArtifacts, deliverLocal, checksums in publishLocal, ivyLoggingLevel) map {
(arts, ivyFile, checks, level) => publishConfig(arts, Some(ivyFile), checks, logging = level )
},
ivySbt <<= ivySbt0,
ivyModule <<= (ivySbt, moduleSettings) map { (ivySbt, settings) => new ivySbt.Module(settings) },
update <<= (ivyModule, thisProjectRef, updateConfiguration, cacheDirectory, scalaInstance, streams) map { (module, ref, config, cacheDirectory, si, s) =>
cachedUpdate(cacheDirectory / "update", Project.display(ref), module, config, Some(si), s.log)
},
update <<= (conflictWarning, update, streams) map { (config, report, s) => ConflictWarning(config, report, s.log); report },
transitiveClassifiers in GlobalScope :== Seq(SourceClassifier, DocClassifier),
classifiersModule in updateClassifiers <<= (projectID, update, transitiveClassifiers in updateClassifiers, ivyConfigurations in updateClassifiers) map { ( pid, up, classifiers, confs) =>
GetClassifiersModule(pid, up.allModules, confs, classifiers)
},
updateClassifiers <<= (ivySbt, classifiersModule in updateClassifiers, updateConfiguration, ivyScala, target in LocalRootProject, appConfiguration, streams) map { (is, mod, c, ivyScala, out, app, s) =>
withExcludes(out, mod.classifiers, lock(app)) { excludes =>
IvyActions.updateClassifiers(is, GetClassifiersConfiguration(mod, excludes, c, ivyScala), s.log)
}
},
sbtDependency in GlobalScope <<= appConfiguration { app =>
val id = app.provider.id
val base = ModuleID(id.groupID, id.name, id.version, crossVersion = id.crossVersioned)
IvySbt.substituteCross(base, app.provider.scalaProvider.version).copy(crossVersion = false)
}
)
def pluginProjectID: Initialize[ModuleID] = (sbtVersion in update, scalaVersion, projectID, sbtPlugin) { (sbtV, scalaV, pid, isPlugin) =>
if(isPlugin) sbtPluginExtra(pid, sbtV, scalaV) else pid
}
def ivySbt0: Initialize[Task[IvySbt]] =
(ivyConfiguration, credentials, streams) map { (conf, creds, s) =>
Credentials.register(creds, s.log)
new IvySbt(conf)
}
def moduleSettings0: Initialize[Task[ModuleSettings]] =
(projectID, allDependencies, ivyXML, ivyConfigurations, defaultConfiguration, ivyScala, ivyValidate, projectInfo) map {
(pid, deps, ivyXML, confs, defaultConf, ivyS, validate, pinfo) => new InlineConfiguration(pid, pinfo, deps, ivyXML, confs, defaultConf, ivyS, validate)
}
def sbtClassifiersTasks = inTask(updateSbtClassifiers)(Seq(
transitiveClassifiers in GlobalScope in updateSbtClassifiers ~= ( _.filter(_ != DocClassifier) ),
externalResolvers <<= (externalResolvers, appConfiguration) map { (defaultRs, ac) =>
bootRepositories(ac) getOrElse defaultRs
},
ivyConfiguration <<= (externalResolvers, ivyPaths, offline, checksums, appConfiguration, streams) map { (rs, paths, off, check, app, s) =>
new InlineIvyConfiguration(paths, rs, Nil, Nil, off, Option(lock(app)), check, s.log)
},
ivySbt <<= ivySbt0,
classifiersModule <<= (projectID, sbtDependency, transitiveClassifiers) map { ( pid, sbtDep, classifiers) =>
GetClassifiersModule(pid, sbtDep :: Nil, Configurations.Default :: Nil, classifiers)
},
updateSbtClassifiers in TaskGlobal <<= (ivySbt, classifiersModule, updateConfiguration, ivyScala, target in LocalRootProject, appConfiguration, streams) map {
(is, mod, c, ivyScala, out, app, s) =>
withExcludes(out, mod.classifiers, lock(app)) { excludes =>
IvyActions.transitiveScratch(is, "sbt", GetClassifiersConfiguration(mod, excludes, c, ivyScala), s.log)
}
}
))
def deliverTask(config: TaskKey[DeliverConfiguration]): Initialize[Task[File]] =
(ivyModule, config, update, streams) map { (module, config, _, s) => IvyActions.deliver(module, config, s.log) }
def publishTask(config: TaskKey[PublishConfiguration], deliverKey: TaskKey[_]): Initialize[Task[Unit]] =
(ivyModule, config, streams) map { (module, config, s) =>
IvyActions.publish(module, config, s.log)
}
import Cache._
import CacheIvy.{classpathFormat, /*publishIC,*/ updateIC, updateReportF, excludeMap}
def withExcludes(out: File, classifiers: Seq[String], lock: xsbti.GlobalLock)(f: Map[ModuleID, Set[String]] => UpdateReport): UpdateReport =
{
val exclName = "exclude_classifiers"
val file = out / exclName
lock(out / (exclName + ".lock"), new Callable[UpdateReport] { def call = {
val excludes = CacheIO.fromFile[Map[ModuleID, Set[String]]](excludeMap, Map.empty[ModuleID, Set[String]])(file)
val report = f(excludes)
val allExcludes = excludes ++ IvyActions.extractExcludes(report)
CacheIO.toFile(excludeMap)(allExcludes)(file)
IvyActions.addExcluded(report, classifiers, allExcludes)
}})
}
def cachedUpdate(cacheFile: File, label: String, module: IvySbt#Module, config: UpdateConfiguration, scalaInstance: Option[ScalaInstance], log: Logger): UpdateReport =
{
implicit val updateCache = updateIC
implicit val updateReport = updateReportF
type In = IvyConfiguration :+: ModuleSettings :+: UpdateConfiguration :+: HNil
def work = (_: In) match { case conf :+: settings :+: config :+: HNil =>
log.info("Updating " + label + "...")
val r = IvyActions.update(module, config, log)
log.info("Done updating.")
scalaInstance match { case Some(si) => substituteScalaFiles(si, r); case None => r }
}
val f =
Tracked.inputChanged(cacheFile / "inputs") { (inChanged: Boolean, in: In) =>
val outCache = Tracked.lastOutput[In, UpdateReport](cacheFile / "output") {
case (_, Some(out)) if !inChanged && out.allFiles.forall(_.exists) && out.cachedDescriptor.exists => out
case _ => work(in)
}
outCache(in)
}
f(module.owner.configuration :+: module.moduleSettings :+: config :+: HNil)
}
/*
// can't cache deliver/publish easily since files involved are hidden behind patterns. publish will be difficult to verify target-side anyway
def cachedPublish(cacheFile: File)(g: (IvySbt#Module, PublishConfiguration) => Unit, module: IvySbt#Module, config: PublishConfiguration) => Unit =
{ case module :+: config :+: HNil =>
/* implicit val publishCache = publishIC
val f = cached(cacheFile) { (conf: IvyConfiguration, settings: ModuleSettings, config: PublishConfiguration) =>*/
g(module, config)
/*}
f(module.owner.configuration :+: module.moduleSettings :+: config :+: HNil)*/
}*/
def defaultRepositoryFilter = (repo: MavenRepository) => !repo.root.startsWith("file:")
def getPublishTo(repo: Option[Resolver]): Resolver = repo getOrElse error("Repository for publishing is not specified.")
def deliverConfig(outputDirectory: File, status: String = "release", logging: UpdateLogging.Value = UpdateLogging.DownloadOnly) =
new DeliverConfiguration(deliverPattern(outputDirectory), status, None, logging)
def publishConfig(artifacts: Map[Artifact, File], ivyFile: Option[File], checksums: Seq[String], resolverName: String = "local", logging: UpdateLogging.Value = UpdateLogging.DownloadOnly) =
new PublishConfiguration(ivyFile, resolverName, artifacts, checksums, logging)
def deliverPattern(outputPath: File): String = (outputPath / "[artifact]-[revision](-[classifier]).[ext]").absolutePath
def projectDependenciesTask =
(thisProject, settings) map { (p, data) =>
p.dependencies flatMap { dep => (projectID in dep.project) get data map { _.copy(configurations = dep.configuration) } }
}
def depMap: Initialize[Task[Map[ModuleRevisionId, ModuleDescriptor]]] =
(thisProject, thisProjectRef, settings, streams) flatMap { (root, rootRef, data, s) =>
val dependencies = (p: (ProjectRef, ResolvedProject)) => p._2.dependencies.flatMap(pr => thisProject in pr.project get data map { (pr.project, _) })
depMap(Dag.topologicalSort((rootRef,root))(dependencies).dropRight(1), data, s.log)
}
def depMap(projects: Seq[(ProjectRef,ResolvedProject)], data: Settings[Scope], log: Logger): Task[Map[ModuleRevisionId, ModuleDescriptor]] =
projects.flatMap { case (p,_) => ivyModule in p get data }.join.map { mods =>
mods map { _.dependencyMapping(log) } toMap ;
}
def projectResolverTask: Initialize[Task[Resolver]] =
projectDescriptors map { m =>
new RawRepository(new ProjectResolver("inter-project", m))
}
def analyzed[T](data: T, analysis: inc.Analysis) = Attributed.blank(data).put(Keys.analysis, analysis)
def makeProducts: Initialize[Task[Seq[File]]] =
(compile, compileInputs, copyResources) map { (_, i, _) => i.config.classesDirectory :: Nil }
def exportProductsTask: Initialize[Task[Classpath]] =
(products.task, packageBin.task, exportJars, compile) flatMap { (psTask, pkgTask, useJars, analysis) =>
(if(useJars) Seq(pkgTask).join else psTask) map { _ map { f => analyzed(f, analysis) } }
}
def internalDependencies: Initialize[Task[Classpath]] =
(thisProjectRef, thisProject, classpathConfiguration, configuration, settings) flatMap internalDependencies0
def unmanagedDependencies: Initialize[Task[Classpath]] =
(thisProjectRef, thisProject, configuration, settings) flatMap unmanagedDependencies0
def mkIvyConfiguration: Initialize[Task[IvyConfiguration]] =
(fullResolvers, ivyPaths, otherResolvers, moduleConfigurations, offline, checksums in update, appConfiguration, streams) map { (rs, paths, other, moduleConfs, off, check, app, s) =>
new InlineIvyConfiguration(paths, rs, other, moduleConfs, off, Some(lock(app)), check, s.log)
}
import java.util.LinkedHashSet
import collection.JavaConversions.asScalaSet
def interSort(projectRef: ProjectRef, project: ResolvedProject, conf: Configuration, data: Settings[Scope]): Seq[(ProjectRef,String)] =
{
val visited = asScalaSet(new LinkedHashSet[(ProjectRef,String)])
def visit(p: ProjectRef, project: ResolvedProject, c: Configuration)
{
val applicableConfigs = allConfigs(c)
for(ac <- applicableConfigs) // add all configurations in this project
visited add (p, ac.name)
val masterConfs = names(getConfigurations(projectRef, data))
for( ResolvedClasspathDependency(dep, confMapping) <- project.dependencies)
{
val depProject = thisProject in dep get data getOrElse error("Invalid project: " + dep)
val configurations = getConfigurations(dep, data)
val mapping = mapped(confMapping, masterConfs, names(configurations), "compile", "*->compile")
// map master configuration 'c' and all extended configurations to the appropriate dependency configuration
for(ac <- applicableConfigs; depConfName <- mapping(ac.name))
{
for(depConf <- confOpt(configurations, depConfName) )
if( ! visited( (dep, depConfName) ) )
visit(dep, depProject, depConf)
}
}
}
visit(projectRef, project, conf)
visited.toSeq
}
def unmanagedDependencies0(projectRef: ProjectRef, project: ResolvedProject, conf: Configuration, data: Settings[Scope]): Task[Classpath] =
interDependencies(projectRef, project, conf, conf, data, true, unmanagedLibs)
def internalDependencies0(projectRef: ProjectRef, project: ResolvedProject, conf: Configuration, self: Configuration, data: Settings[Scope]): Task[Classpath] =
interDependencies(projectRef, project, conf, self, data, false, productsTask)
def interDependencies(projectRef: ProjectRef, project: ResolvedProject, conf: Configuration, self: Configuration, data: Settings[Scope], includeSelf: Boolean,
f: (ProjectRef, String, Settings[Scope]) => Task[Classpath]): Task[Classpath] =
{
val visited = interSort(projectRef, project, conf, data)
val tasks = asScalaSet(new LinkedHashSet[Task[Classpath]])
for( (dep, c) <- visited )
if(includeSelf || (dep != projectRef) || (conf.name != c && self.name != c))
tasks += f(dep, c, data)
(tasks.toSeq.join).map(_.flatten.distinct)
}
def mapped(confString: Option[String], masterConfs: Seq[String], depConfs: Seq[String], default: String, defaultMapping: String): String => Seq[String] =
{
lazy val defaultMap = parseMapping(defaultMapping, masterConfs, depConfs, _ :: Nil)
parseMapping(confString getOrElse default, masterConfs, depConfs, defaultMap)
}
def parseMapping(confString: String, masterConfs: Seq[String], depConfs: Seq[String], default: String => Seq[String]): String => Seq[String] =
union(confString.split(";") map parseSingleMapping(masterConfs, depConfs, default))
def parseSingleMapping( masterConfs: Seq[String], depConfs: Seq[String], default: String => Seq[String])(confString: String): String => Seq[String] =
{
val ms: Seq[(String,Seq[String])] =
trim(confString.split("->",2)) match {
case x :: Nil => for(a <- parseList(x, masterConfs)) yield (a,default(a))
case x :: y :: Nil => val target = parseList(y, depConfs); for(a <- parseList(x, masterConfs)) yield (a,target)
case _ => error("Invalid configuration '" + confString + "'") // shouldn't get here
}
val m = ms.toMap
s => m.getOrElse(s, Nil)
}
def union[A,B](maps: Seq[A => Seq[B]]): A => Seq[B] =
a => (Seq[B]() /: maps) { _ ++ _(a) } distinct;
def parseList(s: String, allConfs: Seq[String]): Seq[String] = (trim(s split ",") flatMap replaceWildcard(allConfs)).distinct
def replaceWildcard(allConfs: Seq[String])(conf: String): Seq[String] =
if(conf == "") Nil else if(conf == "*") allConfs else conf :: Nil
private def trim(a: Array[String]): List[String] = a.toList.map(_.trim)
def missingConfiguration(in: String, conf: String) =
error("Configuration '" + conf + "' not defined in '" + in + "'")
def allConfigs(conf: Configuration): Seq[Configuration] =
Dag.topologicalSort(conf)(_.extendsConfigs)
def getConfigurations(p: ResolvedReference, data: Settings[Scope]): Seq[Configuration] =
ivyConfigurations in p get data getOrElse Nil
def confOpt(configurations: Seq[Configuration], conf: String): Option[Configuration] =
configurations.find(_.name == conf)
def productsTask(dep: ResolvedReference, conf: String, data: Settings[Scope]): Task[Classpath] =
getClasspath(exportedProducts, dep, conf, data)
def unmanagedLibs(dep: ResolvedReference, conf: String, data: Settings[Scope]): Task[Classpath] =
getClasspath(unmanagedJars, dep, conf, data)
def getClasspath(key: TaskKey[Classpath], dep: ResolvedReference, conf: String, data: Settings[Scope]): Task[Classpath] =
( key in (dep, ConfigKey(conf)) ) get data getOrElse constant(Nil)
def defaultConfigurationTask(p: ResolvedReference, data: Settings[Scope]): Configuration =
flatten(defaultConfiguration in p get data) getOrElse Configurations.Default
def flatten[T](o: Option[Option[T]]): Option[T] = o flatMap idFun
lazy val typesafeSnapshots = typesafeRepo("snapshots")
lazy val typesafeResolver = typesafeRepo("releases")
def typesafeRepo(status: String) = Resolver.url("typesafe-ivy-"+status, new URL("http://repo.typesafe.com/typesafe/ivy-" + status + "/"))(Resolver.ivyStylePatterns)
def modifyForPlugin(plugin: Boolean, dep: ModuleID): ModuleID =
if(plugin) dep.copy(configurations = Some(Provided.name)) else dep
def autoLibraryDependency(auto: Boolean, plugin: Boolean, version: String): Seq[ModuleID] =
if(auto)
modifyForPlugin(plugin, ScalaArtifacts.libraryDependency(version)) :: Nil
else
Nil
import DependencyFilter._
def managedJars(config: Configuration, jarTypes: Set[String], up: UpdateReport): Classpath =
up.filter( configurationFilter(config.name) && artifactFilter(`type` = jarTypes) ).toSeq.map { case (conf, module, art, file) =>
Attributed(file)(AttributeMap.empty.put(artifact.key, art).put(moduleID.key, module).put(configuration.key, config))
} distinct;
def autoPlugins(report: UpdateReport): Seq[String] =
{
val pluginClasspath = report matching configurationFilter(CompilerPlugin.name)
classpath.ClasspathUtilities.compilerPlugins(pluginClasspath).map("-Xplugin:" + _.getAbsolutePath).toSeq
}
lazy val compilerPluginConfig = Seq(
scalacOptions <<= (scalacOptions, autoCompilerPlugins, update) map { (options, auto, report) =>
if(auto) options ++ autoPlugins(report) else options
}
)
def substituteScalaFiles(scalaInstance: ScalaInstance, report: UpdateReport): UpdateReport =
report.substitute { (configuration, module, arts) =>
import ScalaArtifacts._
(module.organization, module.name) match
{
case (Organization, LibraryID) => (Artifact(LibraryID), scalaInstance.libraryJar) :: Nil
case (Organization, CompilerID) => (Artifact(CompilerID), scalaInstance.compilerJar) :: Nil
case _ => arts
}
}
// try/catch for supporting earlier launchers
def bootIvyHome(app: xsbti.AppConfiguration): Option[File] =
try { Option(app.provider.scalaProvider.launcher.ivyHome) }
catch { case _: NoSuchMethodError => None }
def bootRepositories(app: xsbti.AppConfiguration): Option[Seq[Resolver]] =
try { Some(app.provider.scalaProvider.launcher.ivyRepositories.toSeq map bootRepository) }
catch { case _: NoSuchMethodError => None }
private[this] def bootRepository(repo: xsbti.Repository): Resolver =
{
import xsbti.Predefined
repo match
{
case m: xsbti.MavenRepository => MavenRepository(m.id, m.url.toString)
case i: xsbti.IvyRepository => Resolver.url(i.id, i.url)(Patterns(i.ivyPattern :: Nil, i.artifactPattern :: Nil, false))
case p: xsbti.PredefinedRepository => p.id match {
case Predefined.Local => Resolver.defaultLocal
case Predefined.MavenLocal => Resolver.mavenLocal
case Predefined.MavenCentral => DefaultMavenRepository
case Predefined.ScalaToolsReleases => ScalaToolsReleases
case Predefined.ScalaToolsSnapshots => ScalaToolsSnapshots
}
}
}
}
trait BuildExtra extends BuildCommon
{
import Defaults._
def addSbtPlugin(dependency: ModuleID): Setting[Seq[ModuleID]] =
libraryDependencies <+= (sbtVersion in update,scalaVersion) { (sbtV, scalaV) => sbtPluginExtra(dependency, sbtV, scalaV) }
def compilerPlugin(dependency: ModuleID): ModuleID =