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