summaryrefslogtreecommitdiff
path: root/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/tasks/featuresplit/PackagedDependenciesWriterTask.kt
blob: ab80a6dff3ca913ea37a82b0a678e21019e28e4a (plain)
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
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.build.gradle.internal.tasks.featuresplit

import com.android.build.gradle.internal.attributes.VariantAttr
import com.android.build.gradle.internal.component.ComponentCreationConfig
import com.android.build.gradle.internal.ide.dependencies.getIdString
import com.android.build.gradle.internal.publishing.AndroidArtifacts
import com.android.build.gradle.internal.publishing.AndroidArtifacts.ARTIFACT_TYPE
import com.android.build.gradle.internal.publishing.PublishedConfigSpec
import com.android.build.gradle.internal.scope.InternalArtifactType
import com.android.build.gradle.internal.tasks.BuildAnalyzer
import com.android.build.gradle.internal.tasks.NonIncrementalTask
import com.android.build.gradle.internal.tasks.factory.VariantTaskCreationAction
import com.android.build.gradle.internal.utils.setDisallowChanges
import com.android.ide.common.attribution.TaskCategoryLabel
import com.android.utils.FileUtils
import com.google.common.base.Joiner
import org.gradle.api.Action
import org.gradle.api.artifacts.ArtifactCollection
import org.gradle.api.artifacts.component.ComponentIdentifier
import org.gradle.api.artifacts.component.ModuleComponentIdentifier
import org.gradle.api.artifacts.component.ProjectComponentIdentifier
import org.gradle.api.artifacts.result.ResolvedArtifactResult
import org.gradle.api.attributes.AttributeContainer
import org.gradle.api.file.FileCollection
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskProvider

private val aarOrJarType = Action { container: AttributeContainer ->
    container.attribute(ARTIFACT_TYPE, AndroidArtifacts.ArtifactType.AAR_OR_JAR.type)
}

/** Task to write the list of transitive dependencies.  */
@CacheableTask
@BuildAnalyzer(taskCategoryLabels = [TaskCategoryLabel.HELP])
abstract class PackagedDependenciesWriterTask : NonIncrementalTask() {

    @get:OutputFile
    abstract val outputFile: RegularFileProperty

    private lateinit var runtimeAarOrJarDeps: ArtifactCollection

    @get:Input
    val content: List<String>
       get() = runtimeAarOrJarDeps.map { it.toIdString() }.sorted()

    // the list of packaged dependencies by transitive dependencies.
    private lateinit var transitivePackagedDeps : ArtifactCollection

    @get:InputFiles
    @get:PathSensitive(PathSensitivity.NONE)
    val transitivePackagedDepsFC : FileCollection
        get() = transitivePackagedDeps.artifactFiles

    @get:Input
    abstract val currentProjectIds: ListProperty<String>

    override fun doTaskAction() {
        val apkFilters = mutableSetOf<String>()
        val contentFilters = mutableSetOf<String>()
        // load the transitive information and remove from the full content.
        // We know this is correct because this information is also used in
        // FilteredArtifactCollection to remove this content from runtime-based ArtifactCollection.
        // However since we directly use the Configuration here, we have to manually remove it.
        for (transitiveDep in transitivePackagedDeps) {
            // register the APK that generated this list to remove it from our list
            apkFilters.add(transitiveDep.toIdString())
            // read its packaged content to also remove it.
            val lines = transitiveDep.file.readLines()
            contentFilters.addAll(lines)
        }

        val contentWithProject = content + currentProjectIds.get()

        // compute the overall content
        val filteredContent =
            contentWithProject.filter {
                !apkFilters.contains(it) && !contentFilters.contains(it)
            }.sorted()

        val asFile = outputFile.get().asFile
        FileUtils.mkdirs(asFile.parentFile)
        asFile.writeText(Joiner.on(System.lineSeparator()).join(filteredContent))
    }

