• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3# Copyright (C) 2017 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"""Installs VNDK snapshot under prebuilts/vndk/v{version}."""
18
19import argparse
20import glob
21import logging
22import os
23import re
24import shutil
25import subprocess
26import sys
27import tempfile
28import textwrap
29
30import utils
31
32from check_gpl_license import GPLChecker
33from gen_buildfiles import GenBuildFile
34
35ANDROID_BUILD_TOP = utils.get_android_build_top()
36PREBUILTS_VNDK_DIR = utils.join_realpath(ANDROID_BUILD_TOP, 'prebuilts/vndk')
37
38
39def start_branch(build):
40    branch_name = 'update-' + (build or 'local')
41    logging.info('Creating branch {branch} in {dir}'.format(
42        branch=branch_name, dir=os.getcwd()))
43    utils.check_call(['repo', 'start', branch_name, '.'])
44
45
46def remove_old_snapshot(install_dir):
47    logging.info('Removing any old files in {}'.format(install_dir))
48    for file in glob.glob('{}/*'.format(install_dir)):
49        try:
50            if os.path.isfile(file):
51                os.unlink(file)
52            elif os.path.isdir(file):
53                shutil.rmtree(file)
54        except Exception as error:
55            logging.error('Error: {}'.format(error))
56            sys.exit(1)
57
58
59def install_snapshot(branch, build, local_dir, install_dir, temp_artifact_dir):
60    """Installs VNDK snapshot build artifacts to prebuilts/vndk/v{version}.
61
62    1) Fetch build artifacts from Android Build server or from local_dir
63    2) Unzip build artifacts
64
65    Args:
66      branch: string or None, branch name of build artifacts
67      build: string or None, build number of build artifacts
68      local_dir: string or None, local dir to pull artifacts from
69      install_dir: string, directory to install VNDK snapshot
70      temp_artifact_dir: string, temp directory to hold build artifacts fetched
71        from Android Build server. For 'local' option, is set to None.
72    """
73    artifact_pattern = 'android-vndk-*.zip'
74
75    if branch and build:
76        artifact_dir = temp_artifact_dir
77        os.chdir(temp_artifact_dir)
78        logging.info('Fetching {pattern} from {branch} (bid: {build})'.format(
79            pattern=artifact_pattern, branch=branch, build=build))
80        utils.fetch_artifact(branch, build, artifact_pattern)
81
82        manifest_pattern = 'manifest_{}.xml'.format(build)
83        logging.info('Fetching {file} from {branch} (bid: {build})'.format(
84            file=manifest_pattern, branch=branch, build=build))
85        utils.fetch_artifact(branch, build, manifest_pattern,
86                             utils.MANIFEST_FILE_NAME)
87
88        os.chdir(install_dir)
89    elif local_dir:
90        logging.info('Fetching local VNDK snapshot from {}'.format(local_dir))
91        artifact_dir = local_dir
92
93    artifacts = glob.glob(os.path.join(artifact_dir, artifact_pattern))
94    for artifact in artifacts:
95        logging.info('Unzipping VNDK snapshot: {}'.format(artifact))
96        utils.check_call(['unzip', '-qn', artifact, '-d', install_dir])
97
98
99def gather_notice_files(install_dir):
100    """Gathers all NOTICE files to a common NOTICE_FILES directory."""
101
102    common_notices_dir = utils.NOTICE_FILES_DIR_PATH
103    logging.info('Creating {} directory to gather all NOTICE files...'.format(
104        common_notices_dir))
105    os.makedirs(common_notices_dir)
106    for arch in utils.get_snapshot_archs(install_dir):
107        notices_dir_per_arch = os.path.join(arch, utils.NOTICE_FILES_DIR_NAME)
108        if os.path.isdir(notices_dir_per_arch):
109            for notice_file in glob.glob(
110                    '{}/*.txt'.format(notices_dir_per_arch)):
111                if not os.path.isfile(
112                        os.path.join(common_notices_dir,
113                                     os.path.basename(notice_file))):
114                    shutil.copy(notice_file, common_notices_dir)
115            shutil.rmtree(notices_dir_per_arch)
116
117
118def post_processe_files_if_needed(vndk_version):
119    """Renames vndkcore.libraries.txt and vndksp.libraries.txt
120    files to have version suffix.
121    Create empty vndkproduct.libraries.txt file if not exist.
122
123    Args:
124      vndk_version: int, version of VNDK snapshot
125    """
126    def add_version_suffix(file_name):
127        logging.info('Rename {} to have version suffix'.format(file_name))
128        target_files = glob.glob(
129            os.path.join(utils.CONFIG_DIR_PATH_PATTERN, file_name))
130        for target_file in target_files:
131            name, ext = os.path.splitext(target_file)
132            os.rename(target_file, name + '.' + str(vndk_version) + ext)
133    def create_empty_file_if_not_exist(file_name):
134        target_dirs = glob.glob(utils.CONFIG_DIR_PATH_PATTERN)
135        for dir in target_dirs:
136            path = os.path.join(dir, file_name)
137            if os.path.isfile(path):
138                continue
139            logging.info('Creating empty file: {}'.format(path))
140            open(path, 'a').close()
141
142    files_to_add_version_suffix = ('vndkcore.libraries.txt',
143                                   'vndkprivate.libraries.txt')
144    files_to_create_if_not_exist = ('vndkproduct.libraries.txt',)
145    for file_to_rename in files_to_add_version_suffix:
146        add_version_suffix(file_to_rename)
147    for file_to_create in files_to_create_if_not_exist:
148        create_empty_file_if_not_exist(file_to_create)
149
150
151def update_buildfiles(buildfile_generator):
152    logging.info('Generating root Android.bp file...')
153    buildfile_generator.generate_root_android_bp()
154
155    logging.info('Generating common/Android.bp file...')
156    buildfile_generator.generate_common_android_bp()
157
158    logging.info('Generating Android.bp files...')
159    buildfile_generator.generate_android_bp()
160
161
162def check_gpl_license(license_checker):
163    try:
164        license_checker.check_gpl_projects()
165    except ValueError as error:
166        logging.error('***CANNOT INSTALL VNDK SNAPSHOT***: {}'.format(error))
167        raise
168
169
170def commit(branch, build, version):
171    logging.info('Making commit...')
172    utils.check_call(['git', 'add', '.'])
173    message = textwrap.dedent("""\
174        Update VNDK snapshot v{version} to build {build}.
175
176        Taken from branch {branch}.""").format(
177        version=version, branch=branch, build=build)
178    utils.check_call(['git', 'commit', '-m', message])
179
180
181def get_args():
182    parser = argparse.ArgumentParser()
183    parser.add_argument(
184        'vndk_version',
185        type=utils.vndk_version_int,
186        help='VNDK snapshot version to install, e.g. "{}".'.format(
187            utils.MINIMUM_VNDK_VERSION))
188    parser.add_argument('-b', '--branch', help='Branch to pull build from.')
189    parser.add_argument('--build', help='Build number to pull.')
190    parser.add_argument(
191        '--local',
192        help=('Fetch local VNDK snapshot artifacts from specified local '
193              'directory instead of Android Build server. '
194              'Example: --local=/path/to/local/dir'))
195    parser.add_argument(
196        '--use-current-branch',
197        action='store_true',
198        help='Perform the update in the current branch. Do not repo start.')
199    parser.add_argument(
200        '--remote',
201        default='aosp',
202        help=('Remote name to fetch and check if the revision of VNDK snapshot '
203              'is included in the source to conform GPL license. default=aosp'))
204    parser.add_argument(
205        '-v',
206        '--verbose',
207        action='count',
208        default=0,
209        help='Increase output verbosity, e.g. "-v", "-vv".')
210    return parser.parse_args()
211
212
213def main():
214    """Program entry point."""
215    args = get_args()
216
217    local = None
218    if args.local:
219        local = os.path.expanduser(args.local)
220
221    if local:
222        if args.build or args.branch:
223            raise ValueError(
224                'When --local option is set, --branch or --build cannot be '
225                'specified.')
226        elif not os.path.isdir(local):
227            raise RuntimeError(
228                'The specified local directory, {}, does not exist.'.format(
229                    local))
230    else:
231        if not (args.build and args.branch):
232            raise ValueError(
233                'Please provide both --branch and --build or set --local '
234                'option.')
235
236    vndk_version = args.vndk_version
237
238    install_dir = os.path.join(PREBUILTS_VNDK_DIR, 'v{}'.format(vndk_version))
239    if not os.path.isdir(install_dir):
240        raise RuntimeError(
241            'The directory for VNDK snapshot version {ver} does not exist.\n'
242            'Please request a new git project for prebuilts/vndk/v{ver} '
243            'before installing new snapshot.'.format(ver=vndk_version))
244
245    utils.set_logging_config(args.verbose)
246
247    os.chdir(install_dir)
248
249    if not args.use_current_branch:
250        start_branch(args.build)
251
252    remove_old_snapshot(install_dir)
253    os.makedirs(utils.COMMON_DIR_PATH)
254
255    temp_artifact_dir = None
256    if not local:
257        temp_artifact_dir = tempfile.mkdtemp()
258
259    try:
260        install_snapshot(args.branch, args.build, local, install_dir,
261                         temp_artifact_dir)
262        gather_notice_files(install_dir)
263        post_processe_files_if_needed(vndk_version)
264
265        buildfile_generator = GenBuildFile(install_dir, vndk_version)
266        update_buildfiles(buildfile_generator)
267
268        if not local:
269            license_checker = GPLChecker(install_dir, ANDROID_BUILD_TOP,
270                                         temp_artifact_dir, args.remote)
271            check_gpl_license(license_checker)
272            logging.info(
273                'Successfully updated VNDK snapshot v{}'.format(vndk_version))
274    except Exception as error:
275        logging.error('FAILED TO INSTALL SNAPSHOT: {}'.format(error))
276        raise
277    finally:
278        if temp_artifact_dir:
279            logging.info(
280                'Deleting temp_artifact_dir: {}'.format(temp_artifact_dir))
281            shutil.rmtree(temp_artifact_dir)
282
283    if not local:
284        commit(args.branch, args.build, vndk_version)
285        logging.info(
286            'Successfully created commit for VNDK snapshot v{}'.format(
287                vndk_version))
288
289    logging.info('Done.')
290
291
292if __name__ == '__main__':
293    main()
294