blob: bb148513264d515eddf180dfaeaeff084070f767 [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
Colin Cross72119102019-05-20 13:14:18 -070020
Colin Cross8bb10e82018-06-07 16:46:02 -070021import argparse
22import sys
23from xml.dom import minidom
24
25
Colin Cross72119102019-05-20 13:14:18 -070026from manifest import android_ns
27from manifest import compare_version_gt
28from manifest import ensure_manifest_android_ns
29from manifest import find_child_with_attribute
30from manifest import get_children_with_tag
31from manifest import get_indent
32from manifest import parse_manifest
33from manifest import write_xml
Jiyong Parkc08f46f2018-06-18 11:01:00 +090034
35
Colin Cross8bb10e82018-06-07 16:46:02 -070036def parse_args():
37 """Parse commandline arguments."""
38
39 parser = argparse.ArgumentParser()
40 parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
41 help='specify minSdkVersion used by the build system')
Colin Cross7b59e7b2018-09-10 13:35:13 -070042 parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
43 help='specify targetSdkVersion used by the build system')
44 parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
45 help='raise the minimum sdk version in the manifest if necessary')
Colin Cross1b6a3cf2018-07-24 14:51:30 -070046 parser.add_argument('--library', dest='library', action='store_true',
47 help='manifest is for a static library')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090048 parser.add_argument('--uses-library', dest='uses_libraries', action='append',
Jiyong Parkfa17afe2018-10-16 11:00:04 +090049 help='specify additional <uses-library> tag to add. android:requred is set to true')
50 parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
51 help='specify additional <uses-library> tag to add. android:requred is set to false')
David Brazdild5b74992018-08-28 12:41:01 +010052 parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
53 help='manifest is for a package built against the platform')
Victor Hsiehd181c8b2019-01-29 13:00:33 -080054 parser.add_argument('--use-embedded-dex', dest='use_embedded_dex', action='store_true',
55 help=('specify if the app wants to use embedded dex and avoid extracted,'
Colin Crosse4246ab2019-02-05 21:55:21 -080056 'locally compiled code. Must not conflict if already declared '
Victor Hsiehd181c8b2019-01-29 13:00:33 -080057 'in the manifest.'))
Colin Crosse4246ab2019-02-05 21:55:21 -080058 parser.add_argument('--extract-native-libs', dest='extract_native_libs',
59 default=None, type=lambda x: (str(x).lower() == 'true'),
60 help=('specify if the app wants to use embedded native libraries. Must not conflict '
61 'if already declared in the manifest.'))
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
Colin Cross7b59e7b2018-09-10 13:35:13 -070067def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -070068 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
69
70 Args:
71 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -070072 min_sdk_version: The requested minSdkVersion attribute.
73 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross72119102019-05-20 13:14:18 -070074 library: True if the manifest is for a library.
Colin Cross8bb10e82018-06-07 16:46:02 -070075 Raises:
76 RuntimeError: invalid manifest
77 """
78
79 manifest = parse_manifest(doc)
80
81 # Get or insert the uses-sdk element
82 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
83 if len(uses_sdk) > 1:
84 raise RuntimeError('found multiple uses-sdk elements')
85 elif len(uses_sdk) == 1:
86 element = uses_sdk[0]
87 else:
88 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090089 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -070090 manifest.insertBefore(element, manifest.firstChild)
91
92 # Insert an indent before uses-sdk to line it up with the indentation of the
93 # other children of the <manifest> tag.
94 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
95
Colin Cross1b6a3cf2018-07-24 14:51:30 -070096 # Get or insert the minSdkVersion attribute. If it is already present, make
97 # sure it as least the requested value.
Colin Cross8bb10e82018-06-07 16:46:02 -070098 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
99 if min_attr is None:
100 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -0700101 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700102 element.setAttributeNode(min_attr)
103 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700104 if compare_version_gt(min_sdk_version, min_attr.value):
105 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700106
107 # Insert the targetSdkVersion attribute if it is missing. If it is already
108 # present leave it as is.
109 target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
110 if target_attr is None:
111 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
112 if library:
Colin Cross4b176062018-10-01 15:15:51 -0700113 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
114 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
115 # is empty. Set it to something low so that it will be overriden by the
116 # main manifest, but high enough that it doesn't cause implicit
117 # permissions grants.
118 target_attr.value = '15'
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700119 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700120 target_attr.value = target_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700121 element.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700122
123
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900124def add_uses_libraries(doc, new_uses_libraries, required):
125 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900126
127 Args:
128 doc: The XML document. May be modified by this function.
129 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900130 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900131 Raises:
132 RuntimeError: Invalid manifest
133 """
134
135 manifest = parse_manifest(doc)
136 elems = get_children_with_tag(manifest, 'application')
137 application = elems[0] if len(elems) == 1 else None
138 if len(elems) > 1:
139 raise RuntimeError('found multiple <application> tags')
140 elif not elems:
141 application = doc.createElement('application')
142 indent = get_indent(manifest.firstChild, 1)
143 first = manifest.firstChild
144 manifest.insertBefore(doc.createTextNode(indent), first)
145 manifest.insertBefore(application, first)
146
147 indent = get_indent(application.firstChild, 2)
148
149 last = application.lastChild
150 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
151 last = None
152
153 for name in new_uses_libraries:
154 if find_child_with_attribute(application, 'uses-library', android_ns,
155 'name', name) is not None:
156 # If the uses-library tag of the same 'name' attribute value exists,
157 # respect it.
158 continue
159
160 ul = doc.createElement('uses-library')
161 ul.setAttributeNS(android_ns, 'android:name', name)
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900162 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900163
164 application.insertBefore(doc.createTextNode(indent), last)
165 application.insertBefore(ul, last)
166
167 # align the closing tag with the opening tag if it's not
168 # indented
169 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
170 indent = get_indent(application.previousSibling, 1)
171 application.appendChild(doc.createTextNode(indent))
172
Colin Cross72119102019-05-20 13:14:18 -0700173
David Brazdild5b74992018-08-28 12:41:01 +0100174def add_uses_non_sdk_api(doc):
175 """Add android:usesNonSdkApi=true attribute to <application>.
176
177 Args:
178 doc: The XML document. May be modified by this function.
179 Raises:
180 RuntimeError: Invalid manifest
181 """
182
183 manifest = parse_manifest(doc)
184 elems = get_children_with_tag(manifest, 'application')
185 application = elems[0] if len(elems) == 1 else None
186 if len(elems) > 1:
187 raise RuntimeError('found multiple <application> tags')
188 elif not elems:
189 application = doc.createElement('application')
190 indent = get_indent(manifest.firstChild, 1)
191 first = manifest.firstChild
192 manifest.insertBefore(doc.createTextNode(indent), first)
193 manifest.insertBefore(application, first)
194
195 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
196 if attr is None:
197 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
198 attr.value = 'true'
199 application.setAttributeNode(attr)
200
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900201
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800202def add_use_embedded_dex(doc):
Victor Hsiehce7818e2018-10-22 11:16:25 -0700203 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
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800215 attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700216 if attr is None:
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800217 attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700218 attr.value = 'true'
219 application.setAttributeNode(attr)
220 elif attr.value != 'true':
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800221 raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700222
223
Colin Crosse4246ab2019-02-05 21:55:21 -0800224def add_extract_native_libs(doc, extract_native_libs):
225 manifest = parse_manifest(doc)
226 elems = get_children_with_tag(manifest, 'application')
227 application = elems[0] if len(elems) == 1 else None
228 if len(elems) > 1:
229 raise RuntimeError('found multiple <application> tags')
230 elif not elems:
231 application = doc.createElement('application')
232 indent = get_indent(manifest.firstChild, 1)
233 first = manifest.firstChild
234 manifest.insertBefore(doc.createTextNode(indent), first)
235 manifest.insertBefore(application, first)
236
237 value = str(extract_native_libs).lower()
238 attr = application.getAttributeNodeNS(android_ns, 'extractNativeLibs')
239 if attr is None:
240 attr = doc.createAttributeNS(android_ns, 'android:extractNativeLibs')
241 attr.value = value
242 application.setAttributeNode(attr)
243 elif attr.value != value:
244 raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
245 (attr.value, value))
246
247
Colin Cross8bb10e82018-06-07 16:46:02 -0700248def main():
249 """Program entry point."""
250 try:
251 args = parse_args()
252
253 doc = minidom.parse(args.input)
254
255 ensure_manifest_android_ns(doc)
256
Colin Cross7b59e7b2018-09-10 13:35:13 -0700257 if args.raise_min_sdk_version:
258 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700259
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900260 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900261 add_uses_libraries(doc, args.uses_libraries, True)
262
263 if args.optional_uses_libraries:
264 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900265
David Brazdild5b74992018-08-28 12:41:01 +0100266 if args.uses_non_sdk_api:
267 add_uses_non_sdk_api(doc)
268
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800269 if args.use_embedded_dex:
270 add_use_embedded_dex(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700271
Colin Crosse4246ab2019-02-05 21:55:21 -0800272 if args.extract_native_libs is not None:
273 add_extract_native_libs(doc, args.extract_native_libs)
274
Colin Cross8bb10e82018-06-07 16:46:02 -0700275 with open(args.output, 'wb') as f:
276 write_xml(f, doc)
277
278 # pylint: disable=broad-except
279 except Exception as err:
280 print('error: ' + str(err), file=sys.stderr)
281 sys.exit(-1)
282
283if __name__ == '__main__':
284 main()