• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2024 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 json
17import os
18import subprocess
19from threading import Lock
20from pathlib import Path
21
22_indep_args_cache = None
23_cache_lock = Lock()
24
25
26def get_json(file_path):
27    data = {}
28    try:
29        with open(file_path, "r") as f:
30            data = json.load(f)
31    except FileNotFoundError:
32        print(f"can not find file: {file_path}.")
33    except Exception as e:
34        print(f"{file_path}: \n {e}")
35    return data
36
37
38def get_indep_args():
39    """
40    Read the JSON file of independent build parameters and return the parsed data.
41    :return: A dictionary containing independent build parameters (on success) or None (on failure)
42    """
43    global _indep_args_cache
44    if _indep_args_cache:
45        return _indep_args_cache
46
47    src_root = Path(__file__).parent.parent.parent.parent
48    file_path = os.path.join(src_root, "out/hb_args/indepbuildargs.json")
49
50    with _cache_lock:
51        if _indep_args_cache is not None:
52            return _indep_args_cache
53    try:
54        with open(file_path, "r") as file:
55            data = json.load(file)
56            _indep_args_cache = data
57            return data
58    except FileNotFoundError:
59        print(f"File not found: {file_path}")
60    except json.JSONDecodeError as e:
61        print(f"Invalid JSON format in {file_path}: {e}")
62    except PermissionError as e:
63        print(f"Permission denied for {file_path}: {e}")
64    except Exception as e:
65        print(f"Unexpected error reading {file_path}: {e}")
66    return None
67
68
69def get_ninja_args():
70    """
71    Obtain the parameters for the Ninja build system from the independent build parameters.
72    :return: A list of Ninja parameters
73    """
74    input_ninja_args = []
75    data = get_indep_args()
76    input_ninja_args.extend(data["ninja_args"]["argDefault"])
77    if data["keep_ninja_going"]["argDefault"]:
78        input_ninja_args.append("-k100000")
79    return input_ninja_args
80
81
82def get_gn_args():
83    input_gn_args = []
84    data = get_indep_args()
85    if data["gn_args"]["argDefault"]:
86        input_gn_args.extend(data["gn_args"]["argDefault"])
87    return input_gn_args
88
89
90def get_gn_flags():
91    input_gn_flags = []
92    data = get_indep_args()
93    if data["gn_flags"]["argDefault"]:
94        input_gn_flags.extend(data["gn_flags"]["argDefault"])
95    return input_gn_flags
96
97
98def get_build_target():
99    """
100    Obtain the build targets from the independent build parameters.
101    :return: A list of build targets
102    """
103    input_build_target = []
104    data = get_indep_args()
105    if data["build_target"]["argDefault"]:
106        input_build_target.extend(data["build_target"]["argDefault"])
107    return input_build_target
108
109
110def is_enable_ccache():
111    """
112    Check if ccache is enabled.
113    :return: Returns True if ccache is enabled; otherwise, returns False.
114    """
115    return get_indep_args()["ccache"]["argDefault"]
116
117
118def print_ccache_stats():
119    """
120    Print the ccache statistics information.
121    If ccache is enabled, execute the 'ccache -s' command and print the output.
122    If the ccache command is not found or execution fails, print the corresponding error message.
123    """
124    if is_enable_ccache():
125        try:
126            output = subprocess.check_output(["ccache", "-s"], text=True)
127            print("ccache hit statistics:")
128            print(output)
129        except FileNotFoundError:
130            print("Error: ccache command not found")
131        except subprocess.CalledProcessError as e:
132            print(f"Failed to execute ccache command: {e}")
133
134
135def clean_ccache_info():
136    """
137    Clean the ccache statistics information.
138    If ccache is enabled, execute the 'ccache -z' command to reset the ccache statistics.
139    If the ccache command is not found or execution fails, print the corresponding error message.
140    """
141    if is_enable_ccache():
142        try:
143            subprocess.check_output(["ccache", "-z"], text=True)
144        except FileNotFoundError:
145            print("Error: ccache command not found")
146        except subprocess.CalledProcessError as e:
147            print(f"Failed to execute ccache command: {e}")
148