blob: 6af0ca9001aaa30e2888f6a889a9c682fec88fa2 [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')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090052 parser.add_argument('--uses-library', dest='uses_libraries', action='append',
53 help='specify additional <uses-library> tag to add')
Colin Cross8bb10e82018-06-07 16:46:02 -070054 parser.add_argument('input', help='input AndroidManifest.xml file')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090055 parser.add_argument('output', help='output AndroidManifest.xml file')
Colin Cross8bb10e82018-06-07 16:46:02 -070056 return parser.parse_args()
57
58
59def parse_manifest(doc):
60 """Get the manifest element."""
61
62 manifest = doc.documentElement
63 if manifest.tagName != 'manifest':
64 raise RuntimeError('expected manifest tag at root')
65 return manifest
66
67
68def ensure_manifest_android_ns(doc):
69 """Make sure the manifest tag defines the android namespace."""
70
71 manifest = parse_manifest(doc)
72
73 ns = manifest.getAttributeNodeNS(minidom.XMLNS_NAMESPACE, 'android')
74 if ns is None:
75 attr = doc.createAttributeNS(minidom.XMLNS_NAMESPACE, 'xmlns:android')
76 attr.value = android_ns
77 manifest.setAttributeNode(attr)
78 elif ns.value != android_ns:
79 raise RuntimeError('manifest tag has incorrect android namespace ' +
80 ns.value)
81
82
83def as_int(s):
84 try:
85 i = int(s)
86 except ValueError:
87 return s, False
88 return i, True
89
90
91def compare_version_gt(a, b):
92 """Compare two SDK versions.
93
94 Compares a and b, treating codenames like 'Q' as higher
95 than numerical versions like '28'.
96
97 Returns True if a > b
98
99 Args:
100 a: value to compare
101 b: value to compare
102 Returns:
103 True if a is a higher version than b
104 """
105
106 a, a_is_int = as_int(a.upper())
107 b, b_is_int = as_int(b.upper())
108
109 if a_is_int == b_is_int:
110 # Both are codenames or both are versions, compare directly
111 return a > b
112 else:
113 # One is a codename, the other is not. Return true if
114 # b is an integer version
115 return b_is_int
116
117
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900118def get_indent(element, default_level):
119 indent = ''
120 if element is not None and element.nodeType == minidom.Node.TEXT_NODE:
121 text = element.nodeValue
122 indent = text[:len(text)-len(text.lstrip())]
123 if not indent or indent == '\n':
124 # 1 indent = 4 space
125 indent = '\n' + (' ' * default_level * 4)
126 return indent
127
128
Colin Cross8bb10e82018-06-07 16:46:02 -0700129def raise_min_sdk_version(doc, requested):
130 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
131
132 Args:
133 doc: The XML document. May be modified by this function.
134 requested: The requested minSdkVersion attribute.
135 Raises:
136 RuntimeError: invalid manifest
137 """
138
139 manifest = parse_manifest(doc)
140
141 # Get or insert the uses-sdk element
142 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
143 if len(uses_sdk) > 1:
144 raise RuntimeError('found multiple uses-sdk elements')
145 elif len(uses_sdk) == 1:
146 element = uses_sdk[0]
147 else:
148 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900149 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -0700150 manifest.insertBefore(element, manifest.firstChild)
151
152 # Insert an indent before uses-sdk to line it up with the indentation of the
153 # other children of the <manifest> tag.
154 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
155
156 # Get or insert the minSdkVersion attribute
157 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
158 if min_attr is None:
159 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
160 min_attr.value = '1'
161 element.setAttributeNode(min_attr)
162
163 # Update the value of the minSdkVersion attribute if necessary
164 if compare_version_gt(requested, min_attr.value):
165 min_attr.value = requested
166
167
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900168def add_uses_libraries(doc, new_uses_libraries):
169 """Add additional <uses-library> tags with android:required=true.
170
171 Args:
172 doc: The XML document. May be modified by this function.
173 new_uses_libraries: The names of libraries to be added by this function.
174 Raises:
175 RuntimeError: Invalid manifest
176 """
177
178 manifest = parse_manifest(doc)
179 elems = get_children_with_tag(manifest, 'application')
180 application = elems[0] if len(elems) == 1 else None
181 if len(elems) > 1:
182 raise RuntimeError('found multiple <application> tags')
183 elif not elems:
184 application = doc.createElement('application')
185 indent = get_indent(manifest.firstChild, 1)
186 first = manifest.firstChild
187 manifest.insertBefore(doc.createTextNode(indent), first)
188 manifest.insertBefore(application, first)
189
190 indent = get_indent(application.firstChild, 2)
191
192 last = application.lastChild
193 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
194 last = None
195
196 for name in new_uses_libraries:
197 if find_child_with_attribute(application, 'uses-library', android_ns,
198 'name', name) is not None:
199 # If the uses-library tag of the same 'name' attribute value exists,
200 # respect it.
201 continue
202
203 ul = doc.createElement('uses-library')
204 ul.setAttributeNS(android_ns, 'android:name', name)
205 ul.setAttributeNS(android_ns, 'android:required', 'true')
206
207 application.insertBefore(doc.createTextNode(indent), last)
208 application.insertBefore(ul, last)
209
210 # align the closing tag with the opening tag if it's not
211 # indented
212 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
213 indent = get_indent(application.previousSibling, 1)
214 application.appendChild(doc.createTextNode(indent))
215
216
Colin Cross8bb10e82018-06-07 16:46:02 -0700217def write_xml(f, doc):
218 f.write('<?xml version="1.0" encoding="utf-8"?>\n')
219 for node in doc.childNodes:
220 f.write(node.toxml(encoding='utf-8') + '\n')
221
222
223def main():
224 """Program entry point."""
225 try:
226 args = parse_args()
227
228 doc = minidom.parse(args.input)
229
230 ensure_manifest_android_ns(doc)
231
232 if args.min_sdk_version:
233 raise_min_sdk_version(doc, args.min_sdk_version)
234
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900235 if args.uses_libraries:
236 add_uses_libraries(doc, args.uses_libraries)
237
Colin Cross8bb10e82018-06-07 16:46:02 -0700238 with open(args.output, 'wb') as f:
239 write_xml(f, doc)
240
241 # pylint: disable=broad-except
242 except Exception as err:
243 print('error: ' + str(err), file=sys.stderr)
244 sys.exit(-1)
245
246if __name__ == '__main__':
247 main()