1#!/usr/bin/env python
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"""Utility functions for VNDK snapshot."""
18
19import glob
20import os
21import re
22import subprocess
23import sys
24
25# Global Keys
26#   All paths are relative to install_dir: prebuilts/vndk/v{version}
27COMMON_DIR_NAME = 'common'
28COMMON_DIR_PATH = COMMON_DIR_NAME
29ANDROID_MK_PATH = os.path.join(COMMON_DIR_PATH, 'Android.mk')
30CONFIG_DIR_PATH_PATTERN = '*/configs'
31MANIFEST_FILE_NAME = 'manifest.xml'
32MODULE_PATHS_FILE_NAME = 'module_paths.txt'
33NOTICE_FILES_DIR_NAME = 'NOTICE_FILES'
34NOTICE_FILES_DIR_PATH = os.path.join(COMMON_DIR_PATH, NOTICE_FILES_DIR_NAME)
35
36
37def get_android_build_top():
38    ANDROID_BUILD_TOP = os.getenv('ANDROID_BUILD_TOP')
39    if not ANDROID_BUILD_TOP:
40        print('Error: Missing ANDROID_BUILD_TOP env variable. Please run '
41              '\'. build/envsetup.sh; lunch <build target>\'. Exiting script.')
42        sys.exit(1)
43    return ANDROID_BUILD_TOP
44
45
46def join_realpath(root, *args):
47    return os.path.realpath(os.path.join(root, *args))
48
49
50def _get_dir_from_env(env_var, default):
51    return os.path.realpath(os.getenv(env_var, default))
52
53
54def get_out_dir(android_build_top):
55    return _get_dir_from_env('OUT_DIR', join_realpath(android_build_top,
56                                                      'out'))
57
58
59def get_dist_dir(out_dir):
60    return _get_dir_from_env('DIST_DIR', join_realpath(out_dir, 'dist'))
61
62
63def get_snapshot_variants(install_dir):
64    """Returns a list of VNDK snapshot variants under install_dir.
65
66    Args:
67      install_dir: string, absolute path of prebuilts/vndk/v{version}
68    """
69    variants = []
70    for file in glob.glob('{}/*'.format(install_dir)):
71        basename = os.path.basename(file)
72        if os.path.isdir(file) and basename != COMMON_DIR_NAME:
73            variants.append(basename)
74    return variants
75
76
77def arch_from_path(path):
78    """Extracts arch of prebuilts from path relative to install_dir.
79
80    Args:
81      path: string, path relative to prebuilts/vndk/v{version}
82
83    Returns:
84      string, arch of prebuilt (e.g., 'arm' or 'arm64' or 'x86' or 'x86_64')
85    """
86    return path.split('/')[1].split('-')[1]
87
88
89def variant_from_path(path):
90    """Extracts VNDK snapshot variant from path relative to install_dir.
91
92    Args:
93      path: string, path relative to prebuilts/vndk/v{version}
94
95    Returns:
96      string, VNDK snapshot variant (e.g. 'arm64')
97    """
98    return path.split('/')[0]
99
100
101def find(path, names):
102    """Returns a list of files in a directory that match the given names.
103
104    Args:
105      path: string, absolute path of directory from which to find files
106      names: list of strings, names of the files to find
107    """
108    found = []
109    for root, _, files in os.walk(path):
110        for file_name in sorted(files):
111            if file_name in names:
112                abspath = os.path.abspath(os.path.join(root, file_name))
113                rel_to_root = abspath.replace(os.path.abspath(path), '')
114                found.append(rel_to_root[1:])  # strip leading /
115    return found
116
117
118def fetch_artifact(branch, build, pattern, destination='.'):
119    """Fetches build artifacts from Android Build server.
120
121    Args:
122      branch: string, branch to pull build artifacts from
123      build: string, build number to pull build artifacts from
124      pattern: string, pattern of build artifact file name
125      destination: string, destination to pull build artifact to
126    """
127    fetch_artifact_path = '/google/data/ro/projects/android/fetch_artifact'
128    cmd = [
129        fetch_artifact_path, '--branch', branch, '--target=vndk', '--bid',
130        build, pattern, destination
131    ]
132    print 'Running `{}`'.format(' '.join(cmd))
133    subprocess.check_call(cmd)
134