forked from coursier/coursier
/
Tasks.scala
1422 lines (1165 loc) · 42.7 KB
/
Tasks.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package coursier
import java.io.{File, OutputStreamWriter}
import java.net.URL
import java.util.concurrent.{ConcurrentHashMap, ExecutorService, Executors}
import coursier.core.{Authentication, Publication}
import coursier.extra.Typelevel
import coursier.ivy.{IvyRepository, PropertiesPattern}
import coursier.Keys._
import coursier.Structure._
import coursier.util.Print
import sbt.librarymanagement._
import sbt.{Classpaths, Def, Resolver, UpdateReport}
import sbt.Keys._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Try
import scalaz.{-\/, \/-}
import scalaz.concurrent.{Strategy, Task}
object Tasks {
def allRecursiveInterDependencies(state: sbt.State, projectRef: sbt.ProjectRef) = {
def dependencies(map: Map[String, Seq[String]], id: String): Set[String] = {
def helper(map: Map[String, Seq[String]], acc: Set[String]): Set[String] =
if (acc.exists(map.contains)) {
val (kept, rem) = map.partition { case (k, _) => acc(k) }
helper(rem, acc ++ kept.valuesIterator.flatten)
} else
acc
helper(map - id, map.getOrElse(id, Nil).toSet)
}
val allProjectsDeps =
for (p <- structure(state).allProjects)
yield p.id -> p.dependencies.map(_.project.project)
val deps = dependencies(allProjectsDeps.toMap, projectRef.project)
structure(state).allProjectRefs.filter(p => deps(p.project))
}
private val slowReposBase = Seq(
"https://repo.typesafe.com/",
"https://repo.scala-sbt.org/",
"http://repo.typesafe.com/",
"http://repo.scala-sbt.org/"
)
private val fastReposBase = Seq(
"http://repo1.maven.org/",
"https://repo1.maven.org/"
)
def coursierResolversTask: Def.Initialize[sbt.Task[Seq[Resolver]]] = Def.taskDyn {
def url(res: Resolver): Option[String] =
res match {
case m: sbt.librarymanagement.MavenRepository =>
Some(m.root)
case u: sbt.URLRepository =>
u.patterns.artifactPatterns.headOption
.orElse(u.patterns.ivyPatterns.headOption)
case _ =>
None
}
def fastRepo(res: Resolver): Boolean =
url(res).exists(u => fastReposBase.exists(u.startsWith))
def slowRepo(res: Resolver): Boolean =
url(res).exists(u => slowReposBase.exists(u.startsWith))
val bootResOpt = bootResolvers.value
val overrideFlag = overrideBuildResolvers.value
val resultTask = bootResOpt.filter(_ => overrideFlag) match {
case Some(r) => Def.task(r)
case None =>
Def.taskDyn {
val extRes = externalResolvers.value
val isSbtPlugin = sbtPlugin.value
if (isSbtPlugin)
Def.task {
Seq(
sbtResolver.value,
Classpaths.sbtPluginReleases
) ++ extRes
}
else
Def.task(extRes)
}
}
Def.task {
val result = resultTask.value
val reorderResolvers = coursierReorderResolvers.value
val keepPreloaded = coursierKeepPreloaded.value
val result0 =
if (reorderResolvers && result.exists(fastRepo) && result.exists(slowRepo)) {
val (slow, other) = result.partition(slowRepo)
other ++ slow
} else
result
if (keepPreloaded)
result0
else
result0.filter { r =>
!r.name.startsWith("local-preloaded")
}
}
}
def coursierRecursiveResolversTask: Def.Initialize[sbt.Task[Seq[Resolver]]] =
Def.taskDyn {
val state = sbt.Keys.state.value
val projectRef = sbt.Keys.thisProjectRef.value
val projects = allRecursiveInterDependencies(state, projectRef)
val t = coursierResolvers
.forAllProjects(state, projectRef +: projects)
.map(_.values.toVector.flatten)
Def.task(t.value)
}
def coursierFallbackDependenciesTask: Def.Initialize[sbt.Task[Seq[(Module, String, URL, Boolean)]]] =
Def.taskDyn {
val state = sbt.Keys.state.value
val projectRef = sbt.Keys.thisProjectRef.value
val projects = allRecursiveInterDependencies(state, projectRef)
val allDependenciesTask = allDependencies
.forAllProjects(state, projectRef +: projects)
.map(_.values.toVector.flatten)
Def.task {
val allDependencies = allDependenciesTask.value
FromSbt.fallbackDependencies(
allDependencies,
scalaVersion.in(projectRef).get(state),
scalaBinaryVersion.in(projectRef).get(state)
)
}
}
def coursierProjectTask: Def.Initialize[sbt.Task[Project]] =
Def.taskDyn {
val state = sbt.Keys.state.value
val projectRef = sbt.Keys.thisProjectRef.value
// should projectID.configurations be used instead?
val configurations = ivyConfigurations.in(projectRef).get(state)
val allDependenciesTask = allDependencies.in(projectRef).get(state)
lazy val projId = projectID.in(projectRef).get(state)
lazy val sv = scalaVersion.in(projectRef).get(state)
lazy val sbv = scalaBinaryVersion.in(projectRef).get(state)
lazy val exclusions = {
var anyNonSupportedExclusionRule = false
val res = excludeDependencies
.in(projectRef)
.get(state)
.flatMap { rule =>
if (rule.artifact != "*" || rule.configurations.nonEmpty) {
state.log.warn(s"Unsupported exclusion rule $rule")
anyNonSupportedExclusionRule = true
Nil
} else
Seq(
(rule.organization, FromSbt.sbtCrossVersionName(rule.name, rule.crossVersion, sv, sbv))
)
}
.toSet
if (anyNonSupportedExclusionRule)
state.log.warn("Only supported exclusion rule fields: organization, name")
res
}
Def.task {
val allDependencies = allDependenciesTask.value
val configMap = configurations.map(cfg => cfg.name -> cfg.extendsConfigs.map(_.name)).toMap
val proj = FromSbt.project(
projId,
allDependencies,
configMap,
sv,
sbv
)
proj.copy(
dependencies = proj.dependencies.map {
case (config, dep) =>
(config, dep.copy(exclusions = dep.exclusions ++ exclusions))
}
)
}
}
def coursierInterProjectDependenciesTask: Def.Initialize[sbt.Task[Seq[Project]]] =
Def.taskDyn {
val state = sbt.Keys.state.value
val projectRef = sbt.Keys.thisProjectRef.value
val projects = allRecursiveInterDependencies(state, projectRef)
val t = coursierProject.forAllProjects(state, projects).map(_.values.toVector)
Def.task(t.value)
}
def coursierPublicationsTask(
configsMap: (sbt.Configuration, String)*
): Def.Initialize[sbt.Task[Seq[(String, Publication)]]] =
Def.task {
val state = sbt.Keys.state.value
val projectRef = sbt.Keys.thisProjectRef.value
val projId = sbt.Keys.projectID.value
val sv = sbt.Keys.scalaVersion.value
val sbv = sbt.Keys.scalaBinaryVersion.value
val ivyConfs = sbt.Keys.ivyConfigurations.value
val sourcesConfigOpt =
if (ivyConfigurations.value.exists(_.name == "sources"))
Some("sources")
else
None
val docsConfigOpt =
if (ivyConfigurations.value.exists(_.name == "docs"))
Some("docs")
else
None
val sbtBinArtifacts =
for ((config, targetConfig) <- configsMap) yield {
val publish = publishArtifact
.in(projectRef)
.in(packageBin)
.in(config)
.getOrElse(state, false)
if (publish)
artifact
.in(projectRef)
.in(packageBin)
.in(config)
.find(state)
.map(targetConfig -> _)
else
None
}
val sbtSourceArtifacts =
for ((config, targetConfig) <- configsMap) yield {
val publish = publishArtifact
.in(projectRef)
.in(packageSrc)
.in(config)
.getOrElse(state, false)
if (publish)
artifact
.in(projectRef)
.in(packageSrc)
.in(config)
.find(state)
.map(sourcesConfigOpt.getOrElse(targetConfig) -> _)
else
None
}
val sbtDocArtifacts =
for ((config, targetConfig) <- configsMap) yield {
val publish = publishArtifact
.in(projectRef)
.in(packageDoc)
.in(config)
.getOrElse(state, false)
if (publish)
artifact
.in(projectRef)
.in(packageDoc)
.in(config)
.find(state)
.map(docsConfigOpt.getOrElse(targetConfig) -> _)
else
None
}
val sbtArtifacts = sbtBinArtifacts ++ sbtSourceArtifacts ++ sbtDocArtifacts
def artifactPublication(artifact: sbt.Artifact) = {
val name = FromSbt.sbtCrossVersionName(
artifact.name,
projId.crossVersion,
sv,
sbv
)
Publication(
name,
artifact.`type`,
artifact.extension,
artifact.classifier.getOrElse("")
)
}
val sbtArtifactsPublication = sbtArtifacts.collect {
case Some((config, artifact)) =>
config -> artifactPublication(artifact)
}
val stdArtifactsSet = sbtArtifacts.flatMap(_.map { case (_, a) => a }.toSeq).toSet
// Second-way of getting artifacts from SBT
// No obvious way of getting the corresponding publishArtifact value for the ones
// only here, it seems.
val extraSbtArtifacts = artifacts.in(projectRef).getOrElse(state, Nil)
.filterNot(stdArtifactsSet)
// Seems that SBT does that - if an artifact has no configs,
// it puts it in all of them. See for example what happens to
// the standalone JAR artifact of the coursier cli module.
def allConfigsIfEmpty(configs: Iterable[ConfigRef]): Iterable[ConfigRef] =
if (configs.isEmpty) ivyConfs.filter(_.isPublic).map(c => ConfigRef(c.name)) else configs
val extraSbtArtifactsPublication = for {
artifact <- extraSbtArtifacts
config <- allConfigsIfEmpty(artifact.configurations.map(x => ConfigRef(x.name)))
// FIXME If some configurations from artifact.configurations are not public, they may leak here :\
} yield config.name -> artifactPublication(artifact)
sbtArtifactsPublication ++ extraSbtArtifactsPublication
}
def coursierConfigurationsTask(shadedConfig: Option[(String, String)]) = Def.task {
val configs0 = ivyConfigurations
.value
.map { config =>
config.name -> config.extendsConfigs.map(_.name)
}
.toMap
def allExtends(c: String) = {
// possibly bad complexity
def helper(current: Set[String]): Set[String] = {
val newSet = current ++ current.flatMap(configs0.getOrElse(_, Nil))
if ((newSet -- current).nonEmpty)
helper(newSet)
else
newSet
}
helper(Set(c))
}
val map = configs0.map {
case (config, _) =>
config -> allExtends(config)
}
map ++ shadedConfig.toSeq.flatMap {
case (baseConfig, shadedConfig) =>
Seq(
baseConfig -> (map.getOrElse(baseConfig, Set(baseConfig)) + shadedConfig),
shadedConfig -> map.getOrElse(shadedConfig, Set(shadedConfig))
)
}
}
private[coursier] final case class ResolutionCacheKey(
project: Project,
repositories: Seq[Repository],
userEnabledProfiles: Set[String],
resolution: Map[Set[String], Resolution],
sbtClassifiers: Boolean
)
private[coursier] final case class ReportCacheKey(
project: Project,
resolution: Map[Set[String], Resolution],
withClassifiers: Boolean,
sbtClassifiers: Boolean,
ignoreArtifactErrors: Boolean
)
private[coursier] val resolutionsCache = new ConcurrentHashMap[ResolutionCacheKey, Map[Set[String], Resolution]]
// these may actually not need to be cached any more, now that the resolutions
// are cached
private[coursier] val reportsCache = new ConcurrentHashMap[ReportCacheKey, UpdateReport]
private def forcedScalaModules(
scalaOrganization: String,
scalaVersion: String
): Map[Module, String] =
Map(
Module(scalaOrganization, "scala-library") -> scalaVersion,
Module(scalaOrganization, "scala-compiler") -> scalaVersion,
Module(scalaOrganization, "scala-reflect") -> scalaVersion,
Module(scalaOrganization, "scalap") -> scalaVersion
)
private def createLogger() = new TermDisplay(new OutputStreamWriter(System.err))
private[coursier] def exceptionPatternParser(): String => coursier.ivy.Pattern = {
val props = sys.props.toMap
val extraProps = new ArrayBuffer[(String, String)]
def addUriProp(key: String): Unit =
for (b <- props.get(key)) {
val uri = new File(b).toURI.toString
extraProps += s"$key.uri" -> uri
}
addUriProp("sbt.global.base")
addUriProp("user.home")
{
s =>
val p = PropertiesPattern.parse(s) match {
case -\/(err) =>
throw new Exception(s"Cannot parse pattern $s: $err")
case \/-(p) =>
p
}
p.substituteProperties(props ++ extraProps) match {
case -\/(err) =>
throw new Exception(err)
case \/-(p) =>
p
}
}
}
private def globalPluginPatterns(sbtVersion: String): Seq[coursier.ivy.Pattern] = {
// FIXME get the 0.13 automatically?
val defaultRawPattern = s"$${sbt.global.base.uri-$${user.home.uri}/.sbt/$sbtVersion}/plugins/target" +
"/resolution-cache/" +
"[organization]/[module](/scala_[scalaVersion])(/sbt_[sbtVersion])/[revision]/resolved.xml.[ext]"
// seems to be required in more recent versions of sbt (since 0.13.16?)
val extraRawPattern = s"$${sbt.global.base.uri-$${user.home.uri}/.sbt/$sbtVersion}/plugins/target" +
"(/scala-[scalaVersion])(/sbt-[sbtVersion])" +
"/resolution-cache/" +
"[organization]/[module](/scala_[scalaVersion])(/sbt_[sbtVersion])/[revision]/resolved.xml.[ext]"
Seq(
defaultRawPattern,
extraRawPattern
).map(exceptionPatternParser())
}
def parentProjectCacheTask: Def.Initialize[sbt.Task[Map[Seq[sbt.Resolver],Seq[coursier.ProjectCache]]]] =
Def.taskDyn {
val state = sbt.Keys.state.value
val projectRef = sbt.Keys.thisProjectRef.value
val projectDeps = structure(state).allProjects
.find(_.id == projectRef.project)
.map(_.dependencies.map(_.project.project).toSet)
.getOrElse(Set.empty)
val projects = structure(state).allProjectRefs.filter(p => projectDeps(p.project))
val t =
for {
m <- coursierRecursiveResolvers.forAllProjects(state, projects)
n <- coursierResolutions.forAllProjects(state, m.keys.toSeq)
} yield
n.foldLeft(Map.empty[Seq[Resolver], Seq[ProjectCache]]) {
case (caches, (ref, resolutions)) =>
val mainResOpt = resolutions.collectFirst {
case (k, v) if k("compile") => v
}
val r = for {
resolvers <- m.get(ref)
resolution <- mainResOpt
} yield
caches.updated(resolvers, resolution.projectCache +: caches.getOrElse(resolvers, Seq.empty))
r.getOrElse(caches)
}
Def.task(t.value)
}
def ivyGraphsTask = Def.task {
// probably bad complexity, but that shouldn't matter given the size of the graphs involved...
val p = coursierProject.value
final class Wrapper(val set: mutable.HashSet[String]) {
def ++=(other: Wrapper): this.type = {
set ++= other.set
this
}
}
val sets =
new mutable.HashMap[String, Wrapper] ++= p.configurations.map {
case (k, l) =>
val s = new mutable.HashSet[String]()
s ++= l
s += k
k -> new Wrapper(s)
}
for (k <- p.configurations.keys) {
val s = sets(k)
var foundNew = true
while (foundNew) {
foundNew = false
for (other <- s.set.toVector) {
val otherS = sets(other)
if (!otherS.eq(s)) {
s ++= otherS
sets += other -> s
foundNew = true
}
}
}
}
sets.values.toVector.distinct.map(_.set.toSet)
}
private val noOptionalFilter: Option[Dependency => Boolean] = Some(dep => !dep.optional)
private val typelevelOrgSwap: Option[Dependency => Dependency] = Some(Typelevel.swap(_))
def resolutionsTask(
sbtClassifiers: Boolean = false
): Def.Initialize[sbt.Task[Map[Set[String], coursier.Resolution]]] = Def.taskDyn {
val projectName = thisProjectRef.value.project
val sv = scalaVersion.value
val sbv = scalaBinaryVersion.value
val currentProjectTask: sbt.Def.Initialize[sbt.Task[(Project, Seq[(Module, String, URL, Boolean)], Seq[Set[String]])]] =
if (sbtClassifiers)
Def.task {
val cm = coursierSbtClassifiersModule.value
val proj = FromSbt.sbtClassifiersProject(cm, sv, sbv)
val fallbackDeps = FromSbt.fallbackDependencies(
cm.dependencies,
sv,
sbv
)
(proj, fallbackDeps, Vector(cm.configurations.map(_.name).toSet))
}
else
Def.task {
val baseConfigGraphs = coursierConfigGraphs.value
(coursierProject.value.copy(publications = coursierPublications.value), coursierFallbackDependencies.value, baseConfigGraphs)
}
val interProjectDependencies = coursierInterProjectDependencies.value
val parallelDownloads = coursierParallelDownloads.value
val checksums = coursierChecksums.value
val maxIterations = coursierMaxIterations.value
val cachePolicies = coursierCachePolicies.value
val ttl = coursierTtl.value
val cache = coursierCache.value
val log = streams.value.log
// are these always defined? (e.g. for Java only projects?)
val so = scalaOrganization.value
val userForceVersions = dependencyOverrides
.value
.map(FromSbt.moduleVersion(_, sv, sbv))
.toMap
val resolversTask =
if (sbtClassifiers)
Def.task(coursierSbtResolvers.value)
else
Def.task(coursierRecursiveResolvers.value.distinct)
val verbosityLevel = coursierVerbosity.value
val userEnabledProfiles = mavenProfiles.value
val typelevel = scalaOrganization.value == Typelevel.typelevelOrg
val globalPluginsRepos =
for (p <- globalPluginPatterns(sbtBinaryVersion.value))
yield IvyRepository.fromPattern(
p,
withChecksums = false,
withSignatures = false,
withArtifacts = false
)
val interProjectRepo = InterProjectRepository(interProjectDependencies)
val ivyHome = sys.props.getOrElse(
"ivy.home",
new File(sys.props("user.home")).toURI.getPath + ".ivy2"
)
val sbtIvyHome = sys.props.getOrElse(
"sbt.ivy.home",
ivyHome
)
val ivyProperties = Map(
"ivy.home" -> ivyHome,
"sbt.ivy.home" -> sbtIvyHome
) ++ sys.props
val useSbtCredentials = coursierUseSbtCredentials.value
val authenticationByHostTask =
if (useSbtCredentials)
Def.task {
sbt.Keys.credentials.value
.flatMap {
case dc: sbt.DirectCredentials => List(dc)
case fc: sbt.FileCredentials =>
sbt.Credentials.loadCredentials(fc.path) match {
case Left(err) =>
log.warn(s"$err, ignoring it")
Nil
case Right(dc) => List(dc)
}
}
.map { c =>
c.host -> Authentication(c.userName, c.passwd)
}
.toMap
}
else
Def.task(Map.empty[String, Authentication])
val authenticationByRepositoryId = coursierCredentials.value.mapValues(_.authentication)
def resTask(
currentProject: Project,
fallbackDependencies: Seq[(Module, String, URL, Boolean)],
configGraphs: Seq[Set[String]],
repositories: Seq[Repository],
internalRepositories: Seq[Repository],
allStartRes: Map[Set[String], coursier.Resolution]
) = Def.task {
def resolution(startRes: Resolution) = {
var pool: ExecutorService = null
var resLogger: TermDisplay = null
val printOptionalMessage = verbosityLevel >= 0 && verbosityLevel <= 1
val res = try {
pool = Executors.newFixedThreadPool(parallelDownloads, Strategy.DefaultDaemonThreadFactory)
resLogger = createLogger()
val fetch = Fetch.from(
repositories,
Cache.fetch(cache, cachePolicies.head, checksums = checksums, logger = Some(resLogger), pool = pool, ttl = ttl),
cachePolicies.tail.map(p =>
Cache.fetch(cache, p, checksums = checksums, logger = Some(resLogger), pool = pool, ttl = ttl)
): _*
)
def depsRepr(deps: Seq[(String, Dependency)]) =
deps.map { case (config, dep) =>
s"${dep.module}:${dep.version}:$config->${dep.configuration}"
}.sorted.distinct
if (verbosityLevel >= 2) {
val repoReprs = repositories.map {
case r: IvyRepository =>
s"ivy:${r.pattern}"
case r: InterProjectRepository =>
"inter-project"
case r: MavenRepository =>
r.root
case r =>
// should not happen
r.toString
}
log.info(
"Repositories:\n" +
repoReprs.map(" " + _).mkString("\n")
)
}
val initialMessage =
Seq(
if (verbosityLevel >= 0)
Seq(s"Updating $projectName" + (if (sbtClassifiers) " (sbt classifiers)" else ""))
else
Nil,
if (verbosityLevel >= 2)
depsRepr(currentProject.dependencies).map(depRepr =>
s" $depRepr"
)
else
Nil
).flatten.mkString("\n")
if (verbosityLevel >= 2)
log.info(initialMessage)
resLogger.init(if (printOptionalMessage) log.info(initialMessage))
startRes
.process
.run(fetch, maxIterations)
.unsafePerformSyncAttempt
.leftMap(ex =>
ResolutionError.UnknownException(ex)
.throwException()
)
.merge
} finally {
if (pool != null)
pool.shutdown()
if (resLogger != null)
if ((resLogger.stopDidPrintSomething() && printOptionalMessage) || verbosityLevel >= 2)
log.info(s"Resolved $projectName dependencies")
}
if (!res.isDone)
ResolutionError.MaximumIterationsReached
.throwException()
if (res.conflicts.nonEmpty) {
val projCache = res.projectCache.mapValues { case (_, p) => p }
ResolutionError.Conflicts(
"Conflict(s) in dependency resolution:\n " +
Print.dependenciesUnknownConfigs(res.conflicts.toVector, projCache)
).throwException()
}
if (res.metadataErrors.nonEmpty) {
val internalRepositoriesLen = internalRepositories.length
val errors =
if (repositories.length > internalRepositoriesLen)
// drop internal repository errors
res.metadataErrors.map {
case (dep, errs) =>
dep -> errs.drop(internalRepositoriesLen)
}
else
res.metadataErrors
ResolutionError.MetadataDownloadErrors(errors)
.throwException()
}
res
}
// let's update only one module at once, for a better output
// Downloads are already parallel, no need to parallelize further anyway
synchronized {
allStartRes.map {
case (config, startRes) =>
config -> resolution(startRes)
}
}
}
Def.taskDyn {
val (currentProject, fallbackDependencies, configGraphs) = currentProjectTask.value
val resolvers = resolversTask.value
// TODO Warn about possible duplicated modules from source repositories?
val authenticationByHost = authenticationByHostTask.value
val fallbackDependenciesRepositories =
if (fallbackDependencies.isEmpty)
Nil
else {
val map = fallbackDependencies.map {
case (mod, ver, url, changing) =>
(mod, ver) -> ((url, changing))
}.toMap
Seq(
FallbackDependenciesRepository(map)
)
}
if (verbosityLevel >= 2) {
log.info("InterProjectRepository")
for (p <- interProjectDependencies)
log.info(s" ${p.module}:${p.version}")
}
def withAuthenticationByHost(repo: Repository, credentials: Map[String, Authentication]): Repository = {
def httpHost(s: String) =
if (s.startsWith("http://") || s.startsWith("https://"))
Try(Cache.url(s).getHost).toOption
else
None
repo match {
case m: MavenRepository =>
if (m.authentication.isEmpty)
httpHost(m.root).flatMap(credentials.get).fold(m) { auth =>
m.copy(authentication = Some(auth))
}
else
m
case i: IvyRepository =>
if (i.authentication.isEmpty) {
val base = i.pattern.chunks.takeWhile {
case _: coursier.ivy.Pattern.Chunk.Const => true
case _ => false
}.map(_.string).mkString
httpHost(base).flatMap(credentials.get).fold(i) { auth =>
i.copy(authentication = Some(auth))
}
} else
i
case _ =>
repo
}
}
val internalRepositories = globalPluginsRepos :+ interProjectRepo
val repositories =
internalRepositories ++
resolvers.flatMap { resolver =>
FromSbt.repository(
resolver,
ivyProperties,
log,
authenticationByRepositoryId.get(resolver.name)
)
}.map(withAuthenticationByHost(_, authenticationByHost)) ++
fallbackDependenciesRepositories
val parentProjectCache: ProjectCache = coursierParentProjectCache.value
.get(resolvers)
.map(_.foldLeft[ProjectCache](Map.empty)(_ ++ _))
.getOrElse(Map.empty)
def startRes(configs: Set[String]) = Resolution(
currentProject
.dependencies
.collect {
case (config, dep) if configs(config) =>
dep
}
.toSet,
filter = noOptionalFilter,
userActivations =
if (userEnabledProfiles.isEmpty)
None
else
Some(userEnabledProfiles.iterator.map(_ -> true).toMap),
forceVersions =
// order matters here
userForceVersions ++
(if (configs("compile") || configs("scala-tool")) forcedScalaModules(so, sv) else Map()) ++
interProjectDependencies.map(_.moduleVersion),
projectCache = parentProjectCache,
mapDependencies = if (typelevel && (configs("compile") || configs("scala-tool"))) typelevelOrgSwap else None
)
val allStartRes = configGraphs.map(configs => configs -> startRes(configs)).toMap
val key = ResolutionCacheKey(
currentProject,
repositories,
userEnabledProfiles,
allStartRes,
sbtClassifiers
)
Option(resolutionsCache.get(key)) match {
case Some(res) =>
Def.task(res)
case None =>
val t = resTask(
currentProject,
fallbackDependencies,
configGraphs,
repositories,
internalRepositories,
allStartRes
)
t.map { res =>
resolutionsCache.put(key, res)
res
}
}
}
}
def artifactFilesOrErrors(
withClassifiers: Boolean,
sbtClassifiers: Boolean = false,
ignoreArtifactErrors: Boolean = false,
includeSignatures: Boolean = false
) = Def.taskDyn {
val projectName = thisProjectRef.value.project
val parallelDownloads = coursierParallelDownloads.value
val artifactsChecksums = coursierArtifactsChecksums.value
val cachePolicies = coursierCachePolicies.value
val ttl = coursierTtl.value
val cache = coursierCache.value
val log = streams.value.log
val verbosityLevel = coursierVerbosity.value
val resTask: sbt.Def.Initialize[sbt.Task[Seq[Resolution]]] =
if (withClassifiers && sbtClassifiers)
Def.task(Seq(coursierSbtClassifiersResolution.value))
else
Def.task(coursierResolutions.value.values.toVector)
val classifiersTask: sbt.Def.Initialize[sbt.Task[Option[Seq[String]]]] =
if (withClassifiers) {
if (sbtClassifiers)
Def.task(Some(coursierSbtClassifiersModule.value.classifiers))
else
Def.task(Some(transitiveClassifiers.value))
} else
Def.task(None)
Def.task {
val classifiers = classifiersTask.value
val res = resTask.value
val allArtifacts0 =
classifiers match {
case None => res.flatMap(_.artifacts(withOptional = true))
case Some(cl) => res.flatMap(_.classifiersArtifacts(cl))
}
val allArtifacts =
if (includeSignatures)
allArtifacts0.flatMap { a =>
val sigOpt = a.extra.get("sig").map(_.copy(attributes = Attributes()))
Seq(a) ++ sigOpt.toSeq
}
else
allArtifacts0