xref: /aosp_15_r20/build/soong/scripts/manifest_fixer.py (revision 333d2b3687b3a337dbcca9d65000bca186795e39)
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
19import argparse
20import sys
21from xml.dom import minidom
22
23
24from manifest import *
25
26def parse_args():
27  """Parse commandline arguments."""
28
29  parser = argparse.ArgumentParser()
30  parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
31                      help='specify minSdkVersion used by the build system')
32  parser.add_argument('--replaceMaxSdkVersionPlaceholder', default='', dest='max_sdk_version',
33                      help='specify maxSdkVersion used by the build system')
34  parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
35                      help='specify targetSdkVersion used by the build system')
36  parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
37                      help='raise the minimum sdk version in the manifest if necessary')
38  parser.add_argument('--library', dest='library', action='store_true',
39                      help='manifest is for a static library')
40  parser.add_argument('--uses-library', dest='uses_libraries', action='append',
41                      help='specify additional <uses-library> tag to add. android:required is set to true')
42  parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
43                      help='specify additional <uses-library> tag to add. android:required is set to false')
44  parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
45                      help='manifest is for a package built against the platform')
46  parser.add_argument('--logging-parent', dest='logging_parent', default='',
47                      help=('specify logging parent as an additional <meta-data> tag. '
48                            'This value is ignored if the logging_parent meta-data tag is present.'))
49  parser.add_argument('--use-embedded-dex', dest='use_embedded_dex', action='store_true',
50                      help=('specify if the app wants to use embedded dex and avoid extracted,'
51                            'locally compiled code. Must not conflict if already declared '
52                            'in the manifest.'))
53  parser.add_argument('--extract-native-libs', dest='extract_native_libs',
54                      default=None, type=lambda x: (str(x).lower() == 'true'),
55                      help=('specify if the app wants to use embedded native libraries. Must not conflict '
56                            'if already declared in the manifest.'))
57  parser.add_argument('--has-no-code', dest='has_no_code', action='store_true',
58                      help=('adds hasCode="false" attribute to application. Ignored if application elem '
59                            'already has a hasCode attribute.'))
60  parser.add_argument('--test-only', dest='test_only', action='store_true',
61                      help=('adds testOnly="true" attribute to application. Assign true value if application elem '
62                            'already has a testOnly attribute.'))
63  parser.add_argument('--override-placeholder-version', dest='new_version',
64                      help='Overrides the versionCode if it\'s set to the placeholder value of 0')
65  parser.add_argument('input', help='input AndroidManifest.xml file')
66  parser.add_argument('output', help='output AndroidManifest.xml file')
67  return parser.parse_args()
68
69
70def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
71  """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
72
73  Args:
74    doc: The XML document.  May be modified by this function.
75    min_sdk_version: The requested minSdkVersion attribute.
76    target_sdk_version: The requested targetSdkVersion attribute.
77    library: True if the manifest is for a library.
78  Raises:
79    RuntimeError: invalid manifest
80  """
81
82  manifest = parse_manifest(doc)
83
84  for uses_sdk in get_or_create_uses_sdks(doc, manifest):
85    # Get or insert the minSdkVersion attribute.  If it is already present, make
86    # sure it as least the requested value.
87    min_attr = uses_sdk.getAttributeNodeNS(android_ns, 'minSdkVersion')
88    if min_attr is None:
89      min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
90      min_attr.value = min_sdk_version
91      uses_sdk.setAttributeNode(min_attr)
92    else:
93      if compare_version_gt(min_sdk_version, min_attr.value):
94        min_attr.value = min_sdk_version
95
96    # Insert the targetSdkVersion attribute if it is missing.  If it is already
97    # present leave it as is.
98    target_attr = uses_sdk.getAttributeNodeNS(android_ns, 'targetSdkVersion')
99    if target_attr is None:
100      target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
101      if library:
102        # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
103        # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
104        # is empty.  Set it to something low so that it will be overridden by the
105        # main manifest, but high enough that it doesn't cause implicit
106        # permissions grants.
107        target_attr.value = '16'
108      else:
109        target_attr.value = target_sdk_version
110      uses_sdk.setAttributeNode(target_attr)
111
112
113def add_logging_parent(doc, logging_parent_value):
114  """Add logging parent as an additional <meta-data> tag.
115
116  Args:
117    doc: The XML document. May be modified by this function.
118    logging_parent_value: A string representing the logging
119      parent value.
120  Raises:
121    RuntimeError: Invalid manifest
122  """
123  manifest = parse_manifest(doc)
124
125  logging_parent_key = 'android.content.pm.LOGGING_PARENT'
126  for application in get_or_create_applications(doc, manifest):
127    indent = get_indent(application.firstChild, 2)
128
129    last = application.lastChild
130    if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
131      last = None
132
133    if not find_child_with_attribute(application, 'meta-data', android_ns,
134                                     'name', logging_parent_key):
135      ul = doc.createElement('meta-data')
136      ul.setAttributeNS(android_ns, 'android:name', logging_parent_key)
137      ul.setAttributeNS(android_ns, 'android:value', logging_parent_value)
138      application.insertBefore(doc.createTextNode(indent), last)
139      application.insertBefore(ul, last)
140      last = application.lastChild
141
142    # align the closing tag with the opening tag if it's not
143    # indented
144    if last and last.nodeType != minidom.Node.TEXT_NODE:
145      indent = get_indent(application.previousSibling, 1)
146      application.appendChild(doc.createTextNode(indent))
147
148
149def add_uses_libraries(doc, new_uses_libraries, required):
150  """Add additional <uses-library> tags
151
152  Args:
153    doc: The XML document. May be modified by this function.
154    new_uses_libraries: The names of libraries to be added by this function.
155    required: The value of android:required attribute. Can be true or false.
156  Raises:
157    RuntimeError: Invalid manifest
158  """
159
160  manifest = parse_manifest(doc)
161  for application in get_or_create_applications(doc, manifest):
162    indent = get_indent(application.firstChild, 2)
163
164    last = application.lastChild
165    if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
166      last = None
167
168    for name in new_uses_libraries:
169      if find_child_with_attribute(application, 'uses-library', android_ns,
170                                   'name', name) is not None:
171        # If the uses-library tag of the same 'name' attribute value exists,
172        # respect it.
173        continue
174
175      ul = doc.createElement('uses-library')
176      ul.setAttributeNS(android_ns, 'android:name', name)
177      ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
178
179      application.insertBefore(doc.createTextNode(indent), last)
180      application.insertBefore(ul, last)
181
182    # align the closing tag with the opening tag if it's not
183    # indented
184    if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
185      indent = get_indent(application.previousSibling, 1)
186      application.appendChild(doc.createTextNode(indent))
187
188
189def add_uses_non_sdk_api(doc):
190  """Add android:usesNonSdkApi=true attribute to <application>.
191
192  Args:
193    doc: The XML document. May be modified by this function.
194  Raises:
195    RuntimeError: Invalid manifest
196  """
197
198  manifest = parse_manifest(doc)
199  for application in get_or_create_applications(doc, manifest):
200    attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
201    if attr is None:
202      attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
203      attr.value = 'true'
204      application.setAttributeNode(attr)
205
206
207def add_use_embedded_dex(doc):
208  manifest = parse_manifest(doc)
209  for application in get_or_create_applications(doc, manifest):
210    attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
211    if attr is None:
212      attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
213      attr.value = 'true'
214      application.setAttributeNode(attr)
215    elif attr.value != 'true':
216      raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
217
218
219def add_extract_native_libs(doc, extract_native_libs):
220  manifest = parse_manifest(doc)
221  for application in get_or_create_applications(doc, manifest):
222    value = str(extract_native_libs).lower()
223    attr = application.getAttributeNodeNS(android_ns, 'extractNativeLibs')
224    if attr is None:
225      attr = doc.createAttributeNS(android_ns, 'android:extractNativeLibs')
226      attr.value = value
227      application.setAttributeNode(attr)
228    elif attr.value != value:
229      raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
230                         (attr.value, value))
231
232
233def set_has_code_to_false(doc):
234  manifest = parse_manifest(doc)
235  for application in get_or_create_applications(doc, manifest):
236    attr = application.getAttributeNodeNS(android_ns, 'hasCode')
237    if attr is not None:
238      # Do nothing if the application already has a hasCode attribute.
239      continue
240    attr = doc.createAttributeNS(android_ns, 'android:hasCode')
241    attr.value = 'false'
242    application.setAttributeNode(attr)
243
244
245def set_test_only_flag_to_true(doc):
246  manifest = parse_manifest(doc)
247  for application in get_or_create_applications(doc, manifest):
248    attr = application.getAttributeNodeNS(android_ns, 'testOnly')
249    if attr is not None:
250      # Do nothing If the application already has a testOnly attribute.
251      continue
252    attr = doc.createAttributeNS(android_ns, 'android:testOnly')
253    attr.value = 'true'
254    application.setAttributeNode(attr)
255
256
257def set_max_sdk_version(doc, max_sdk_version):
258  """Replace the maxSdkVersion attribute value for permission and
259  uses-permission tags if the value was originally set to 'current'.
260  Used for cts test cases where the maxSdkVersion should equal to
261  Build.SDK_INT.
262
263  Args:
264    doc: The XML document.  May be modified by this function.
265    max_sdk_version: The requested maxSdkVersion attribute.
266  """
267  manifest = parse_manifest(doc)
268  for tag in ['permission', 'uses-permission']:
269    children = get_children_with_tag(manifest, tag)
270    for child in children:
271      max_attr = child.getAttributeNodeNS(android_ns, 'maxSdkVersion')
272      if max_attr and max_attr.value == 'current':
273        max_attr.value = max_sdk_version
274
275
276def override_placeholder_version(doc, new_version):
277  """Replace the versionCode attribute value if it\'s currently
278  set to the placeholder version of 0.
279
280  Args:
281    doc: The XML document.  May be modified by this function.
282    new_version: The new version to set if versionCode is equal to 0.
283  """
284  manifest = parse_manifest(doc)
285  version = manifest.getAttribute("android:versionCode")
286  if version == '0':
287    manifest.setAttribute("android:versionCode", new_version)
288
289
290def main():
291  """Program entry point."""
292  try:
293    args = parse_args()
294
295    doc = minidom.parse(args.input)
296
297    ensure_manifest_android_ns(doc)
298
299    if args.raise_min_sdk_version:
300      raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
301
302    if args.max_sdk_version:
303      set_max_sdk_version(doc, args.max_sdk_version)
304
305    if args.uses_libraries:
306      add_uses_libraries(doc, args.uses_libraries, True)
307
308    if args.optional_uses_libraries:
309      add_uses_libraries(doc, args.optional_uses_libraries, False)
310
311    if args.uses_non_sdk_api:
312      add_uses_non_sdk_api(doc)
313
314    if args.logging_parent:
315      add_logging_parent(doc, args.logging_parent)
316
317    if args.use_embedded_dex:
318      add_use_embedded_dex(doc)
319
320    if args.has_no_code:
321      set_has_code_to_false(doc)
322
323    if args.test_only:
324      set_test_only_flag_to_true(doc)
325
326    if args.extract_native_libs is not None:
327      add_extract_native_libs(doc, args.extract_native_libs)
328
329    if args.new_version:
330      override_placeholder_version(doc, args.new_version)
331
332    with open(args.output, 'w') as f:
333      write_xml(f, doc)
334
335  # pylint: disable=broad-except
336  except Exception as err:
337    print('error: ' + str(err), file=sys.stderr)
338    sys.exit(-1)
339
340
341if __name__ == '__main__':
342  main()
343