1#!/usr/bin/env python3 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 16 17""" 18Usage: python3 main.py <path_to_ets2panda> <path_to_gen_dir> <path_to_header_or_dir> [<path_to_header_or_dir> ...] 19Description: Parse c++ headers to yaml files. 20""" 21 22import os.path 23import traceback 24from arg_parser import parse_arguments, check_arguments 25 26# pylint: disable=W0401,W0614 27from cpp_parser import CppParser 28from log_tools import init_log, error_log, parsing_failed_msg, warning_log 29from prepare_header import remove_comments, extract_and_remove_includes 30from file_tools import print_to_yaml 31from runtime_collections import ( 32 init_collections, 33 add_to_statistics, 34 add_to_custom_yamls, 35 save_custom_yamls, 36 save_statistics, 37) 38 39 40def parse_header(src_path: str, dest_path: str) -> None: 41 """ 42 Parse one .h file to .yaml. 43 """ 44 with open(src_path, "r", encoding="utf-8") as file: 45 data = file.read() 46 data = remove_comments(data) 47 data, includes = extract_and_remove_includes(data) 48 49 try: 50 res = CppParser(data).parse() 51 52 if len(includes) != 0: 53 res["include"] = includes 54 55 if not os.path.exists(os.path.dirname(dest_path)): 56 os.makedirs(os.path.dirname(dest_path)) 57 58 print_to_yaml(dest_path, res) 59 60 # Collect statistics 61 add_to_statistics("generated_yamls", dest_path) 62 # Collect custom yamls 63 add_to_custom_yamls("pathsToHeaders", "paths", src_path) 64 65 except Exception: # pylint: disable=W0718 66 os.fdopen(os.open(dest_path, os.O_CREAT, mode=511), "w", encoding="utf-8").close() 67 68 warning_log(f"Can't parse '{src_path}'") 69 error_log(f"Error! Can't parse '{src_path}'\n{traceback.format_exc()}\n") 70 parsing_failed_msg(src_path) 71 72 73if __name__ == "__main__": 74 args = check_arguments(parse_arguments()) 75 76 init_collections(args.lib_gen_dir) 77 init_log(args.lib_gen_dir) 78 79 result_dir = os.path.join(args.lib_gen_dir, "gen/headers") 80 os.makedirs(result_dir, exist_ok=True) 81 82 for header in args.headers: 83 dst = os.path.join(result_dir, f"{os.path.splitext(os.path.relpath(header, args.es2panda_root))[0]}.yaml") 84 parse_header(header, dst) 85 86 save_custom_yamls() 87 save_statistics() 88