Best Python code snippet using autotest_python
build.py
Source:build.py  
1#!/usr/bin/env python2#3# Copyright (C) 2017 The Android Open Source Project4#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 at8#9#      http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# 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 and15# limitations under the License.16#17"""Builds binutils."""18from __future__ import print_function19import argparse20import logging21import multiprocessing22import os23import shutil24import site25import subprocess26THIS_DIR = os.path.realpath(os.path.dirname(__file__))27site.addsitedir(os.path.join(THIS_DIR, '../../ndk'))28# pylint: disable=wrong-import-position29import ndk.abis  # pylint: disable=import-error30import ndk.ext.shutil  # pylint: disable=import-error31import ndk.paths  # pylint: disable=import-error32import ndk.timer  # pylint: disable=import-error33# pylint: enable=wrong-import-position34def logger():35    """Returns the module level logger."""36    return logging.getLogger(__name__)37def makedirs(path):38    """os.makedirs with logging."""39    logger().info('makedirs ' + path)40    os.makedirs(path)41def rmtree(path):42    """shutil.rmtree with logging."""43    logger().info('rmtree ' + path)44    shutil.rmtree(path)45def chdir(path):46    """os.chdir with logging."""47    logger().info('chdir ' + path)48    os.chdir(path)49def check_call(cmd, *args, **kwargs):50    """subprocess.check_call with logging."""51    logger().info('check_call %s', subprocess.list2cmdline(cmd))52    subprocess.check_call(cmd, *args, **kwargs)53def configure(arch, host, install_dir, src_dir):54    """Configures binutils."""55    is_windows = host in ('win', 'win64')56    configure_host = {57        'darwin': 'x86_64-apple-darwin',58        'linux': 'x86_64-linux-gnu',59        'win': 'i686-w64-mingw32',60        'win64': 'x86_64-w64-mingw32',61    }[host]62    sysroot = ndk.paths.sysroot_path(ndk.abis.arch_to_toolchain(arch))63    configure_args = [64        os.path.join(src_dir, 'configure'),65        '--target={}'.format(ndk.abis.arch_to_triple(arch)),66        '--host={}'.format(configure_host),67        '--enable-initfini-array',68        '--enable-plugins',69        '--with-sysroot={}'.format(sysroot),70        '--prefix={}'.format(install_dir),71    ]72    if arch == 'arm64':73        configure_args.append('--enable-fix-cortex-a53-835769')74        configure_args.append('--enable-gold')75    else:76        # Gold for aarch64 currently emits broken debug info.77        # https://issuetracker.google.com/7083824778        configure_args.append('--enable-gold=default')79    if not is_windows:80        # Multithreaded linking is implemented with pthreads, which we81        # historically couldn't use on Windows.82        # TODO: Try enabling this now that we have winpthreads in mingw.83        configure_args.append('--enable-threads')84    env = {}85    m32 = False86    if host == 'darwin':87        toolchain = ndk.paths.android_path(88            'prebuilts/gcc/darwin-x86/host/i686-apple-darwin-4.2.1')89        toolchain_prefix = 'i686-apple-darwin10'90        env['MACOSX_DEPLOYMENT_TARGET'] = '10.6'91    elif host == 'linux':92        toolchain = ndk.paths.android_path(93            'prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8')94        toolchain_prefix = 'x86_64-linux'95    elif is_windows:96        toolchain = ndk.paths.android_path(97            'prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8')98        toolchain_prefix = 'x86_64-w64-mingw32'99        if host == 'win':100            m32 = True101    else:102        raise NotImplementedError103    cc = os.path.join(toolchain, 'bin', '{}-gcc'.format(toolchain_prefix))104    cxx = os.path.join(toolchain, 'bin', '{}-g++'.format(toolchain_prefix))105    # Our darwin prebuilts are gcc *only*. No binutils.106    if host == 'darwin':107        ar = 'ar'108        strip = 'strip'109    else:110        ar = os.path.join(toolchain, 'bin', '{}-ar'.format(toolchain_prefix))111        strip = os.path.join(112            toolchain, 'bin', '{}-strip'.format(toolchain_prefix))113    env['AR'] = ar114    env['CC'] = cc115    env['CXX'] = cxx116    env['STRIP'] = strip117    if m32:118        env['CFLAGS'] = '-m32'119        env['CXXFLAGS'] = '-m32'120        env['LDFLAGS'] = '-m32'121    else:122        env['CFLAGS'] = '-m64'123        env['CXXFLAGS'] = '-m64'124        env['LDFLAGS'] = '-m64'125    env_args = ['env'] + ['='.join([k, v]) for k, v in env.items()]126    check_call(env_args + configure_args)127def build(jobs):128    """Builds binutils."""129    check_call(['make', '-j', str(jobs)])130def install(jobs):131    """Installs binutils."""132    check_call(['make', 'install-strip', '-j', str(jobs)])133def dist(dist_dir, base_dir, package_name):134    """Packages binutils for distribution."""135    has_pbzip2 = ndk.ext.shutil.which('pbzip2') is not None136    if has_pbzip2:137        compress_arg = '--use-compress-prog=pbzip2'138    else:139        compress_arg = '-j'140    package_path = os.path.join(dist_dir, package_name + '.tar.bz2')141    cmd = [142        'tar', compress_arg, '-cf', package_path, '-C', base_dir, package_name,143    ]144    subprocess.check_call(cmd)145def parse_args():146    """Parse command line arguments."""147    parser = argparse.ArgumentParser()148    parser.add_argument(149        '--arch', choices=ndk.abis.ALL_ARCHITECTURES, required=True)150    parser.add_argument(151        '--host', choices=('darwin', 'linux', 'win', 'win64'), required=True)152    parser.add_argument(153        '--clean', action='store_true',154        help='Clean the out directory before building.')155    parser.add_argument(156        '-j', '--jobs', type=int, default=multiprocessing.cpu_count(),157        help='Number of jobs to use when building.')158    return parser.parse_args()159def main():160    """Program entry point."""161    args = parse_args()162    logging.basicConfig(level=logging.INFO)163    total_timer = ndk.timer.Timer()164    total_timer.start()165    out_dir = ndk.paths.get_out_dir()166    dist_dir = ndk.paths.get_dist_dir(out_dir)167    base_build_dir = os.path.join(168        out_dir, 'binutils', args.host, args.arch)169    build_dir = os.path.join(base_build_dir, 'build')170    package_name = 'binutils-{}-{}'.format(args.arch, args.host)171    install_dir = os.path.join(base_build_dir, 'install', package_name)172    binutils_path = os.path.join(THIS_DIR, 'binutils-2.27')173    did_clean = False174    clean_timer = ndk.timer.Timer()175    if args.clean and os.path.exists(build_dir):176        did_clean = True177        with clean_timer:178            rmtree(build_dir)179    if not os.path.exists(build_dir):180        makedirs(build_dir)181    orig_dir = os.getcwd()182    chdir(build_dir)183    try:184        configure_timer = ndk.timer.Timer()185        with configure_timer:186            configure(args.arch, args.host, install_dir, binutils_path)187        build_timer = ndk.timer.Timer()188        with build_timer:189            build(args.jobs)190        install_timer = ndk.timer.Timer()191        with install_timer:192            install(args.jobs)193    finally:194        chdir(orig_dir)195    package_timer = ndk.timer.Timer()196    with package_timer:197        dist(dist_dir, os.path.dirname(install_dir), package_name)198    total_timer.finish()199    if did_clean:200        print('Clean: {}'.format(clean_timer.duration))201    print('Configure: {}'.format(configure_timer.duration))202    print('Build: {}'.format(build_timer.duration))203    print('Install: {}'.format(install_timer.duration))204    print('Package: {}'.format(package_timer.duration))205    print('Total: {}'.format(total_timer.duration))206if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
