• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2021 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import os
17import sys
18import subprocess
19import json
20from typing import List
21
22
23def run_command(cmd: List[str], verbose=None):
24    """Execute command `cmd`
25    :param cmd: Command to be executed.
26    :param verbose: Whether echo runtime infomation and output of command `cmd`.
27    :return output: The output of command `cmd`.
28    :return returncode: The return code of command `cmd`.
29    """
30    if verbose:
31        print("Running: {}".format(' '.join(cmd)))
32    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
33    output, _ = p.communicate()
34    if verbose:
35        print(output.decode().rstrip())
36    return output, p.returncode
37
38
39def package_installed(pkg_name: str):
40    """Check whether package `pkg_name` is installed or not.
41    Got package `pkg_name` installation state by executing `dpkg -s pkg_name`.
42    :param pkg_name: Package name to check.
43    :return r: Check result, 0 means installed, non-zero means not installed.
44    """
45    cmd = ['dpkg', '-s', pkg_name]
46    _, r = run_command(cmd)
47    return r
48
49
50def check_build_requried_packages(host_version: str, check: bool=True):
51    """Check whether packages required by build process installed or not.
52    By parsing file `REPO_ROOT/build/scripts/build_package_list.json`.
53    Example content: `{"18.04":{"dep_package":["pkg1","pkg2",...]}, "20.04":{...}, "22.04":{...}}`
54    Currently there are only lists for `Ubuntu 18.04` , `Ubuntu 20.04` and `Ubuntu 22.04`.
55    :param host_version: OS version of the host.
56    :param check: Whether to prompt user of missing package.
57    :return _build_package_list: List of packages required by build process.
58    :return install_package_list: Packages installed.
59    :return uninstall_package_list: Packages missing.
60    """
61    sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'util'))
62    from file_utils import find_top
63    cur_dir = find_top()
64    build_package_json = os.path.join(
65        cur_dir, 'build/scripts/build_package_list.json')
66    with open(build_package_json, 'r') as file:
67        file_json = json.load(file)
68        for _version in file_json.keys():
69            if host_version == _version or host_version.startswith(_version):
70                _build_package_list = file_json["{}".format(
71                    _version)]["dep_package"]
72    uninstall_package_list = []
73    for pkg in _build_package_list:
74        if package_installed(pkg):
75            if check:
76                print("\033[33m {} is not installed. please install it.\033[0m".
77                      format(pkg))
78            uninstall_package_list.append(pkg)
79    install_package_list = list(
80        set(_build_package_list).difference(uninstall_package_list))
81    return _build_package_list, install_package_list, uninstall_package_list
82
83
84def check_os_version():
85    """Check OS type and version.
86    By parsing file `/etc/issue`.
87    :return -1: Retuern -1 if OS is not supported.
88    :return host_os: Host OS type, currently only `Ubuntu` supported.
89    :return host_version: Host OS version, currently only `18.04[.X]`, `20.04[.X]` or `22.04[.X]` supported.
90    """
91    available_os = ('Ubuntu')
92    available_releases = ('18.04', '20.04', '22.04')
93    _os_info, _returncode = run_command(['cat', '/etc/issue'])
94    if _returncode != 0:
95        return -1
96
97    _os_info = _os_info.decode().rstrip().split()
98    host_os = _os_info[0]
99    host_version = _os_info[1]
100    if host_os not in available_os:
101        print("\033[33m OS {} is not supported for ohos build.\033[0m".format(
102            host_os))
103        return -1
104    version_available = False
105    for _version in available_releases:
106        if host_version == _version or host_version.startswith(_version):
107            version_available = True
108            break
109    if not version_available:
110        print("\033[33m OS version {} is not supported for ohos build.\033[0m".
111              format(host_version))
112        print("\033[33m Available OS version are {}.\033[0m".format(
113            ', '.join(available_releases)))
114        return -1
115    return host_os, host_version
116
117
118def main():
119    """Entrance function.
120    :return -1: Return -1 on error.
121    :return 0: Return 0 on success.
122    """
123    check_result = check_os_version()
124
125    if check_result == -1:
126        return -1
127
128    _, _, missing_packages = check_build_requried_packages(
129        check_result[1], check=True)
130
131    if (len(missing_packages) == 0):
132        return 0
133    else:
134        print("\033[31m Missing dependencies, please check!\033[0m")
135        return -1
136
137
138if __name__ == '__main__':
139    sys.exit(main())
140