• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2025 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 re
18import argparse
19import shutil
20import json
21import stat
22from typing import List
23
24# ani header file list
25_ANI_HEADER_LISTS = [
26]
27
28# Precompiled regular expression
29_HEADER_PATTERN = re.compile(
30    r'^\s*#\s*include\s+["<](.*/)?({})[">]'.format(
31        '|'.join(map(re.escape, _ANI_HEADER_LISTS))
32    )
33)
34
35
36def process_header_file(file_path):
37    """processing single header file"""
38    modified = False
39    try:
40        with open(file_path, 'r+', encoding='utf-8') as f:
41            content = f.read()
42            # Use a regular expression to process all rows at once
43            new_content = []
44            for line in content.splitlines():
45                if not _HEADER_PATTERN.match(line):
46                    new_content.append(line)
47                else:
48                    modified = True
49
50            if modified:
51                f.seek(0)
52                f.write('\n'.join(new_content))
53                f.truncate()
54    except Exception as e:
55        print(f"process file {file_path} failed: {str(e)}")
56    return modified
57
58
59def clean_ndk_ani_headers(ndk_header_path):
60    if not _ANI_HEADER_LISTS:
61        print("Warning: ani header file list")
62        return
63
64    # all files to be processed
65    file_paths = []
66    for root, _, files in os.walk(ndk_header_path):
67        for file in files:
68            if not file.endswith('.h'):
69                continue
70
71            file_path = os.path.join(root, file)
72            if file in _ANI_HEADER_LISTS:
73                try:
74                    os.remove(file_path)
75                    print(f"Deleted ani header file: {file_path}")
76                except OSError as e:
77                    print(f"Error deleting {file_path}: {str(e)}")
78            else:
79                file_paths.append(file_path)
80
81    # Bulk processing file include
82    for file_path in file_paths:
83        process_header_file(file_path)
84
85
86# Clear the ani header file in the systemCapability configuration json file
87def clean_json_systemCapability_headers(capability_header_path):
88    try:
89        with open(capability_header_path, 'r') as f:
90            systemCapabilitys = json.load(f)
91    except Exception as e:
92        print(f"Error reading JSON file: {str(e)}")
93        return
94
95    # Traverse all levels of items
96    for _systemCapability in systemCapabilitys:
97        # filtering ani header file
98        systemCapabilitys[_systemCapability] = [item for item in systemCapabilitys[_systemCapability]
99            if os.path.basename(item) not in _ANI_HEADER_LISTS]
100
101    # Saving the modified JSON
102    try:
103        fd = os.open(capability_header_path, os.O_WRONLY | os.O_TRUNC | os.O_CREAT,
104                     stat.S_IRUSR | stat.S_IWUSR)
105        with os.fdopen(fd, 'w') as f:
106            json.dump(systemCapabilitys, f, indent=2)
107        print("JSON file updated successfully")
108    except Exception as e:
109        print(f"Error saving JSON file: {str(e)}")
110
111
112def main():
113    parser = argparse.ArgumentParser()
114    parser.add_argument('--ndk-header-path', help='ndk header path', required=True)
115    parser.add_argument('--system-capability-header-config', required=True)
116    args = parser.parse_args()
117
118    if not os.path.isdir(args.ndk_header_path):
119        print(f"Error:path {args.ndk_header_path} is not exist!")
120        return
121
122    clean_ndk_ani_headers(args.ndk_header_path)
123    clean_json_systemCapability_headers(args.system_capability_header_config)
124    print("Ani Header file cleanup complete!")
125
126
127if __name__ == '__main__':
128    main()
129