Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 1 | #!/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 | |
| 19 | from __future__ import print_function |
| 20 | import argparse |
| 21 | import sys |
| 22 | from xml.dom import minidom |
| 23 | |
| 24 | |
| 25 | android_ns = 'http://schemas.android.com/apk/res/android' |
| 26 | |
| 27 | |
| 28 | def 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 Park | c08f46f | 2018-06-18 11:01:00 +0900 | [diff] [blame] | 37 | def 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 Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 46 | def 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 Cross | 7b59e7b | 2018-09-10 13:35:13 -0700 | [diff] [blame] | 52 | 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 Cross | 1b6a3cf | 2018-07-24 14:51:30 -0700 | [diff] [blame] | 56 | parser.add_argument('--library', dest='library', action='store_true', |
| 57 | help='manifest is for a static library') |
Jiyong Park | c08f46f | 2018-06-18 11:01:00 +0900 | [diff] [blame] | 58 | parser.add_argument('--uses-library', dest='uses_libraries', action='append', |
| 59 | help='specify additional <uses-library> tag to add') |
David Brazdil | d5b7499 | 2018-08-28 12:41:01 +0100 | [diff] [blame] | 60 | 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 Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 62 | parser.add_argument('input', help='input AndroidManifest.xml file') |
Jiyong Park | c08f46f | 2018-06-18 11:01:00 +0900 | [diff] [blame] | 63 | parser.add_argument('output', help='output AndroidManifest.xml file') |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 64 | return parser.parse_args() |
| 65 | |
| 66 | |
| 67 | def 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 | |
| 76 | def 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 | |
| 91 | def as_int(s): |
| 92 | try: |
| 93 | i = int(s) |
| 94 | except ValueError: |
| 95 | return s, False |
| 96 | return i, True |
| 97 | |
| 98 | |
| 99 | def 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 Park | c08f46f | 2018-06-18 11:01:00 +0900 | [diff] [blame] | 126 | def 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 Cross | 7b59e7b | 2018-09-10 13:35:13 -0700 | [diff] [blame] | 137 | def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library): |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 138 | """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 Cross | 7b59e7b | 2018-09-10 13:35:13 -0700 | [diff] [blame] | 142 | min_sdk_version: The requested minSdkVersion attribute. |
| 143 | target_sdk_version: The requested targetSdkVersion attribute. |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 144 | 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 Park | c08f46f | 2018-06-18 11:01:00 +0900 | [diff] [blame] | 158 | indent = get_indent(manifest.firstChild, 1) |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 159 | 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 Cross | 1b6a3cf | 2018-07-24 14:51:30 -0700 | [diff] [blame] | 165 | # Get or insert the minSdkVersion attribute. If it is already present, make |
| 166 | # sure it as least the requested value. |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 167 | min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion') |
| 168 | if min_attr is None: |
| 169 | min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion') |
Colin Cross | 7b59e7b | 2018-09-10 13:35:13 -0700 | [diff] [blame] | 170 | min_attr.value = min_sdk_version |
Colin Cross | 1b6a3cf | 2018-07-24 14:51:30 -0700 | [diff] [blame] | 171 | element.setAttributeNode(min_attr) |
| 172 | else: |
Colin Cross | 7b59e7b | 2018-09-10 13:35:13 -0700 | [diff] [blame] | 173 | if compare_version_gt(min_sdk_version, min_attr.value): |
| 174 | min_attr.value = min_sdk_version |
Colin Cross | 1b6a3cf | 2018-07-24 14:51:30 -0700 | [diff] [blame] | 175 | |
| 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: |
Colin Cross | 4b17606 | 2018-10-01 15:15:51 -0700 | [diff] [blame] | 182 | # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but |
| 183 | # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it |
| 184 | # is empty. Set it to something low so that it will be overriden by the |
| 185 | # main manifest, but high enough that it doesn't cause implicit |
| 186 | # permissions grants. |
| 187 | target_attr.value = '15' |
Colin Cross | 1b6a3cf | 2018-07-24 14:51:30 -0700 | [diff] [blame] | 188 | else: |
Colin Cross | 7b59e7b | 2018-09-10 13:35:13 -0700 | [diff] [blame] | 189 | target_attr.value = target_sdk_version |
Colin Cross | 1b6a3cf | 2018-07-24 14:51:30 -0700 | [diff] [blame] | 190 | element.setAttributeNode(target_attr) |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 191 | |
| 192 | |
Jiyong Park | c08f46f | 2018-06-18 11:01:00 +0900 | [diff] [blame] | 193 | def add_uses_libraries(doc, new_uses_libraries): |
| 194 | """Add additional <uses-library> tags with android:required=true. |
| 195 | |
| 196 | Args: |
| 197 | doc: The XML document. May be modified by this function. |
| 198 | new_uses_libraries: The names of libraries to be added by this function. |
| 199 | Raises: |
| 200 | RuntimeError: Invalid manifest |
| 201 | """ |
| 202 | |
| 203 | manifest = parse_manifest(doc) |
| 204 | elems = get_children_with_tag(manifest, 'application') |
| 205 | application = elems[0] if len(elems) == 1 else None |
| 206 | if len(elems) > 1: |
| 207 | raise RuntimeError('found multiple <application> tags') |
| 208 | elif not elems: |
| 209 | application = doc.createElement('application') |
| 210 | indent = get_indent(manifest.firstChild, 1) |
| 211 | first = manifest.firstChild |
| 212 | manifest.insertBefore(doc.createTextNode(indent), first) |
| 213 | manifest.insertBefore(application, first) |
| 214 | |
| 215 | indent = get_indent(application.firstChild, 2) |
| 216 | |
| 217 | last = application.lastChild |
| 218 | if last is not None and last.nodeType != minidom.Node.TEXT_NODE: |
| 219 | last = None |
| 220 | |
| 221 | for name in new_uses_libraries: |
| 222 | if find_child_with_attribute(application, 'uses-library', android_ns, |
| 223 | 'name', name) is not None: |
| 224 | # If the uses-library tag of the same 'name' attribute value exists, |
| 225 | # respect it. |
| 226 | continue |
| 227 | |
| 228 | ul = doc.createElement('uses-library') |
| 229 | ul.setAttributeNS(android_ns, 'android:name', name) |
| 230 | ul.setAttributeNS(android_ns, 'android:required', 'true') |
| 231 | |
| 232 | application.insertBefore(doc.createTextNode(indent), last) |
| 233 | application.insertBefore(ul, last) |
| 234 | |
| 235 | # align the closing tag with the opening tag if it's not |
| 236 | # indented |
| 237 | if application.lastChild.nodeType != minidom.Node.TEXT_NODE: |
| 238 | indent = get_indent(application.previousSibling, 1) |
| 239 | application.appendChild(doc.createTextNode(indent)) |
| 240 | |
David Brazdil | d5b7499 | 2018-08-28 12:41:01 +0100 | [diff] [blame] | 241 | def add_uses_non_sdk_api(doc): |
| 242 | """Add android:usesNonSdkApi=true attribute to <application>. |
| 243 | |
| 244 | Args: |
| 245 | doc: The XML document. May be modified by this function. |
| 246 | Raises: |
| 247 | RuntimeError: Invalid manifest |
| 248 | """ |
| 249 | |
| 250 | manifest = parse_manifest(doc) |
| 251 | elems = get_children_with_tag(manifest, 'application') |
| 252 | application = elems[0] if len(elems) == 1 else None |
| 253 | if len(elems) > 1: |
| 254 | raise RuntimeError('found multiple <application> tags') |
| 255 | elif not elems: |
| 256 | application = doc.createElement('application') |
| 257 | indent = get_indent(manifest.firstChild, 1) |
| 258 | first = manifest.firstChild |
| 259 | manifest.insertBefore(doc.createTextNode(indent), first) |
| 260 | manifest.insertBefore(application, first) |
| 261 | |
| 262 | attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi') |
| 263 | if attr is None: |
| 264 | attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi') |
| 265 | attr.value = 'true' |
| 266 | application.setAttributeNode(attr) |
| 267 | |
Jiyong Park | c08f46f | 2018-06-18 11:01:00 +0900 | [diff] [blame] | 268 | |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 269 | def write_xml(f, doc): |
| 270 | f.write('<?xml version="1.0" encoding="utf-8"?>\n') |
| 271 | for node in doc.childNodes: |
| 272 | f.write(node.toxml(encoding='utf-8') + '\n') |
| 273 | |
| 274 | |
| 275 | def main(): |
| 276 | """Program entry point.""" |
| 277 | try: |
| 278 | args = parse_args() |
| 279 | |
| 280 | doc = minidom.parse(args.input) |
| 281 | |
| 282 | ensure_manifest_android_ns(doc) |
| 283 | |
Colin Cross | 7b59e7b | 2018-09-10 13:35:13 -0700 | [diff] [blame] | 284 | if args.raise_min_sdk_version: |
| 285 | raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library) |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 286 | |
Jiyong Park | c08f46f | 2018-06-18 11:01:00 +0900 | [diff] [blame] | 287 | if args.uses_libraries: |
| 288 | add_uses_libraries(doc, args.uses_libraries) |
| 289 | |
David Brazdil | d5b7499 | 2018-08-28 12:41:01 +0100 | [diff] [blame] | 290 | if args.uses_non_sdk_api: |
| 291 | add_uses_non_sdk_api(doc) |
| 292 | |
Colin Cross | 8bb10e8 | 2018-06-07 16:46:02 -0700 | [diff] [blame] | 293 | with open(args.output, 'wb') as f: |
| 294 | write_xml(f, doc) |
| 295 | |
| 296 | # pylint: disable=broad-except |
| 297 | except Exception as err: |
| 298 | print('error: ' + str(err), file=sys.stderr) |
| 299 | sys.exit(-1) |
| 300 | |
| 301 | if __name__ == '__main__': |
| 302 | main() |