-
Notifications
You must be signed in to change notification settings - Fork 199
/
Resolver.kt
465 lines (422 loc) · 17.5 KB
/
Resolver.kt
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
package com.github.benmanes.gradle.versions.updates
import com.github.benmanes.gradle.versions.updates.resolutionstrategy.ResolutionStrategyWithCurrent
import groovy.xml.XmlSlurper
import groovy.xml.slurpersupport.GPathResult
import groovy.xml.slurpersupport.NodeChildren
import org.codehaus.groovy.runtime.DefaultGroovyMethods.asBoolean
import org.codehaus.groovy.runtime.DefaultGroovyMethods.getMetaClass
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.artifacts.ComponentMetadata
import org.gradle.api.artifacts.ComponentSelection
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.DependencyConstraint
import org.gradle.api.artifacts.ExternalDependency
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.ModuleVersionIdentifier
import org.gradle.api.artifacts.ResolvedDependency
import org.gradle.api.artifacts.UnresolvedDependency
import org.gradle.api.artifacts.repositories.ArtifactRepository
import org.gradle.api.artifacts.repositories.FlatDirectoryArtifactRepository
import org.gradle.api.artifacts.repositories.IvyArtifactRepository
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
import org.gradle.api.artifacts.result.ResolvedArtifactResult
import org.gradle.api.attributes.Attribute
import org.gradle.api.attributes.HasConfigurableAttributes
import org.gradle.api.attributes.java.TargetJvmVersion
import org.gradle.api.internal.artifacts.DefaultModuleVersionIdentifier
import org.gradle.api.internal.artifacts.dependencies.DefaultProjectDependencyConstraint
import org.gradle.internal.component.external.model.DefaultModuleComponentIdentifier
import org.gradle.maven.MavenModule
import org.gradle.maven.MavenPomArtifact
import java.io.File
import java.util.concurrent.ConcurrentHashMap
/**
* Resolves the configuration to determine the version status of its dependencies.
*/
class Resolver(
private val project: Project,
private val resolutionStrategy: Action<in ResolutionStrategyWithCurrent>?,
private val checkConstraints: Boolean,
) {
private var projectUrls = ConcurrentHashMap<ModuleVersionIdentifier, ProjectUrl>()
init {
logRepositories()
}
/** Returns the version status of the configuration's dependencies at the given revision. */
fun resolve(
configuration: Configuration,
revision: String,
): Set<DependencyStatus> {
val coordinates = getCurrentCoordinates(configuration)
val latestConfiguration = createLatestConfiguration(configuration, revision, coordinates)
val lenient = latestConfiguration.resolvedConfiguration.lenientConfiguration
val resolved = lenient.firstLevelModuleDependencies
val unresolved = lenient.unresolvedModuleDependencies
return getStatus(coordinates, resolved, unresolved)
}
/** Returns the version status of the configuration's dependencies. */
private fun getStatus(
coordinates: Map<Coordinate.Key, Coordinate>,
resolved: Set<ResolvedDependency>,
unresolved: Set<UnresolvedDependency>,
): Set<DependencyStatus> {
val result = hashSetOf<DependencyStatus>()
for (dependency in resolved) {
val resolvedCoordinate = Coordinate.from(dependency.module.id)
val originalCoordinate = coordinates[resolvedCoordinate.key]
val coord = originalCoordinate ?: resolvedCoordinate
val projectUrl = getProjectUrl(dependency.module.id)
result.add(DependencyStatus(coord, resolvedCoordinate.version, projectUrl))
}
for (dependency in unresolved) {
val resolvedCoordinate = Coordinate.from(dependency.selector)
val originalCoordinate = coordinates[resolvedCoordinate.key]
val coord = originalCoordinate ?: resolvedCoordinate
result.add(DependencyStatus(coord, dependency))
}
return result
}
/** Returns a copy of the configuration where dependencies will be resolved up to the revision. */
private fun createLatestConfiguration(
configuration: Configuration,
revision: String,
currentCoordinates: Map<Coordinate.Key, Coordinate>,
): Configuration {
val latest =
configuration.allDependencies
.filterIsInstance<ExternalDependency>()
.mapTo(mutableListOf()) { dependency ->
createQueryDependency(dependency as ModuleDependency)
}
// Common use case for dependency constraints is a java-platform BOM project or to control
// version of transitive dependency.
if (supportsConstraints(configuration)) {
for (dependency in configuration.allDependencyConstraints) {
if (dependency !is DefaultProjectDependencyConstraint) {
latest.add(createQueryDependency(dependency))
}
}
}
val copy = configuration.copyRecursive().setTransitive(false)
// https://github.com/ben-manes/gradle-versions-plugin/issues/592
// allow resolution of dynamic latest versions regardless of the original strategy
if (asBoolean(
getMetaClass(copy.resolutionStrategy)
.hasProperty(copy.resolutionStrategy, "failOnDynamicVersions"),
)
) {
getMetaClass(copy.resolutionStrategy)
.setProperty(copy.resolutionStrategy, "failOnDynamicVersions", false)
}
// Resolve using the latest version of explicitly declared dependencies and retains Kotlin's
// inherited dependencies (importantly, including stdlib) from the super configurations. This
// is required for variant resolution, but the full set can break consumer capability matching.
val isKotlinDep = { dependency: ExternalDependency -> (dependency.group?.startsWith("org.jetbrains.kotlin") ?: false) }
val inheritedKotlin =
configuration.allDependencies
.filterIsInstance<ExternalDependency>()
.filter { d -> isKotlinDep(d) }
.minus(configuration.dependencies)
// Adds the Kotlin 1.2.x legacy metadata to assist in variant selection
val metadata = project.configurations.findByName("commonMainMetadataElements")
if (metadata == null) {
val compile = project.configurations.findByName("compile")
if (compile != null) {
addAttributes(copy, compile) { key -> key.contains("kotlin") }
}
} else {
addAttributes(copy, metadata)
}
copy.dependencies.clear()
copy.dependencies.addAll(latest)
copy.dependencies.addAll(inheritedKotlin)
addRevisionFilter(copy, revision)
addAttributes(copy, configuration)
addCustomResolutionStrategy(copy, currentCoordinates)
disableAutoTargetJvm(copy)
return copy
}
/** Returns a variant of the provided dependency used for querying the latest version. */
private fun createQueryDependency(dependency: ModuleDependency): Dependency {
// If no version was specified then it may be intended to be resolved by another plugin
// (e.g. the dependency-management-plugin for BOMs) or is an explicit file (e.g. libs/*.jar).
// In the case of another plugin we use "+" in the hope that the plugin will not restrict the
// query (see issue #97). Otherwise, if it's a file then use "none" to pass it through.
val version =
if (dependency.version == null) {
if (dependency.artifacts.isEmpty()) {
"+"
} else {
"none"
}
} else {
"+"
}
// Format the query with an optional classifier and extension
var query = "${dependency.group.orEmpty()}:${dependency.name}:$version"
if (dependency.artifacts.isNotEmpty()) {
dependency.artifacts.firstOrNull()?.classifier?.let { classifier ->
query += ":$classifier"
}
dependency.artifacts.firstOrNull()?.extension?.let { extension ->
query += "@$extension"
}
}
val latest = project.dependencies.create(query) as ModuleDependency
latest.isTransitive = false
// Copy selection qualifiers if the artifact was not explicitly set
if (dependency.artifacts.isEmpty()) {
addAttributes(latest, dependency)
}
return latest
}
/** Returns a variant of the provided dependency used for querying the latest version. */
private fun createQueryDependency(dependency: DependencyConstraint): Dependency {
// If no version was specified then use "none" to pass it through.
val version = if (dependency.version == null) "none" else "+"
val nonTransitiveDependency =
project.dependencies.create("${dependency.group.orEmpty()}:${dependency.name}:$version") as ModuleDependency
nonTransitiveDependency.isTransitive = false
return nonTransitiveDependency
}
private fun disableAutoTargetJvm(configuration: Configuration) {
// Disable the auto target jvm for the configuration
// https://github.com/ben-manes/gradle-versions-plugin/issues/727#issuecomment-1427132589
configuration.attributes.attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, Integer.MAX_VALUE)
}
/** Adds the attributes from the source to the target. */
private fun addAttributes(
target: HasConfigurableAttributes<*>,
source: HasConfigurableAttributes<*>,
filter: (String) -> Boolean = { _ -> true },
) {
target.attributes { container ->
for (key in source.attributes.keySet()) {
if (filter.invoke(key.name)) {
@Suppress("UNCHECKED_CAST")
val value = source.attributes.getAttribute(key as Attribute<Any>)!!
container.attribute(key, value)
}
}
}
}
/** Adds a revision filter by rejecting candidates using a component selection rule. */
private fun addRevisionFilter(
configuration: Configuration,
revision: String,
) {
configuration.resolutionStrategy { componentSelection ->
componentSelection.componentSelection { rules ->
val revisionFilter = { selection: ComponentSelection, metadata: ComponentMetadata? ->
val accepted =
(metadata == null) ||
((revision == "release") && (metadata.status == "release")) ||
((revision == "milestone") && (metadata.status != "integration")) ||
(revision == "integration") || (selection.candidate.version == "none")
if (!accepted) {
selection.reject("Component status ${metadata?.status} rejected by revision $revision")
}
}
rules.all { selectionAction ->
if (ComponentSelection::class.members.any { it.name == "getMetadata" }) {
revisionFilter(selectionAction, selectionAction.metadata)
}
}
}
}
}
/** Adds a custom resolution strategy only applicable for the dependency updates task. */
private fun addCustomResolutionStrategy(
configuration: Configuration,
currentCoordinates: Map<Coordinate.Key, Coordinate>,
) {
configuration.resolutionStrategy { inner ->
resolutionStrategy?.execute(ResolutionStrategyWithCurrent(inner, currentCoordinates))
}
}
/** Returns the coordinates for the current (declared) dependency versions. */
private fun getCurrentCoordinates(configuration: Configuration): Map<Coordinate.Key, Coordinate> {
val declared =
getResolvableDependencies(configuration)
.associateBy { it.key }
if (declared.isEmpty()) {
return emptyMap()
}
// https://github.com/ben-manes/gradle-versions-plugin/issues/231
val transitive = declared.values.any { it.version == "none" }
val coordinates = hashMapOf<Coordinate.Key, Coordinate>()
val copy = configuration.copyRecursive().setTransitive(transitive)
disableAutoTargetJvm(copy)
val lenient = copy.resolvedConfiguration.lenientConfiguration
val resolved = lenient.firstLevelModuleDependencies
for (dependency in resolved) {
val coordinate = Coordinate.from(dependency.module.id, declared)
coordinates[coordinate.key] = coordinate
}
val unresolved = lenient.unresolvedModuleDependencies
for (dependency in unresolved) {
val key = Coordinate.keyFrom(dependency.selector)
declared[key]?.let { coordinates.put(key, it) }
}
if (supportsConstraints(copy)) {
for (constraint in copy.allDependencyConstraints) {
val coordinate = Coordinate.from(constraint)
// Only add a constraint to the report if there is no dependency matching it, this means it
// is targeting a transitive dependency or is part of a platform.
if (!coordinates.containsKey(coordinate.key)) {
declared[coordinate.key]?.let { coordinates.put(coordinate.key, it) }
}
}
}
// Ignore undeclared (hidden) dependencies that appear when resolving a configuration
coordinates.keys.retainAll(declared.keys)
return coordinates
}
private fun logRepositories() {
val root = project.rootProject == project
val label = "${
if (root) {
project.name
} else {
project.path
}
} project ${
if (root) {
" (root)"
} else {
""
}
}"
if (!project.buildscript.configurations
.flatMap { config -> config.dependencies }
.any()
) {
project.logger.info("Resolving $label buildscript with repositories:")
for (repository in project.buildscript.repositories) {
logRepository(repository)
}
}
project.logger.info("Resolving $label configurations with repositories:")
for (repository in project.repositories) {
logRepository(repository)
}
}
private fun logRepository(repository: ArtifactRepository) {
when (repository) {
is FlatDirectoryArtifactRepository -> {
project.logger.info(" - ${repository.name}: ${repository.dirs}")
}
is IvyArtifactRepository -> {
project.logger.info(" - ${repository.name}: ${repository.url}")
}
is MavenArtifactRepository -> {
project.logger.info(" - ${repository.name}: ${repository.url}")
}
else -> {
project.logger.info(" - ${repository.name}: ${repository.javaClass.simpleName}")
}
}
}
private fun getProjectUrl(id: ModuleVersionIdentifier): String? {
if (project.gradle.startParameter.isOffline) {
return null
}
var projectUrl = ProjectUrl()
val cached = projectUrls.putIfAbsent(id, projectUrl)
if (cached != null) {
projectUrl = cached
}
synchronized(projectUrl) {
if (!projectUrl.resolved) {
projectUrl.resolved = true
projectUrl.url = resolveProjectUrl(id)
}
return projectUrl.url
}
}
private fun resolveProjectUrl(id: ModuleVersionIdentifier): String? {
return try {
val resolutionResult =
project.dependencies
.createArtifactResolutionQuery()
.forComponents(DefaultModuleComponentIdentifier.newId(id))
.withArtifacts(MavenModule::class.java, MavenPomArtifact::class.java)
.execute()
// size is 0 for gradle plugins, 1 for normal dependencies
for (result in resolutionResult.resolvedComponents) {
// size should always be 1
for (artifact in result.getArtifacts(MavenPomArtifact::class.java)) {
if (artifact is ResolvedArtifactResult) {
val file = artifact.file
project.logger.info("Pom file for $id is $file")
var url = getUrlFromPom(file)
if (!url.isNullOrEmpty()) {
project.logger.info("Found url for $id: $url")
return url.trim()
} else {
val parent = getParentFromPom(file)
if (parent != null &&
"${parent.group.orEmpty()}:${parent.name}" != "org.sonatype.oss:oss-parent"
) {
url = getProjectUrl(parent)
if (!url.isNullOrEmpty()) {
return url.trim()
}
}
}
}
}
}
project.logger.info("Did not find url for $id")
null
} catch (e: Exception) {
project.logger.info("Failed to resolve the project's url", e)
null
}
}
private fun supportsConstraints(configuration: Configuration): Boolean {
return checkConstraints && !configuration.allDependencyConstraints.isNullOrEmpty()
}
private fun getResolvableDependencies(configuration: Configuration): List<Coordinate> {
@Suppress("SimplifiableCall")
val coordinates =
configuration.allDependencies
.filter { dependency -> dependency is ExternalDependency }
.mapTo(mutableListOf()) { dependency ->
Coordinate.from(dependency)
}
if (supportsConstraints(configuration)) {
configuration.allDependencyConstraints.forEach { dependencyConstraint ->
coordinates.add(Coordinate.from(dependencyConstraint))
}
}
return coordinates
}
companion object {
private fun getUrlFromPom(file: File): String? {
val pom = XmlSlurper(false, false).parse(file)
val url = (pom.getProperty("url") as NodeChildren?)?.text()
return url
?: ((pom.getProperty("scm") as NodeChildren?)?.getProperty("url") as NodeChildren?)?.text()
}
private fun getParentFromPom(file: File): ModuleVersionIdentifier? {
val pom = XmlSlurper(false, false).parse(file)
val parent: GPathResult? = pom.getProperty("parent") as NodeChildren?
if (parent != null) {
val groupId = (parent.getProperty("groupId") as NodeChildren?)?.text()
val artifactId = (parent.getProperty("artifactId") as NodeChildren?)?.text()
val version = (parent.getProperty("version") as NodeChildren?)?.text()
if (groupId != null && artifactId != null && version != null) {
return DefaultModuleVersionIdentifier.newId(groupId, artifactId, version)
}
}
return null
}
class ProjectUrl {
var resolved: Boolean = false
var url: String? = null
}
}
}