summaryrefslogtreecommitdiff
path: root/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/tasks/manifest/ManifestHelper.kt
blob: e40260e1c134e1b3113d9919678002f73cb0bfe9 (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
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
/*
 * Copyright (C) 2019 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.manifest

import com.android.SdkConstants.DOT_XML
import com.android.ide.common.blame.SourceFile
import com.android.ide.common.blame.SourceFilePosition
import com.android.ide.common.blame.SourcePosition
import com.android.manifmerger.ManifestMerger2
import com.android.manifmerger.ManifestProvider
import com.android.manifmerger.ManifestSystemProperty
import com.android.manifmerger.MergingReport
import com.android.manifmerger.MergingReport.MergedManifestKind.AAPT_SAFE
import com.android.manifmerger.MergingReport.MergedManifestKind.MERGED
import com.android.utils.ILogger
import com.google.common.base.Charsets
import com.google.common.io.Files
import java.io.File
import java.io.IOException

/**
 * Invoke the Manifest Merger version 2.
 *
 * @param packageOverride the value used for the merged manifest's package attribute, which is
 *                        the applicationId for apps and the namespace for libraries.
 * @param namespace the namespace, used to create or shorten fully qualified class names
 * @param extractNativeLibs the value to assign to the injected android:extractNativeLibs attribute.
 *                          The attribute will not be injected if null. Even if not null, the
 *                          attribute will not be modified if it's already present in the main
 *                          manifest or an overlay manifest.
 */
fun mergeManifests(
    mainManifest: File,
    manifestOverlays: List<File>,
    dependencies: List<ManifestProvider>,
    navigationJsons: Collection<File>,
    featureName: String?,
    packageOverride: String?,
    namespace: String,
    profileable: Boolean,
    versionCode: Int?,
    versionName: String?,
    minSdkVersion: String?,
    targetSdkVersion: String?,
    maxSdkVersion: Int?,
    testOnly: Boolean,
    extractNativeLibs: Boolean?,
    outMergedManifestLocation: String?,
    outAaptSafeManifestLocation: String?,
    mergeType: ManifestMerger2.MergeType,
    placeHolders: Map<String, Any>,
    optionalFeatures: Collection<ManifestMerger2.Invoker.Feature>,
    dependencyFeatureNames: Collection<String>,
    generatedLocaleConfigAttribute: String?,
    reportFile: File?,
    logger: ILogger,
    checkIfPackageInMainManifest: Boolean = true,
    compileSdk: Int? = null
): MergingReport {

    try {

        val manifestMergerInvoker = ManifestMerger2.newMerger(mainManifest, logger, mergeType)
            .setPlaceHolderValues(placeHolders)
            .addFlavorAndBuildTypeManifests(*manifestOverlays.toTypedArray())
            .addManifestProviders(dependencies)
            .addNavigationJsons(navigationJsons)
            .withFeatures(*optionalFeatures.toTypedArray())
            .setMergeReportFile(reportFile)
            .setFeatureName(featureName)
            .addDependencyFeatureNames(dependencyFeatureNames)
            .setNamespace(namespace)

        if (checkIfPackageInMainManifest) {
            manifestMergerInvoker.withFeatures(
                ManifestMerger2.Invoker.Feature.CHECK_IF_PACKAGE_IN_MAIN_MANIFEST
            )
        }

        val isAppMerge = mergeType == ManifestMerger2.MergeType.APPLICATION
        val injectProfileable = isAppMerge && profileable

        if (isAppMerge) {
            manifestMergerInvoker.withFeatures(ManifestMerger2.Invoker.Feature.REMOVE_TOOLS_DECLARATIONS)
        }

        if (outAaptSafeManifestLocation != null) {
            manifestMergerInvoker.withFeatures(ManifestMerger2.Invoker.Feature.MAKE_AAPT_SAFE)
        }

        manifestMergerInvoker.setGeneratedLocaleConfigAttribute(generatedLocaleConfigAttribute)

        setInjectableValues(
            manifestMergerInvoker,
            packageOverride,
            versionCode,
            versionName,
            minSdkVersion,
            targetSdkVersion,
            maxSdkVersion,
            injectProfileable,
            testOnly,
            compileSdk,
            extractNativeLibs
        )

        val mergingReport = manifestMergerInvoker.merge()
        logger.verbose("Merging result: %1\$s", mergingReport.result)
        if (mergingReport.result == MergingReport.Result.ERROR) {
            mergingReport.log(logger)
            throw RuntimeException(mergingReport.reportString)
        }
        if (mergingReport.result == MergingReport.Result.WARNING) {
            mergingReport.log(logger)
        }

        val annotatedDocument =
            mergingReport.getMergedDocument(MergingReport.MergedManifestKind.BLAME)
        if (annotatedDocument != null) {
            logger.verbose(annotatedDocument)
        }
        logger.verbose("Merged manifest saved to $outMergedManifestLocation")
        if (outMergedManifestLocation != null) {
            save(mergingReport.getMergedDocument(MergingReport.MergedManifestKind.MERGED),
                File(outMergedManifestLocation))
        }

        if (outAaptSafeManifestLocation != null) {
            save(
                mergingReport.getMergedDocument(
                    if (mergingReport.isAaptSafeManifestUnchanged) MERGED else AAPT_SAFE
                ),
                File(outAaptSafeManifestLocation)
            )
        }
        return mergingReport
    } catch (e: ManifestMerger2.MergeFailureException) {
        // TODO: unacceptable.
        throw RuntimeException(e)
    }

}

/**
 * Finds the original source of the file position pointing to a merged manifest file.
 *
 * The manifest merge blame file is formatted as follow
 * <lineNumber>--><filePath>:<startLine>:<startColumn>-<endLine>:<endColumn>
 */
fun findOriginalManifestFilePosition(
    manifestMergeBlameContents: List<String>,
    mergedFilePosition: SourceFilePosition
): SourceFilePosition {
    if (mergedFilePosition.file == SourceFile.UNKNOWN || mergedFilePosition.file.sourceFile?.absolutePath?.contains(
            "merged_manifests"
        ) == false
    ) {
        return mergedFilePosition
    }
    try {
        val linePrefix = (mergedFilePosition.position.startLine + 1).toString() + "-->"
        manifestMergeBlameContents.forEach { line ->
            val trimmed = line.trim()
            if (trimmed.startsWith(linePrefix)) {
                var position = trimmed.substring(linePrefix.length)
                if (position.startsWith("[")) {
                    val closingIndex = position.indexOf("] ")
                    if (closingIndex >= 0) {
                        position = position.substring(closingIndex + 2)
                    }
                }
                val index = position.indexOf(DOT_XML)
                if (index != -1) {
                    val file = position.substring(0, index + DOT_XML.length)
                    return if (file != position) {
                        val sourcePosition = position.substring(index + DOT_XML.length + 1)
                        SourceFilePosition(File(file), SourcePosition.fromString(sourcePosition))
                    } else {
                        SourceFilePosition(File(file), SourcePosition.UNKNOWN)
                    }
                }
            }
        }
    } catch (e: Exception) {
        return mergedFilePosition
    }
    return mergedFilePosition
}

/**
 * Sets the [ManifestSystemProperty] that can be injected
 * in the manifest file.
 */
private fun setInjectableValues(
    invoker: ManifestMerger2.Invoker,
    packageOverride: String?,
    versionCode: Int?,
    versionName: String?,
    minSdkVersion: String?,
    targetSdkVersion: String?,
    maxSdkVersion: Int?,
    profileable: Boolean,
    testOnly: Boolean,
    compileSdk: Int?,
    extractNativeLibs: Boolean?
) {

    if (packageOverride != null && packageOverride.isNotEmpty()) {
        invoker.setOverride(ManifestSystemProperty.Document.PACKAGE, packageOverride)
    }

    versionCode?.let {
        if (it > 0) {
            invoker.setOverride(ManifestSystemProperty.Manifest.VERSION_CODE, it.toString())
        }
    }

    if (versionName != null && versionName.isNotEmpty()) {
        invoker.setOverride(ManifestSystemProperty.Manifest.VERSION_NAME, versionName)
    }
    if (minSdkVersion != null && minSdkVersion.isNotEmpty()) {
        invoker.setOverride(ManifestSystemProperty.UsesSdk.MIN_SDK_VERSION, minSdkVersion)
    }
    if (targetSdkVersion != null && targetSdkVersion.isNotEmpty()) {
        invoker.setOverride(ManifestSystemProperty.UsesSdk.TARGET_SDK_VERSION, targetSdkVersion)
    }
    if (maxSdkVersion != null) {
        invoker.setOverride(ManifestSystemProperty.UsesSdk.MAX_SDK_VERSION, maxSdkVersion.toString())
    }
    if (profileable) {
        invoker.setOverride(ManifestSystemProperty.Profileable.SHELL, "true")
        // API 29 doesn't support 'android:enabled' for the profileable tag.
        if (compileSdk != null && compileSdk >= 30) {
            invoker.setOverride(ManifestSystemProperty.Profileable.ENABLED, "true")
        }
    }
    if (testOnly) {
        invoker.setOverride(ManifestSystemProperty.Application.TEST_ONLY, "true")
    }
    if (extractNativeLibs != null) {
        // android:extractNativeLibs unrecognized if using compile SDK < 23.
        if (compileSdk == null || compileSdk >= 23) {
            invoker.setOverride(
                ManifestSystemProperty.Application.EXTRACT_NATIVE_LIBS,
                extractNativeLibs.toString()
            )
        }
    }
}

/**
 * Saves the [com.android.manifmerger.XmlDocument] to a file in UTF-8 encoding.
 * @param xmlDocument xml document to save.
 * @param out file to save to.
 */
private fun save(xmlDocument: String?, out: File) {
    try {
        Files.createParentDirs(out)
        Files.asCharSink(out, Charsets.UTF_8).write(xmlDocument!!)
    } catch (e: IOException) {
        throw RuntimeException(e)
    }

}