    /**
     * Action to create the task that generates the transitive dependency list to be consumed by
     * other modules.
     *
     * This cannot depend on preBuild as it would introduce a dependency cycle.
     */
    class CreationAction(creationConfig: ComponentCreationConfig) :
        VariantTaskCreationAction<PackagedDependenciesWriterTask, ComponentCreationConfig>(
            creationConfig,
            dependsOnPreBuildTask = false
        ) {

        override val name: String
            get() = computeTaskName("generate", "FeatureTransitiveDeps")
        override val type: Class<PackagedDependenciesWriterTask>
            get() = PackagedDependenciesWriterTask::class.java

        override fun handleProvider(
            taskProvider: TaskProvider<PackagedDependenciesWriterTask>
        ) {
            super.handleProvider(taskProvider)
            creationConfig.artifacts.setInitialProvider(
                taskProvider,
                PackagedDependenciesWriterTask::outputFile
            ).withName("deps.txt").on(InternalArtifactType.PACKAGED_DEPENDENCIES)
        }

        override fun configure(
            task: PackagedDependenciesWriterTask
        ) {
            super.configure(task)
            val apiAndRuntimeConfigurations = listOfNotNull(
                creationConfig.variantDependencies.getElements(
                    PublishedConfigSpec(
                        AndroidArtifacts.PublishedConfigType.API_ELEMENTS
                    )
                ),
                creationConfig.variantDependencies.getElements(
                    PublishedConfigSpec(
                        AndroidArtifacts.PublishedConfigType.RUNTIME_ELEMENTS
                    )
                )
            )
            task.currentProjectIds.setDisallowChanges(
                apiAndRuntimeConfigurations.let { configurations ->

                    val capabilitiesList = configurations.map { it.outgoing.capabilities }.filter {
                        it.isNotEmpty()
                    }.ifEmpty {
                        listOf(listOf(creationConfig.services.projectInfo.defaultProjectCapability))
                    }

                    val projectId = "${creationConfig.services.projectInfo.path}::${task.variantName}"
                    capabilitiesList.map { capabilities ->
                        encodeCapabilitiesInId(projectId) {
                            capabilities.joinToString(";") { it.toString() }
                        }
                    }.distinct()
                }
            )
            task.runtimeAarOrJarDeps =
                creationConfig.variantDependencies
                    .runtimeClasspath
                    .incoming
                    .artifactView { it.attributes(aarOrJarType) }
                    .artifacts
            task.dependsOn(task.runtimeAarOrJarDeps.artifactFiles)

            task.transitivePackagedDeps =
                creationConfig.variantDependencies.getArtifactCollection(
                    AndroidArtifacts.ConsumedConfigType.PROVIDED_CLASSPATH,
                    AndroidArtifacts.ArtifactScope.PROJECT,
                    AndroidArtifacts.ArtifactType.PACKAGED_DEPENDENCIES)
        }
    }
}

fun ResolvedArtifactResult.toIdString(): String {
    return id.componentIdentifier.toIdString(
        variantProvider = { variant.attributes.getAttribute(VariantAttr.ATTRIBUTE)?.name },
        capabilitiesProvider = { variant.capabilities.joinToString(";") { it.toString() } },
    )
}

private fun ComponentIdentifier.toIdString(
    variantProvider: () -> String?,
    capabilitiesProvider: () -> String
) : String {
    val id = when (this) {
        is ProjectComponentIdentifier -> {
            val variant = variantProvider()
            if (variant == null) {
                getIdString()
            } else {
                "${getIdString()}::${variant}"
            }
        }
        is ModuleComponentIdentifier -> "$group:$module"
        else -> toString()
    }

    return encodeCapabilitiesInId(id, capabilitiesProvider)
}

private fun encodeCapabilitiesInId(
    id: String,
    capabilitiesProvider: () -> String
): String {
    return "$id;${capabilitiesProvider.invoke()}"
}

fun removeVariantNameFromId(
    id: String
): String {
    return if (id.contains("::")) {
        val libraryWithoutVariant = id.substringBeforeLast("::")
        val capabilities = id.substringAfter(";")
        "$libraryWithoutVariant;$capabilities"
    } else {
        id
    }
}