blob: ad3b31330e7c093c71d167c835ae8addcab13474 [file] [log] [blame]
Colin Cross8bb10e82018-06-07 16:46:02 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2018 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17"""A tool for inserting values from the build system into a manifest."""
18
Colin Cross8bb10e82018-06-07 16:46:02 -070019import argparse
20import sys
21from xml.dom import minidom
22
23
Colin Crosse1ab8492024-09-11 13:28:16 -070024from manifest import *
Jiyong Parkc08f46f2018-06-18 11:01:00 +090025
Colin Cross8bb10e82018-06-07 16:46:02 -070026def parse_args():
27 """Parse commandline arguments."""
28
29 parser = argparse.ArgumentParser()
30 parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
31 help='specify minSdkVersion used by the build system')
William Loh5a082f92022-05-17 20:21:50 +000032 parser.add_argument('--replaceMaxSdkVersionPlaceholder', default='', dest='max_sdk_version',
33 help='specify maxSdkVersion used by the build system')
Colin Cross7b59e7b2018-09-10 13:35:13 -070034 parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
35 help='specify targetSdkVersion used by the build system')
36 parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
37 help='raise the minimum sdk version in the manifest if necessary')
Colin Cross1b6a3cf2018-07-24 14:51:30 -070038 parser.add_argument('--library', dest='library', action='store_true',
39 help='manifest is for a static library')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090040 parser.add_argument('--uses-library', dest='uses_libraries', action='append',
Colin Cross6cb462b2024-09-11 11:34:35 -070041 help='specify additional <uses-library> tag to add. android:required is set to true')
Jiyong Parkfa17afe2018-10-16 11:00:04 +090042 parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
Colin Cross6cb462b2024-09-11 11:34:35 -070043 help='specify additional <uses-library> tag to add. android:required is set to false')
David Brazdild5b74992018-08-28 12:41:01 +010044 parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
45 help='manifest is for a package built against the platform')
Baligh Uddin5b16dfb2020-02-11 17:27:19 -080046 parser.add_argument('--logging-parent', dest='logging_parent', default='',
47 help=('specify logging parent as an additional <meta-data> tag. '
48 'This value is ignored if the logging_parent meta-data tag is present.'))
Victor Hsiehd181c8b2019-01-29 13:00:33 -080049 parser.add_argument('--use-embedded-dex', dest='use_embedded_dex', action='store_true',
50 help=('specify if the app wants to use embedded dex and avoid extracted,'
Colin Crosse4246ab2019-02-05 21:55:21 -080051 'locally compiled code. Must not conflict if already declared '
Victor Hsiehd181c8b2019-01-29 13:00:33 -080052 'in the manifest.'))
Colin Crosse4246ab2019-02-05 21:55:21 -080053 parser.add_argument('--extract-native-libs', dest='extract_native_libs',
54 default=None, type=lambda x: (str(x).lower() == 'true'),
Jiyong Parkd044bb42024-05-15 02:09:54 +090055 help=('specify if the app wants to use embedded native libraries. Must not conflict '
56 'if already declared in the manifest.'))
Jaewoong Jungc27ab662019-05-30 15:51:14 -070057 parser.add_argument('--has-no-code', dest='has_no_code', action='store_true',
58 help=('adds hasCode="false" attribute to application. Ignored if application elem '
59 'already has a hasCode attribute.'))
Gurpreet Singh75d65f32022-01-24 17:44:05 +000060 parser.add_argument('--test-only', dest='test_only', action='store_true',
61 help=('adds testOnly="true" attribute to application. Assign true value if application elem '
62 'already has a testOnly attribute.'))
Alexei Nicoara69cf0f32022-07-27 14:59:18 +010063 parser.add_argument('--override-placeholder-version', dest='new_version',
64 help='Overrides the versionCode if it\'s set to the placeholder value of 0')
Colin Cross8bb10e82018-06-07 16:46:02 -070065 parser.add_argument('input', help='input AndroidManifest.xml file')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090066 parser.add_argument('output', help='output AndroidManifest.xml file')
Colin Cross8bb10e82018-06-07 16:46:02 -070067 return parser.parse_args()
68
69
Colin Cross7b59e7b2018-09-10 13:35:13 -070070def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -070071 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
72
73 Args:
74 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -070075 min_sdk_version: The requested minSdkVersion attribute.
76 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross72119102019-05-20 13:14:18 -070077 library: True if the manifest is for a library.
Colin Cross8bb10e82018-06-07 16:46:02 -070078 Raises:
79 RuntimeError: invalid manifest
80 """
81
82 manifest = parse_manifest(doc)
83
Colin Crosse1ab8492024-09-11 13:28:16 -070084 for uses_sdk in get_or_create_uses_sdks(doc, manifest):
85 # Get or insert the minSdkVersion attribute. If it is already present, make
86 # sure it as least the requested value.
87 min_attr = uses_sdk.getAttributeNodeNS(android_ns, 'minSdkVersion')
88 if min_attr is None:
89 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -070090 min_attr.value = min_sdk_version
Colin Crosse1ab8492024-09-11 13:28:16 -070091 uses_sdk.setAttributeNode(min_attr)
Colin Cross1b6a3cf2018-07-24 14:51:30 -070092 else:
Colin Crosse1ab8492024-09-11 13:28:16 -070093 if compare_version_gt(min_sdk_version, min_attr.value):
94 min_attr.value = min_sdk_version
95
96 # Insert the targetSdkVersion attribute if it is missing. If it is already
97 # present leave it as is.
98 target_attr = uses_sdk.getAttributeNodeNS(android_ns, 'targetSdkVersion')
99 if target_attr is None:
100 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
101 if library:
102 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
103 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
104 # is empty. Set it to something low so that it will be overridden by the
105 # main manifest, but high enough that it doesn't cause implicit
106 # permissions grants.
107 target_attr.value = '16'
108 else:
109 target_attr.value = target_sdk_version
110 uses_sdk.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700111
112
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800113def add_logging_parent(doc, logging_parent_value):
114 """Add logging parent as an additional <meta-data> tag.
115
116 Args:
117 doc: The XML document. May be modified by this function.
118 logging_parent_value: A string representing the logging
119 parent value.
120 Raises:
121 RuntimeError: Invalid manifest
122 """
123 manifest = parse_manifest(doc)
124
125 logging_parent_key = 'android.content.pm.LOGGING_PARENT'
Colin Crosse1ab8492024-09-11 13:28:16 -0700126 for application in get_or_create_applications(doc, manifest):
127 indent = get_indent(application.firstChild, 2)
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800128
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800129 last = application.lastChild
Colin Crosse1ab8492024-09-11 13:28:16 -0700130 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
131 last = None
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800132
Colin Crosse1ab8492024-09-11 13:28:16 -0700133 if not find_child_with_attribute(application, 'meta-data', android_ns,
134 'name', logging_parent_key):
135 ul = doc.createElement('meta-data')
136 ul.setAttributeNS(android_ns, 'android:name', logging_parent_key)
137 ul.setAttributeNS(android_ns, 'android:value', logging_parent_value)
138 application.insertBefore(doc.createTextNode(indent), last)
139 application.insertBefore(ul, last)
140 last = application.lastChild
141
142 # align the closing tag with the opening tag if it's not
143 # indented
144 if last and last.nodeType != minidom.Node.TEXT_NODE:
145 indent = get_indent(application.previousSibling, 1)
146 application.appendChild(doc.createTextNode(indent))
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800147
148
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900149def add_uses_libraries(doc, new_uses_libraries, required):
150 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900151
152 Args:
153 doc: The XML document. May be modified by this function.
154 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900155 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900156 Raises:
157 RuntimeError: Invalid manifest
158 """
159
160 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700161 for application in get_or_create_applications(doc, manifest):
162 indent = get_indent(application.firstChild, 2)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900163
Colin Crosse1ab8492024-09-11 13:28:16 -0700164 last = application.lastChild
165 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
166 last = None
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900167
Colin Crosse1ab8492024-09-11 13:28:16 -0700168 for name in new_uses_libraries:
169 if find_child_with_attribute(application, 'uses-library', android_ns,
170 'name', name) is not None:
171 # If the uses-library tag of the same 'name' attribute value exists,
172 # respect it.
173 continue
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900174
Colin Crosse1ab8492024-09-11 13:28:16 -0700175 ul = doc.createElement('uses-library')
176 ul.setAttributeNS(android_ns, 'android:name', name)
177 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900178
Colin Crosse1ab8492024-09-11 13:28:16 -0700179 application.insertBefore(doc.createTextNode(indent), last)
180 application.insertBefore(ul, last)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900181
Colin Crosse1ab8492024-09-11 13:28:16 -0700182 # align the closing tag with the opening tag if it's not
183 # indented
184 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
185 indent = get_indent(application.previousSibling, 1)
186 application.appendChild(doc.createTextNode(indent))
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900187
Colin Cross72119102019-05-20 13:14:18 -0700188
David Brazdild5b74992018-08-28 12:41:01 +0100189def add_uses_non_sdk_api(doc):
190 """Add android:usesNonSdkApi=true attribute to <application>.
191
192 Args:
193 doc: The XML document. May be modified by this function.
194 Raises:
195 RuntimeError: Invalid manifest
196 """
197
198 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700199 for application in get_or_create_applications(doc, manifest):
200 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
201 if attr is None:
202 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
203 attr.value = 'true'
204 application.setAttributeNode(attr)
David Brazdild5b74992018-08-28 12:41:01 +0100205
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900206
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800207def add_use_embedded_dex(doc):
Victor Hsiehce7818e2018-10-22 11:16:25 -0700208 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700209 for application in get_or_create_applications(doc, manifest):
210 attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
211 if attr is None:
212 attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
213 attr.value = 'true'
214 application.setAttributeNode(attr)
215 elif attr.value != 'true':
216 raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700217
218
Colin Crosse4246ab2019-02-05 21:55:21 -0800219def add_extract_native_libs(doc, extract_native_libs):
220 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700221 for application in get_or_create_applications(doc, manifest):
222 value = str(extract_native_libs).lower()
223 attr = application.getAttributeNodeNS(android_ns, 'extractNativeLibs')
224 if attr is None:
225 attr = doc.createAttributeNS(android_ns, 'android:extractNativeLibs')
226 attr.value = value
227 application.setAttributeNode(attr)
228 elif attr.value != value:
229 raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
230 (attr.value, value))
Colin Crosse4246ab2019-02-05 21:55:21 -0800231
232
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700233def set_has_code_to_false(doc):
234 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700235 for application in get_or_create_applications(doc, manifest):
236 attr = application.getAttributeNodeNS(android_ns, 'hasCode')
237 if attr is not None:
238 # Do nothing if the application already has a hasCode attribute.
239 continue
240 attr = doc.createAttributeNS(android_ns, 'android:hasCode')
241 attr.value = 'false'
242 application.setAttributeNode(attr)
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700243
Colin Cross6cb462b2024-09-11 11:34:35 -0700244
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000245def set_test_only_flag_to_true(doc):
246 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700247 for application in get_or_create_applications(doc, manifest):
248 attr = application.getAttributeNodeNS(android_ns, 'testOnly')
249 if attr is not None:
250 # Do nothing If the application already has a testOnly attribute.
251 continue
252 attr = doc.createAttributeNS(android_ns, 'android:testOnly')
253 attr.value = 'true'
254 application.setAttributeNode(attr)
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700255
Colin Cross6cb462b2024-09-11 11:34:35 -0700256
William Loh5a082f92022-05-17 20:21:50 +0000257def set_max_sdk_version(doc, max_sdk_version):
258 """Replace the maxSdkVersion attribute value for permission and
259 uses-permission tags if the value was originally set to 'current'.
260 Used for cts test cases where the maxSdkVersion should equal to
261 Build.SDK_INT.
262
263 Args:
264 doc: The XML document. May be modified by this function.
265 max_sdk_version: The requested maxSdkVersion attribute.
266 """
267 manifest = parse_manifest(doc)
268 for tag in ['permission', 'uses-permission']:
269 children = get_children_with_tag(manifest, tag)
270 for child in children:
271 max_attr = child.getAttributeNodeNS(android_ns, 'maxSdkVersion')
272 if max_attr and max_attr.value == 'current':
273 max_attr.value = max_sdk_version
274
Colin Cross6cb462b2024-09-11 11:34:35 -0700275
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100276def override_placeholder_version(doc, new_version):
277 """Replace the versionCode attribute value if it\'s currently
278 set to the placeholder version of 0.
279
280 Args:
281 doc: The XML document. May be modified by this function.
282 new_version: The new version to set if versionCode is equal to 0.
283 """
284 manifest = parse_manifest(doc)
285 version = manifest.getAttribute("android:versionCode")
Colin Cross6cb462b2024-09-11 11:34:35 -0700286 if version == '0':
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100287 manifest.setAttribute("android:versionCode", new_version)
288
Colin Cross6cb462b2024-09-11 11:34:35 -0700289
Colin Cross8bb10e82018-06-07 16:46:02 -0700290def main():
291 """Program entry point."""
292 try:
293 args = parse_args()
294
295 doc = minidom.parse(args.input)
296
297 ensure_manifest_android_ns(doc)
298
Colin Cross7b59e7b2018-09-10 13:35:13 -0700299 if args.raise_min_sdk_version:
300 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700301
William Loh5a082f92022-05-17 20:21:50 +0000302 if args.max_sdk_version:
303 set_max_sdk_version(doc, args.max_sdk_version)
304
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900305 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900306 add_uses_libraries(doc, args.uses_libraries, True)
307
308 if args.optional_uses_libraries:
309 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900310
David Brazdild5b74992018-08-28 12:41:01 +0100311 if args.uses_non_sdk_api:
312 add_uses_non_sdk_api(doc)
313
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800314 if args.logging_parent:
315 add_logging_parent(doc, args.logging_parent)
316
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800317 if args.use_embedded_dex:
318 add_use_embedded_dex(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700319
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700320 if args.has_no_code:
321 set_has_code_to_false(doc)
322
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000323 if args.test_only:
324 set_test_only_flag_to_true(doc)
325
Colin Crosse4246ab2019-02-05 21:55:21 -0800326 if args.extract_native_libs is not None:
327 add_extract_native_libs(doc, args.extract_native_libs)
328
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100329 if args.new_version:
330 override_placeholder_version(doc, args.new_version)
331
Cole Faustc41dd722021-11-09 15:08:26 -0800332 with open(args.output, 'w') as f:
Colin Cross8bb10e82018-06-07 16:46:02 -0700333 write_xml(f, doc)
334
335 # pylint: disable=broad-except
336 except Exception as err:
337 print('error: ' + str(err), file=sys.stderr)
338 sys.exit(-1)
339
Colin Cross6cb462b2024-09-11 11:34:35 -0700340
Colin Cross8bb10e82018-06-07 16:46:02 -0700341if __name__ == '__main__':
342 main()