blob: 9256cb29e34e8574ae957acabde6d5944b271ca4 [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')
Colin Cross8bb10e82018-06-07 16:46:02 -070064 parser.add_argument('input', help='input AndroidManifest.xml file')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090065 parser.add_argument('output', help='output AndroidManifest.xml file')
Colin Cross8bb10e82018-06-07 16:46:02 -070066 return parser.parse_args()
67
68
69def parse_manifest(doc):
70 """Get the manifest element."""
71
72 manifest = doc.documentElement
73 if manifest.tagName != 'manifest':
74 raise RuntimeError('expected manifest tag at root')
75 return manifest
76
77
78def ensure_manifest_android_ns(doc):
79 """Make sure the manifest tag defines the android namespace."""
80
81 manifest = parse_manifest(doc)
82
83 ns = manifest.getAttributeNodeNS(minidom.XMLNS_NAMESPACE, 'android')
84 if ns is None:
85 attr = doc.createAttributeNS(minidom.XMLNS_NAMESPACE, 'xmlns:android')
86 attr.value = android_ns
87 manifest.setAttributeNode(attr)
88 elif ns.value != android_ns:
89 raise RuntimeError('manifest tag has incorrect android namespace ' +
90 ns.value)
91
92
93def as_int(s):
94 try:
95 i = int(s)
96 except ValueError:
97 return s, False
98 return i, True
99
100
101def compare_version_gt(a, b):
102 """Compare two SDK versions.
103
104 Compares a and b, treating codenames like 'Q' as higher
105 than numerical versions like '28'.
106
107 Returns True if a > b
108
109 Args:
110 a: value to compare
111 b: value to compare
112 Returns:
113 True if a is a higher version than b
114 """
115
116 a, a_is_int = as_int(a.upper())
117 b, b_is_int = as_int(b.upper())
118
119 if a_is_int == b_is_int:
120 # Both are codenames or both are versions, compare directly
121 return a > b
122 else:
123 # One is a codename, the other is not. Return true if
124 # b is an integer version
125 return b_is_int
126
127
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900128def get_indent(element, default_level):
129 indent = ''
130 if element is not None and element.nodeType == minidom.Node.TEXT_NODE:
131 text = element.nodeValue
132 indent = text[:len(text)-len(text.lstrip())]
133 if not indent or indent == '\n':
134 # 1 indent = 4 space
135 indent = '\n' + (' ' * default_level * 4)
136 return indent
137
138
Colin Cross7b59e7b2018-09-10 13:35:13 -0700139def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -0700140 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
141
142 Args:
143 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -0700144 min_sdk_version: The requested minSdkVersion attribute.
145 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross8bb10e82018-06-07 16:46:02 -0700146 Raises:
147 RuntimeError: invalid manifest
148 """
149
150 manifest = parse_manifest(doc)
151
152 # Get or insert the uses-sdk element
153 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
154 if len(uses_sdk) > 1:
155 raise RuntimeError('found multiple uses-sdk elements')
156 elif len(uses_sdk) == 1:
157 element = uses_sdk[0]
158 else:
159 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900160 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -0700161 manifest.insertBefore(element, manifest.firstChild)
162
163 # Insert an indent before uses-sdk to line it up with the indentation of the
164 # other children of the <manifest> tag.
165 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
166
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700167 # Get or insert the minSdkVersion attribute. If it is already present, make
168 # sure it as least the requested value.
Colin Cross8bb10e82018-06-07 16:46:02 -0700169 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
170 if min_attr is None:
171 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -0700172 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700173 element.setAttributeNode(min_attr)
174 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700175 if compare_version_gt(min_sdk_version, min_attr.value):
176 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700177
178 # Insert the targetSdkVersion attribute if it is missing. If it is already
179 # present leave it as is.
180 target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
181 if target_attr is None:
182 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
183 if library:
Colin Cross4b176062018-10-01 15:15:51 -0700184 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
185 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
186 # is empty. Set it to something low so that it will be overriden by the
187 # main manifest, but high enough that it doesn't cause implicit
188 # permissions grants.
189 target_attr.value = '15'
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700190 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700191 target_attr.value = target_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700192 element.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700193
194
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900195def add_uses_libraries(doc, new_uses_libraries, required):
196 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900197
198 Args:
199 doc: The XML document. May be modified by this function.
200 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900201 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900202 Raises:
203 RuntimeError: Invalid manifest
204 """
205
206 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
218 indent = get_indent(application.firstChild, 2)
219
220 last = application.lastChild
221 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
222 last = None
223
224 for name in new_uses_libraries:
225 if find_child_with_attribute(application, 'uses-library', android_ns,
226 'name', name) is not None:
227 # If the uses-library tag of the same 'name' attribute value exists,
228 # respect it.
229 continue
230
231 ul = doc.createElement('uses-library')
232 ul.setAttributeNS(android_ns, 'android:name', name)
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900233 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900234
235 application.insertBefore(doc.createTextNode(indent), last)
236 application.insertBefore(ul, last)
237
238 # align the closing tag with the opening tag if it's not
239 # indented
240 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
241 indent = get_indent(application.previousSibling, 1)
242 application.appendChild(doc.createTextNode(indent))
243
David Brazdild5b74992018-08-28 12:41:01 +0100244def add_uses_non_sdk_api(doc):
245 """Add android:usesNonSdkApi=true attribute to <application>.
246
247 Args:
248 doc: The XML document. May be modified by this function.
249 Raises:
250 RuntimeError: Invalid manifest
251 """
252
253 manifest = parse_manifest(doc)
254 elems = get_children_with_tag(manifest, 'application')
255 application = elems[0] if len(elems) == 1 else None
256 if len(elems) > 1:
257 raise RuntimeError('found multiple <application> tags')
258 elif not elems:
259 application = doc.createElement('application')
260 indent = get_indent(manifest.firstChild, 1)
261 first = manifest.firstChild
262 manifest.insertBefore(doc.createTextNode(indent), first)
263 manifest.insertBefore(application, first)
264
265 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
266 if attr is None:
267 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
268 attr.value = 'true'
269 application.setAttributeNode(attr)
270
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900271
Colin Cross8bb10e82018-06-07 16:46:02 -0700272def write_xml(f, doc):
273 f.write('<?xml version="1.0" encoding="utf-8"?>\n')
274 for node in doc.childNodes:
275 f.write(node.toxml(encoding='utf-8') + '\n')
276
277
278def main():
279 """Program entry point."""
280 try:
281 args = parse_args()
282
283 doc = minidom.parse(args.input)
284
285 ensure_manifest_android_ns(doc)
286
Colin Cross7b59e7b2018-09-10 13:35:13 -0700287 if args.raise_min_sdk_version:
288 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700289
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900290 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900291 add_uses_libraries(doc, args.uses_libraries, True)
292
293 if args.optional_uses_libraries:
294 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900295
David Brazdild5b74992018-08-28 12:41:01 +0100296 if args.uses_non_sdk_api:
297 add_uses_non_sdk_api(doc)
298
Colin Cross8bb10e82018-06-07 16:46:02 -0700299 with open(args.output, 'wb') as f:
300 write_xml(f, doc)
301
302 # pylint: disable=broad-except
303 except Exception as err:
304 print('error: ' + str(err), file=sys.stderr)
305 sys.exit(-1)
306
307if __name__ == '__main__':
308 main()