blob: 945bc1832b358a3db9c121debcef257455a1df72 [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
19from __future__ import print_function
Colin Cross72119102019-05-20 13:14:18 -070020
Colin Cross8bb10e82018-06-07 16:46:02 -070021import argparse
22import sys
23from xml.dom import minidom
24
25
Colin Cross72119102019-05-20 13:14:18 -070026from manifest import android_ns
27from manifest import compare_version_gt
28from manifest import ensure_manifest_android_ns
29from manifest import find_child_with_attribute
30from manifest import get_children_with_tag
31from manifest import get_indent
32from manifest import parse_manifest
33from manifest import write_xml
Jiyong Parkc08f46f2018-06-18 11:01:00 +090034
35
Colin Cross8bb10e82018-06-07 16:46:02 -070036def parse_args():
37 """Parse commandline arguments."""
38
39 parser = argparse.ArgumentParser()
40 parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
41 help='specify minSdkVersion used by the build system')
Colin Cross7b59e7b2018-09-10 13:35:13 -070042 parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
43 help='specify targetSdkVersion used by the build system')
44 parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
45 help='raise the minimum sdk version in the manifest if necessary')
Colin Cross1b6a3cf2018-07-24 14:51:30 -070046 parser.add_argument('--library', dest='library', action='store_true',
47 help='manifest is for a static library')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090048 parser.add_argument('--uses-library', dest='uses_libraries', action='append',
Jiyong Parkfa17afe2018-10-16 11:00:04 +090049 help='specify additional <uses-library> tag to add. android:requred is set to true')
50 parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
51 help='specify additional <uses-library> tag to add. android:requred is set to false')
David Brazdild5b74992018-08-28 12:41:01 +010052 parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
53 help='manifest is for a package built against the platform')
Victor Hsiehd181c8b2019-01-29 13:00:33 -080054 parser.add_argument('--use-embedded-dex', dest='use_embedded_dex', action='store_true',
55 help=('specify if the app wants to use embedded dex and avoid extracted,'
Colin Crosse4246ab2019-02-05 21:55:21 -080056 'locally compiled code. Must not conflict if already declared '
Victor Hsiehd181c8b2019-01-29 13:00:33 -080057 'in the manifest.'))
Colin Crosse4246ab2019-02-05 21:55:21 -080058 parser.add_argument('--extract-native-libs', dest='extract_native_libs',
59 default=None, type=lambda x: (str(x).lower() == 'true'),
60 help=('specify if the app wants to use embedded native libraries. Must not conflict '
61 'if already declared in the manifest.'))
Jaewoong Jungc27ab662019-05-30 15:51:14 -070062 parser.add_argument('--has-no-code', dest='has_no_code', action='store_true',
63 help=('adds hasCode="false" attribute to application. Ignored if application elem '
64 'already has a hasCode attribute.'))
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
84 # Get or insert the uses-sdk element
85 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
86 if len(uses_sdk) > 1:
87 raise RuntimeError('found multiple uses-sdk elements')
88 elif len(uses_sdk) == 1:
89 element = uses_sdk[0]
90 else:
91 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090092 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -070093 manifest.insertBefore(element, manifest.firstChild)
94
95 # Insert an indent before uses-sdk to line it up with the indentation of the
96 # other children of the <manifest> tag.
97 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
98
Colin Cross1b6a3cf2018-07-24 14:51:30 -070099 # Get or insert the minSdkVersion attribute. If it is already present, make
100 # sure it as least the requested value.
Colin Cross8bb10e82018-06-07 16:46:02 -0700101 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
102 if min_attr is None:
103 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -0700104 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700105 element.setAttributeNode(min_attr)
106 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700107 if compare_version_gt(min_sdk_version, min_attr.value):
108 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700109
110 # Insert the targetSdkVersion attribute if it is missing. If it is already
111 # present leave it as is.
112 target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
113 if target_attr is None:
114 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
115 if library:
Colin Cross4b176062018-10-01 15:15:51 -0700116 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
117 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
118 # is empty. Set it to something low so that it will be overriden by the
119 # main manifest, but high enough that it doesn't cause implicit
120 # permissions grants.
121 target_attr.value = '15'
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700122 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700123 target_attr.value = target_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700124 element.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700125
126
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900127def add_uses_libraries(doc, new_uses_libraries, required):
128 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900129
130 Args:
131 doc: The XML document. May be modified by this function.
132 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900133 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900134 Raises:
135 RuntimeError: Invalid manifest
136 """
137
138 manifest = parse_manifest(doc)
139 elems = get_children_with_tag(manifest, 'application')
140 application = elems[0] if len(elems) == 1 else None
141 if len(elems) > 1:
142 raise RuntimeError('found multiple <application> tags')
143 elif not elems:
144 application = doc.createElement('application')
145 indent = get_indent(manifest.firstChild, 1)
146 first = manifest.firstChild
147 manifest.insertBefore(doc.createTextNode(indent), first)
148 manifest.insertBefore(application, first)
149
150 indent = get_indent(application.firstChild, 2)
151
152 last = application.lastChild
153 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
154 last = None
155
156 for name in new_uses_libraries:
157 if find_child_with_attribute(application, 'uses-library', android_ns,
158 'name', name) is not None:
159 # If the uses-library tag of the same 'name' attribute value exists,
160 # respect it.
161 continue
162
163 ul = doc.createElement('uses-library')
164 ul.setAttributeNS(android_ns, 'android:name', name)
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900165 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900166
167 application.insertBefore(doc.createTextNode(indent), last)
168 application.insertBefore(ul, last)
169
170 # align the closing tag with the opening tag if it's not
171 # indented
172 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
173 indent = get_indent(application.previousSibling, 1)
174 application.appendChild(doc.createTextNode(indent))
175
Colin Cross72119102019-05-20 13:14:18 -0700176
David Brazdild5b74992018-08-28 12:41:01 +0100177def add_uses_non_sdk_api(doc):
178 """Add android:usesNonSdkApi=true attribute to <application>.
179
180 Args:
181 doc: The XML document. May be modified by this function.
182 Raises:
183 RuntimeError: Invalid manifest
184 """
185
186 manifest = parse_manifest(doc)
187 elems = get_children_with_tag(manifest, 'application')
188 application = elems[0] if len(elems) == 1 else None
189 if len(elems) > 1:
190 raise RuntimeError('found multiple <application> tags')
191 elif not elems:
192 application = doc.createElement('application')
193 indent = get_indent(manifest.firstChild, 1)
194 first = manifest.firstChild
195 manifest.insertBefore(doc.createTextNode(indent), first)
196 manifest.insertBefore(application, first)
197
198 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
199 if attr is None:
200 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
201 attr.value = 'true'
202 application.setAttributeNode(attr)
203
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900204
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800205def add_use_embedded_dex(doc):
Victor Hsiehce7818e2018-10-22 11:16:25 -0700206 manifest = parse_manifest(doc)
207 elems = get_children_with_tag(manifest, 'application')
208 application = elems[0] if len(elems) == 1 else None
209 if len(elems) > 1:
210 raise RuntimeError('found multiple <application> tags')
211 elif not elems:
212 application = doc.createElement('application')
213 indent = get_indent(manifest.firstChild, 1)
214 first = manifest.firstChild
215 manifest.insertBefore(doc.createTextNode(indent), first)
216 manifest.insertBefore(application, first)
217
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800218 attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700219 if attr is None:
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800220 attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700221 attr.value = 'true'
222 application.setAttributeNode(attr)
223 elif attr.value != 'true':
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800224 raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700225
226
Colin Crosse4246ab2019-02-05 21:55:21 -0800227def add_extract_native_libs(doc, extract_native_libs):
228 manifest = parse_manifest(doc)
229 elems = get_children_with_tag(manifest, 'application')
230 application = elems[0] if len(elems) == 1 else None
231 if len(elems) > 1:
232 raise RuntimeError('found multiple <application> tags')
233 elif not elems:
234 application = doc.createElement('application')
235 indent = get_indent(manifest.firstChild, 1)
236 first = manifest.firstChild
237 manifest.insertBefore(doc.createTextNode(indent), first)
238 manifest.insertBefore(application, first)
239
240 value = str(extract_native_libs).lower()
241 attr = application.getAttributeNodeNS(android_ns, 'extractNativeLibs')
242 if attr is None:
243 attr = doc.createAttributeNS(android_ns, 'android:extractNativeLibs')
244 attr.value = value
245 application.setAttributeNode(attr)
246 elif attr.value != value:
247 raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
248 (attr.value, value))
249
250
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700251def set_has_code_to_false(doc):
252 manifest = parse_manifest(doc)
253 elems = get_children_with_tag(manifest, 'application')
254 application = elems[0] if len(elems) == 1 else None
255 if len(elems) > 1:
256 raise RuntimeError('found multiple <application> tags')
257 elif not elems:
258 application = doc.createElement('application')
259 indent = get_indent(manifest.firstChild, 1)
260 first = manifest.firstChild
261 manifest.insertBefore(doc.createTextNode(indent), first)
262 manifest.insertBefore(application, first)
263
264 attr = application.getAttributeNodeNS(android_ns, 'hasCode')
265 if attr is not None:
266 # Do nothing if the application already has a hasCode attribute.
267 return
268 attr = doc.createAttributeNS(android_ns, 'android:hasCode')
269 attr.value = 'false'
270 application.setAttributeNode(attr)
271
272
Colin Cross8bb10e82018-06-07 16:46:02 -0700273def main():
274 """Program entry point."""
275 try:
276 args = parse_args()
277
278 doc = minidom.parse(args.input)
279
280 ensure_manifest_android_ns(doc)
281
Colin Cross7b59e7b2018-09-10 13:35:13 -0700282 if args.raise_min_sdk_version:
283 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700284
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900285 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900286 add_uses_libraries(doc, args.uses_libraries, True)
287
288 if args.optional_uses_libraries:
289 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900290
David Brazdild5b74992018-08-28 12:41:01 +0100291 if args.uses_non_sdk_api:
292 add_uses_non_sdk_api(doc)
293
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800294 if args.use_embedded_dex:
295 add_use_embedded_dex(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700296
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700297 if args.has_no_code:
298 set_has_code_to_false(doc)
299
Colin Crosse4246ab2019-02-05 21:55:21 -0800300 if args.extract_native_libs is not None:
301 add_extract_native_libs(doc, args.extract_native_libs)
302
Colin Cross8bb10e82018-06-07 16:46:02 -0700303 with open(args.output, 'wb') as f:
304 write_xml(f, doc)
305
306 # pylint: disable=broad-except
307 except Exception as err:
308 print('error: ' + str(err), file=sys.stderr)
309 sys.exit(-1)
310
311if __name__ == '__main__':
312 main()