Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
121 lines (106 loc) · 6.16 KB
/
Copy pathbuild.py
File metadata and controls
121 lines (106 loc) · 6.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/python3
# -------------------------------------------------------------------------
# This file is part of the MindStudio project.
# Copyright (c) 2025 Huawei Technologies Co.,Ltd.
#
# MindStudio is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
# -------------------------------------------------------------------------
import argparse
import json
import logging
import multiprocessing
import os
import subprocess
import sys
import traceback
from pathlib import Path
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class BuildManager:
"""
统一构建管理:依赖拉取 → CMake 配置 → 并行编译 → 安装 / 测试。
用法:
python build.py 完整构建(拉取依赖 + Release 编译)
python build.py local 本地构建(跳过依赖拉取, Release 编译)
python build.py test 单元测试(拉取依赖 + Debug 编译 + 执行测试)
python build.py test local 单元测试(跳过依赖拉取, Debug 编译 + 执行测试)
python build.py -r <revision> 指定依赖的内部源码仓的 Git 分支/标签/commit
参数说明:
- 参数: command : 构建动作: 为空时为全构建, local 为跳过依赖下载, test 为运行单元测试。
- 参数: -r, --revision : 指定 Git 修订版本或标签用于依赖检出。
"""
def __init__(self):
self.project_root = Path(__file__).resolve().parent
self.build_jobs = multiprocessing.cpu_count()
argument_parser = argparse.ArgumentParser(description='Build the project and optionally run tests.')
argument_parser.add_argument('command', nargs='*', default=[],
choices=[[], 'local', 'test'],
help='Build action: omit for full build, "local" to skip dependency download, "test" to run unit tests')
argument_parser.add_argument('-r', '--revision',
help='Specify Git revision for internal dependent repo.')
# 支持解析版本号参数但实际不使用,防止因参数多余导致构建失败
argument_parser.add_argument('--build-version', type=str, default=None, help='Build version for run/exe/dmg packages')
argument_parser.add_argument('--whl-version', type=str, default=None, help='WHL version for Python wheel packages')
argument_parser.add_argument('-e', '--extra', metavar='KEY=VALUE', action='append', default=[],
help='Extra build options in KEY=VALUE format, can be specified multiple times')
self.parsed_arguments = argument_parser.parse_args()
def _execute_command(self, command_sequence, timeout_seconds=36000, cwd=None, env=None,
capture_stdout=False):
logging.info("Running: %s", " ".join(command_sequence))
return subprocess.run(command_sequence, timeout=timeout_seconds, check=True, cwd=cwd, env=env,
stdout=subprocess.PIPE if capture_stdout else None, text=True)
def _check_ut_line_coverage(self):
result = self._execute_command(
["bash", str(self.project_root / "test/generate_coverage.sh"), "--check"],
capture_stdout=True)
summary = json.loads(result.stdout)
total, covered = summary["line_total"], summary["line_covered"]
if (type(total) is not int or type(covered) is not int
or total <= 0 or not 0 <= covered <= total):
raise RuntimeError("Invalid csrc UT line coverage data")
logging.info("csrc UT line coverage: %.2f%% (%d/%d), required: 80%%",
covered * 100.0 / total, covered, total)
if covered * 100 < total * 80:
raise RuntimeError("csrc UT line coverage is below the required 80%")
def run(self):
os.chdir(self.project_root)
# 在非 local 场景下按需更新依赖;在 local 场景下仅使用本地已有代码,不更新依赖。
if 'local' not in self.parsed_arguments.command:
from download_dependencies import DependencyManager
DependencyManager(self.parsed_arguments).run()
if 'test' in self.parsed_arguments.command:
# -------------------- 单元测试 --------------------
unit_test_build_dir = self.project_root / "build_ut"
unit_test_build_dir.mkdir(exist_ok=True)
os.chdir(unit_test_build_dir)
self._execute_command(["cmake", "..", "-DBUILD_TESTS=ON", "-DCMAKE_BUILD_TYPE=Debug","-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"])
self._execute_command(["make", "-j", str(self.build_jobs), "injectionTest"])
# 清理历史计数,确保覆盖率只反映本次测试结果。
for counter in unit_test_build_dir.rglob("*.gcda"):
counter.unlink()
test_dir = unit_test_build_dir / "test"
os.environ['LD_LIBRARY_PATH'] = str(test_dir / "stub") + os.pathsep + os.environ.get('LD_LIBRARY_PATH', '')
self._execute_command(["./injectionTest"], cwd=str(test_dir))
self._check_ut_line_coverage()
else:
# -------------------- 产品构建 --------------------
product_build_dir = self.project_root / "build"
product_build_dir.mkdir(exist_ok=True)
os.chdir(product_build_dir)
self._execute_command(["cmake", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON", ".."])
self._execute_command(["make", "-j", str(self.build_jobs)])
self._execute_command(["make", "install"])
if __name__ == "__main__":
try:
BuildManager().run()
except Exception:
logging.error(f"Unexpected error: {traceback.format_exc()}")
sys.exit(1)