blob: b6fe34e6e5c3514789d30e646afb0fa00895411b [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',
59 help='specify additional <uses-library> tag to add')
David Brazdild5b74992018-08-28 12:41:01 +010060 parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
61 help='manifest is for a package built against the platform')
Colin Cross8bb10e82018-06-07 16:46:02 -070062 parser.add_argument('input', help='input AndroidManifest.xml file')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090063 parser.add_argument('output', help='output AndroidManifest.xml file')
Colin Cross8bb10e82018-06-07 16:46:02 -070064 return parser.parse_args()
65
66
67def parse_manifest(doc):
68 """Get the manifest element."""
69
70 manifest = doc.documentElement
71 if manifest.tagName != 'manifest':
72 raise RuntimeError('expected manifest tag at root')
73 return manifest
74
75
76def ensure_manifest_android_ns(doc):
77 """Make sure the manifest tag defines the android namespace."""
78
79 manifest = parse_manifest(doc)
80
81 ns = manifest.getAttributeNodeNS(minidom.XMLNS_NAMESPACE, 'android')
82 if ns is None:
83 attr = doc.createAttributeNS(minidom.XMLNS_NAMESPACE, 'xmlns:android')
84 attr.value = android_ns
85 manifest.setAttributeNode(attr)
86 elif ns.value != android_ns:
87 raise RuntimeError('manifest tag has incorrect android namespace ' +
88 ns.value)
89
90
91def as_int(s):
92 try:
93 i = int(s)
94 except ValueError:
95 return s, False
96 return i, True
97
98
99def compare_version_gt(a, b):
100 """Compare two SDK versions.
101
102 Compares a and b, treating codenames like 'Q' as higher
103 than numerical versions like '28'.
104
105 Returns True if a > b
106
107 Args:
108 a: value to compare
109 b: value to compare
110 Returns:
111 True if a is a higher version than b
112 """
113
114 a, a_is_int = as_int(a.upper())
115 b, b_is_int = as_int(b.upper())
116
117 if a_is_int == b_is_int:
118 # Both are codenames or both are versions, compare directly
119 return a > b
120 else:
121 # One is a codename, the other is not. Return true if
122 # b is an integer version
123 return b_is_int
124
125
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900126def get_indent(element, default_level):
127 indent = ''
128 if element is not None and element.nodeType == minidom.Node.TEXT_NODE:
129 text = element.nodeValue
130 indent = text[:len(text)-len(text.lstrip())]
131 if not indent or indent == '\n':
132 # 1 indent = 4 space
133 indent = '\n' + (' ' * default_level * 4)
134 return indent
135
136
Colin Cross7b59e7b2018-09-10 13:35:13 -0700137def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -0700138 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
139
140 Args:
141 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -0700142 min_sdk_version: The requested minSdkVersion attribute.
143 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross8bb10e82018-06-07 16:46:02 -0700144 Raises:
145 RuntimeError: invalid manifest
146 """
147
148 manifest = parse_manifest(doc)
149
150 # Get or insert the uses-sdk element
151 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
152 if len(uses_sdk) > 1:
153 raise RuntimeError('found multiple uses-sdk elements')
154 elif len(uses_sdk) == 1:
155 element = uses_sdk[0]
156 else:
157 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900158 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -0700159 manifest.insertBefore(element, manifest.firstChild)
160
161 # Insert an indent before uses-sdk to line it up with the indentation of the
162 # other children of the <manifest> tag.
163 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
164
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700165 # Get or insert the minSdkVersion attribute. If it is already present, make
166 # sure it as least the requested value.
Colin Cross8bb10e82018-06-07 16:46:02 -0700167 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
168 if min_attr is None:
169 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -0700170 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700171 element.setAttributeNode(min_attr)
172 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700173 if compare_version_gt(min_sdk_version, min_attr.value):
174 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700175
176 # Insert the targetSdkVersion attribute if it is missing. If it is already
177 # present leave it as is.
178 target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
179 if target_attr is None:
180 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
181 if library:
182 target_attr.value = '1'
183 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700184 target_attr.value = target_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700185 element.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700186
187
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900188def add_uses_libraries(doc, new_uses_libraries):
189 """Add additional <uses-library> tags with android:required=true.
190
191 Args:
192 doc: The XML document. May be modified by this function.
193 new_uses_libraries: The names of libraries to be added by this function.
194 Raises:
195 RuntimeError: Invalid manifest
196 """
197
198 manifest = parse_manifest(doc)
199 elems = get_children_with_tag(manifest, 'application')
200 application = elems[0] if len(elems) == 1 else None
201 if len(elems) > 1:
202 raise RuntimeError('found multiple <application> tags')
203 elif not elems:
204 application = doc.createElement('application')
205 indent = get_indent(manifest.firstChild, 1)
206 first = manifest.firstChild
207 manifest.insertBefore(doc.createTextNode(indent), first)
208 manifest.insertBefore(application, first)
209
210 indent = get_indent(application.firstChild, 2)
211
212 last = application.lastChild
213 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
214 last = None
215
216 for name in new_uses_libraries:
217 if find_child_with_attribute(application, 'uses-library', android_ns,
218 'name', name) is not None:
219 # If the uses-library tag of the same 'name' attribute value exists,
220 # respect it.
221 continue
222
223 ul = doc.createElement('uses-library')
224 ul.setAttributeNS(android_ns, 'android:name', name)
225 ul.setAttributeNS(android_ns, 'android:required', 'true')
226
227 application.insertBefore(doc.createTextNode(indent), last)
228 application.insertBefore(ul, last)
229
230 # align the closing tag with the opening tag if it's not
231 # indented
232 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
233 indent = get_indent(application.previousSibling, 1)
234 application.appendChild(doc.createTextNode(indent))
235
David Brazdild5b74992018-08-28 12:41:01 +0100236def add_uses_non_sdk_api(doc):
237 """Add android:usesNonSdkApi=true attribute to <application>.
238
239 Args:
240 doc: The XML document. May be modified by this function.
241 Raises:
242 RuntimeError: Invalid manifest
243 """
244
245 manifest = parse_manifest(doc)
246 elems = get_children_with_tag(manifest, 'application')
247 application = elems[0] if len(elems) == 1 else None
248 if len(elems) > 1:
249 raise RuntimeError('found multiple <application> tags')
250 elif not elems:
251 application = doc.createElement('application')
252 indent = get_indent(manifest.firstChild, 1)
253 first = manifest.firstChild
254 manifest.insertBefore(doc.createTextNode(indent), first)
255 manifest.insertBefore(application, first)
256
257 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
258 if attr is None:
259 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
260 attr.value = 'true'
261 application.setAttributeNode(attr)
262
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900263
Colin Cross8bb10e82018-06-07 16:46:02 -0700264def write_xml(f, doc):
265 f.write('<?xml version="1.0" encoding="utf-8"?>\n')
266 for node in doc.childNodes:
267 f.write(node.toxml(encoding='utf-8') + '\n')
268
269
270def main():
271 """Program entry point."""
272 try:
273 args = parse_args()
274
275 doc = minidom.parse(args.input)
276
277 ensure_manifest_android_ns(doc)
278
Colin Cross7b59e7b2018-09-10 13:35:13 -0700279 if args.raise_min_sdk_version:
280 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700281
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900282 if args.uses_libraries:
283 add_uses_libraries(doc, args.uses_libraries)
284
David Brazdild5b74992018-08-28 12:41:01 +0100285 if args.uses_non_sdk_api:
286 add_uses_non_sdk_api(doc)
287
Colin Cross8bb10e82018-06-07 16:46:02 -0700288 with open(args.output, 'wb') as f:
289 write_xml(f, doc)
290
291 # pylint: disable=broad-except
292 except Exception as err:
293 print('error: ' + str(err), file=sys.stderr)
294 sys.exit(-1)
295
296if __name__ == '__main__':
297 main()