• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# coding=utf-8
3
4#
5# Copyright (c) 2020-2023 Huawei Device Co., Ltd.
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19import os
20import subprocess
21import json
22import stat
23
24FLAGS = os.O_WRONLY | os.O_CREAT | os.O_EXCL
25MODES = stat.S_IWUSR | stat.S_IRUSR
26
27
28def get_source_file_list(path):
29    """
30    获取path路径下源文件路径列表
31    """
32    file_path_list = []
33    file_path_list_append = file_path_list.append
34    for root, dirs, files in os.walk(path):
35        for file_name in files:
36            file_path = os.path.join(root, file_name)
37            _, suffix = os.path.splitext(file_name)
38            if suffix in [".c", ".h", ".cpp"]:
39                file_path_list_append(file_path)
40    return file_path_list
41
42
43def rewrite_source_file(source_path_list: list):
44    """
45    源文件加“//LCOV_EXCL_BR_LINE”
46    """
47    keys = ["if", "while", "switch", "case", "for", "try", "catch"]
48    if not source_path_list:
49        print("no any source file here")
50        return
51
52    print("[**********  Start Rewrite Source File **********]")
53    for path in source_path_list:
54        if not os.path.exists(path) or "test" in path:
55            continue
56        with open(path, "r", encoding="utf-8", errors="ignore") as read_fp:
57            code_lines = read_fp.readlines()
58        source_dir, suffix_name = os.path.splitext(path)
59        if os.path.exists(f"{source_dir}_bk.{suffix_name}"):
60            os.remove(f"{source_dir}_bk.{suffix_name}")
61        with os.fdopen(os.open(f"{source_dir}_bk.{suffix_name}", FLAGS, MODES), 'w') as write_fp:
62            for line in code_lines:
63                for key in keys:
64                    if key in line and line.strip().startswith(key):
65                        write_fp.write(line)
66                        break
67                    elif " //LCOV_EXCL_BR_LINE" not in line and not line.strip().endswith("\\"):
68                        write_fp.write(line.strip("\n").strip("\n\r") + " //LCOV_EXCL_BR_LINE")
69                        write_fp.write("\n")
70                        break
71                    elif key == keys[-1]:
72                        write_fp.write(line)
73                        break
74
75            os.remove(path)
76            subprocess.Popen("mv %s %s" % (f"{source_dir}_bk.{suffix_name}", path),
77                             shell=True).communicate()
78    print("[**********  End Rewrite Source File **********]")
79
80
81def add_lcov(subsystem_config_path):
82    try:
83        with open(subsystem_config_path, "r", encoding="utf-8", errors="ignore") as fp:
84            data_dict = json.load(fp)
85        for key, value in data_dict.items():
86            if "path" in value.keys():
87                for path_str in value["path"]:
88                    file_path = os.path.join(root_path, path_str)
89                    if os.path.exists(file_path):
90                        subprocess.Popen("cp -r %s %s" % (
91                            file_path, f"{file_path}_primal"), shell=True).communicate()
92                        source_file_path = get_source_file_list(file_path)
93                        rewrite_source_file(source_file_path)
94                    else:
95                        print("The directory does not exist.", file_path)
96    except(FileNotFoundError, AttributeError, ValueError, KeyError):
97        print("add LCOV_EXCL_BR_LINE Error")
98
99
100def get_part_config_json(part_list, system_info_path, part_path):
101    if os.path.exists(system_info_path):
102        new_json_text = {}
103        for part in part_list:
104            with open(system_info_path, "r") as system_text:
105                system_text_json = json.load(system_text)
106                if part in system_text_json:
107                    new_json_text[part] = system_text_json[part]
108                else:
109                    print("part not in all_subsystem_config.json")
110        new_json = json.dumps(new_json_text, indent=4)
111        if os.path.exists(part_path):
112            os.remove(part_path)
113        with os.fdopen(os.open(part_path, FLAGS, MODES), 'w') as out_file:
114            out_file.write(new_json)
115    else:
116        print("%s not exists.", system_info_path)
117
118
119if __name__ == '__main__':
120    part_name_list = []
121    while True:
122        print("For example: run -tp partname\n"
123              "             run -tp partname1 partname2")
124
125        # 获取用户输入命令
126        part_name = input("Please enter your command: ")
127        if part_name == "":
128            continue
129        if " -tp " in part_name:
130            part_name_list = part_name.strip().split(" -tp ")[1].split()
131            break
132        else:
133            continue
134
135    current_path = os.getcwd()
136    root_path = current_path.split("/test/testfwk/developer_test")[0]
137    all_system_info_path = os.path.join(
138        root_path,
139        "test/testfwk/developer_test/localCoverage/all_subsystem_config.json")
140    part_info_path = os.path.join(
141        root_path,
142        "test/testfwk/developer_test/localCoverage/restore_comment/part_config.json")
143
144    # 获取要修改的源代码的部件信息
145    get_part_config_json(part_name_list, all_system_info_path, part_info_path)
146
147    # 执行修改
148    add_lcov(part_info_path)
149