blob: 917f55b4a9b5604ed8951cf47949d2b28240bc10 [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
20import argparse
21import sys
22from xml.dom import minidom
23
24
25android_ns = 'http://schemas.android.com/apk/res/android'
26
27
28def get_children_with_tag(parent, tag_name):
29 children = []
30 for child in parent.childNodes:
31 if child.nodeType == minidom.Node.ELEMENT_NODE and \
32 child.tagName == tag_name:
33 children.append(child)
34 return children
35
36
Jiyong Parkc08f46f2018-06-18 11:01:00 +090037def find_child_with_attribute(element, tag_name, namespace_uri,
38 attr_name, value):
39 for child in get_children_with_tag(element, tag_name):
40 attr = child.getAttributeNodeNS(namespace_uri, attr_name)
41 if attr is not None and attr.value == value:
42 return child
43 return None
44
45
Colin Cross8bb10e82018-06-07 16:46:02 -070046def parse_args():
47 """Parse commandline arguments."""
48
49 parser = argparse.ArgumentParser()
50 parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
51 help='specify minSdkVersion used by the build system')
Colin Cross7b59e7b2018-09-10 13:35:13 -070052 parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
53 help='specify targetSdkVersion used by the build system')
54 parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
55 help='raise the minimum sdk version in the manifest if necessary')
Colin Cross1b6a3cf2018-07-24 14:51:30 -070056 parser.add_argument('--library', dest='library', action='store_true',
57 help='manifest is for a static library')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090058 parser.add_argument('--uses-library', dest='uses_libraries', action='append',
Jiyong Parkfa17afe2018-10-16 11:00:04 +090059 help='specify additional <uses-library> tag to add. android:requred is set to true')
60 parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
61 help='specify additional <uses-library> tag to add. android:requred is set to false')
David Brazdild5b74992018-08-28 12:41:01 +010062 parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
63 help='manifest is for a package built against the platform')
Victor Hsiehd181c8b2019-01-29 13:00:33 -080064 parser.add_argument('--use-embedded-dex', dest='use_embedded_dex', action='store_true',
65 help=('specify if the app wants to use embedded dex and avoid extracted,'
66 'locally compiled code. Should not be conflict if already declared '
67 'in the manifest.'))
Colin Cross8bb10e82018-06-07 16:46:02 -070068 parser.add_argument('input', help='input AndroidManifest.xml file')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090069 parser.add_argument('output', help='output AndroidManifest.xml file')
Colin Cross8bb10e82018-06-07 16:46:02 -070070 return parser.parse_args()
71
72
73def parse_manifest(doc):
74 """Get the manifest element."""
75
76 manifest = doc.documentElement
77 if manifest.tagName != 'manifest':
78 raise RuntimeError('expected manifest tag at root')
79 return manifest
80
81
82def ensure_manifest_android_ns(doc):
83 """Make sure the manifest tag defines the android namespace."""
84
85 manifest = parse_manifest(doc)
86
87 ns = manifest.getAttributeNodeNS(minidom.XMLNS_NAMESPACE, 'android')
88 if ns is None:
89 attr = doc.createAttributeNS(minidom.XMLNS_NAMESPACE, 'xmlns:android')
90 attr.value = android_ns
91 manifest.setAttributeNode(attr)
92 elif ns.value != android_ns:
93 raise RuntimeError('manifest tag has incorrect android namespace ' +
94 ns.value)
95
96
97def as_int(s):
98 try:
99 i = int(s)
100 except ValueError:
101 return s, False
102 return i, True
103
104
105def compare_version_gt(a, b):
106 """Compare two SDK versions.
107
108 Compares a and b, treating codenames like 'Q' as higher
109 than numerical versions like '28'.
110
111 Returns True if a > b
112
113 Args:
114 a: value to compare
115 b: value to compare
116 Returns:
117 True if a is a higher version than b
118 """
119
120 a, a_is_int = as_int(a.upper())
121 b, b_is_int = as_int(b.upper())
122
123 if a_is_int == b_is_int:
124 # Both are codenames or both are versions, compare directly
125 return a > b
126 else:
127 # One is a codename, the other is not. Return true if
128 # b is an integer version
129 return b_is_int
130
131
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900132def get_indent(element, default_level):
133 indent = ''
134 if element is not None and element.nodeType == minidom.Node.TEXT_NODE:
135 text = element.nodeValue
136 indent = text[:len(text)-len(text.lstrip())]
137 if not indent or indent == '\n':
138 # 1 indent = 4 space
139 indent = '\n' + (' ' * default_level * 4)
140 return indent
141
142
Colin Cross7b59e7b2018-09-10 13:35:13 -0700143def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -0700144 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
145
146 Args:
147 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -0700148 min_sdk_version: The requested minSdkVersion attribute.
149 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross8bb10e82018-06-07 16:46:02 -0700150 Raises:
151 RuntimeError: invalid manifest
152 """
153
154 manifest = parse_manifest(doc)
155
156 # Get or insert the uses-sdk element
157 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
158 if len(uses_sdk) > 1:
159 raise RuntimeError('found multiple uses-sdk elements')
160 elif len(uses_sdk) == 1:
161 element = uses_sdk[0]
162 else:
163 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900164 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -0700165 manifest.insertBefore(element, manifest.firstChild)
166
167 # Insert an indent before uses-sdk to line it up with the indentation of the
168 # other children of the <manifest> tag.
169 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
170
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700171 # Get or insert the minSdkVersion attribute. If it is already present, make
172 # sure it as least the requested value.
Colin Cross8bb10e82018-06-07 16:46:02 -0700173 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
174 if min_attr is None:
175 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -0700176 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700177 element.setAttributeNode(min_attr)
178 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700179 if compare_version_gt(min_sdk_version, min_attr.value):
180 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700181
182 # Insert the targetSdkVersion attribute if it is missing. If it is already
183 # present leave it as is.
184 target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
185 if target_attr is None:
186 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
187 if library:
Colin Cross4b176062018-10-01 15:15:51 -0700188 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
189 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
190 # is empty. Set it to something low so that it will be overriden by the
191 # main manifest, but high enough that it doesn't cause implicit
192 # permissions grants.
193 target_attr.value = '15'
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700194 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700195 target_attr.value = target_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700196 element.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700197
198
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900199def add_uses_libraries(doc, new_uses_libraries, required):
200 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900201
202 Args:
203 doc: The XML document. May be modified by this function.
204 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900205 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900206 Raises:
207 RuntimeError: Invalid manifest
208 """
209
210 manifest = parse_manifest(doc)
211 elems = get_children_with_tag(manifest, 'application')
212 application = elems[0] if len(elems) == 1 else None
213 if len(elems) > 1:
214 raise RuntimeError('found multiple <application> tags')
215 elif not elems:
216 application = doc.createElement('application')
217 indent = get_indent(manifest.firstChild, 1)
218 first = manifest.firstChild
219 manifest.insertBefore(doc.createTextNode(indent), first)
220 manifest.insertBefore(application, first)
221
222 indent = get_indent(application.firstChild, 2)
223
224 last = application.lastChild
225 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
226 last = None
227
228 for name in new_uses_libraries:
229 if find_child_with_attribute(application, 'uses-library', android_ns,
230 'name', name) is not None:
231 # If the uses-library tag of the same 'name' attribute value exists,
232 # respect it.
233 continue
234
235 ul = doc.createElement('uses-library')
236 ul.setAttributeNS(android_ns, 'android:name', name)
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900237 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900238
239 application.insertBefore(doc.createTextNode(indent), last)
240 application.insertBefore(ul, last)
241
242 # align the closing tag with the opening tag if it's not
243 # indented
244 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
245 indent = get_indent(application.previousSibling, 1)
246 application.appendChild(doc.createTextNode(indent))
247
David Brazdild5b74992018-08-28 12:41:01 +0100248def add_uses_non_sdk_api(doc):
249 """Add android:usesNonSdkApi=true attribute to <application>.
250
251 Args:
252 doc: The XML document. May be modified by this function.
253 Raises:
254 RuntimeError: Invalid manifest
255 """
256
257 manifest = parse_manifest(doc)
258 elems = get_children_with_tag(manifest, 'application')
259 application = elems[0] if len(elems) == 1 else None
260 if len(elems) > 1:
261 raise RuntimeError('found multiple <application> tags')
262 elif not elems:
263 application = doc.createElement('application')
264 indent = get_indent(manifest.firstChild, 1)
265 first = manifest.firstChild
266 manifest.insertBefore(doc.createTextNode(indent), first)
267 manifest.insertBefore(application, first)
268
269 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
270 if attr is None:
271 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
272 attr.value = 'true'
273 application.setAttributeNode(attr)
274
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900275
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800276def add_use_embedded_dex(doc):
Victor Hsiehce7818e2018-10-22 11:16:25 -0700277 manifest = parse_manifest(doc)
278 elems = get_children_with_tag(manifest, 'application')
279 application = elems[0] if len(elems) == 1 else None
280 if len(elems) > 1:
281 raise RuntimeError('found multiple <application> tags')
282 elif not elems:
283 application = doc.createElement('application')
284 indent = get_indent(manifest.firstChild, 1)
285 first = manifest.firstChild
286 manifest.insertBefore(doc.createTextNode(indent), first)
287 manifest.insertBefore(application, first)
288
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800289 attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700290 if attr is None:
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800291 attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700292 attr.value = 'true'
293 application.setAttributeNode(attr)
294 elif attr.value != 'true':
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800295 raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700296
297
Colin Cross8bb10e82018-06-07 16:46:02 -0700298def write_xml(f, doc):
299 f.write('<?xml version="1.0" encoding="utf-8"?>\n')
300 for node in doc.childNodes:
301 f.write(node.toxml(encoding='utf-8') + '\n')
302
303
304def main():
305 """Program entry point."""
306 try:
307 args = parse_args()
308
309 doc = minidom.parse(args.input)
310
311 ensure_manifest_android_ns(doc)
312
Colin Cross7b59e7b2018-09-10 13:35:13 -0700313 if args.raise_min_sdk_version:
314 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700315
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900316 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900317 add_uses_libraries(doc, args.uses_libraries, True)
318
319 if args.optional_uses_libraries:
320 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900321
David Brazdild5b74992018-08-28 12:41:01 +0100322 if args.uses_non_sdk_api:
323 add_uses_non_sdk_api(doc)
324
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800325 if args.use_embedded_dex:
326 add_use_embedded_dex(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700327
Colin Cross8bb10e82018-06-07 16:46:02 -0700328 with open(args.output, 'wb') as f:
329 write_xml(f, doc)
330
331 # pylint: disable=broad-except
332 except Exception as err:
333 print('error: ' + str(err), file=sys.stderr)
334 sys.exit(-1)
335
336if __name__ == '__main__':
337 main()