xref: /aosp_15_r20/external/cronet/build/android/gyp/system_image_apks.py (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1#!/usr/bin/env python3
2
3# Copyright 2022 The Chromium Authors
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6"""Generates APKs for use on system images."""
7
8import argparse
9import os
10import pathlib
11import tempfile
12import shutil
13import sys
14import zipfile
15
16_DIR_SOURCE_ROOT = str(pathlib.Path(__file__).parents[2])
17sys.path.append(os.path.join(_DIR_SOURCE_ROOT, 'build', 'android', 'gyp'))
18from util import build_utils
19
20
21def main():
22  parser = argparse.ArgumentParser()
23  parser.add_argument('--input', required=True, help='Input path')
24  parser.add_argument('--output', required=True, help='Output path')
25  parser.add_argument('--bundle-wrapper', help='APK operations script path')
26  parser.add_argument('--fuse-apk',
27                      help='Create single .apk rather than using apk splits',
28                      action='store_true')
29  args = parser.parse_args()
30
31  if not args.bundle_wrapper:
32    shutil.copyfile(args.input, args.output)
33    return
34
35  with tempfile.NamedTemporaryFile(suffix='.apks') as tmp_file:
36    cmd = [
37        args.bundle_wrapper, 'build-bundle-apks', '--output-apks', tmp_file.name
38    ]
39    cmd += ['--build-mode', 'system' if args.fuse_apk else 'system_apks']
40
41    # Creates a .apks zip file that contains the system image APK(s).
42    build_utils.CheckOutput(cmd)
43
44    if args.fuse_apk:
45      with zipfile.ZipFile(tmp_file.name) as z:
46        pathlib.Path(args.output).write_bytes(z.read('system/system.apk'))
47      return
48
49    # Rename .apk files and remove toc.pb to make it clear that system apks
50    # should not be installed via bundletool.
51    with zipfile.ZipFile(tmp_file.name) as z_input, \
52        zipfile.ZipFile(args.output, 'w') as z_output:
53      for info in z_input.infolist():
54        if info.filename.endswith('.apk'):
55          data = z_input.read(info)
56          info.filename = (info.filename.replace('splits/',
57                                                 '').replace('-master', ''))
58          z_output.writestr(info, data)
59
60
61if __name__ == '__main__':
62  sys.exit(main())
63