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 re 17import os 18import shutil 19from collections import defaultdict 20 21 22def get_ts_files(directory): 23 return set( 24 f for f in os.listdir(directory) 25 if os.path.isfile(os.path.join(directory, f)) and f.endswith('.ts') 26 ) 27 28 29def merge_component(handwritten_path: str, generated_path: str) -> None: 30 if not os.path.exists(handwritten_path) or not os.path.exists(generated_path): 31 return 32 33 handwritten_files = get_ts_files(handwritten_path) 34 generated_files = get_ts_files(generated_path) 35 36 for file in handwritten_files: 37 handwritten_file_path = os.path.join(handwritten_path, file) 38 generated_file_path = os.path.join(generated_path, file) 39 40 if file in generated_files: 41 merge_file(generated_file_path, handwritten_file_path) 42 else: 43 shutil.copy(handwritten_file_path, generated_file_path) 44 return 45 46 47def merge_file(f1: str, f2: str) -> None: 48 with open(f1, 'r') as file1: 49 lines1 = file1.readlines() 50 with open(f2, 'r') as file2: 51 lines2 = file2.readlines() 52 53 def process_lines(lines): 54 import_dict = defaultdict(set) 55 non_import = [] 56 pattern = re.compile( 57 r'^import\s*{([^}]+)}\s*from\s*(["\'])(.*?)\2\s*;?\s*$') 58 for line in lines: 59 stripped = line.strip() 60 match = pattern.match(stripped) 61 if match: 62 symbols_str, quote, module = match.groups() 63 symbols = [s.strip() for s in symbols_str.split(',')] 64 import_dict[module].update(symbols) 65 else: 66 non_import.append(line) 67 return import_dict, non_import 68 69 imports1, non_import1 = process_lines(lines1) 70 imports2, non_import2 = process_lines(lines2) 71 72 merged_imports = defaultdict(set) 73 for module in {**imports1, **imports2}: 74 merged_imports[module].update(imports1.get(module, set())) 75 merged_imports[module].update(imports2.get(module, set())) 76 77 import_lines = [ 78 f'import {{ {", ".join(sorted(symbols))} }} from "{module}";\n' 79 for module, symbols in sorted(merged_imports.items()) 80 ] 81 82 with open(f1, 'w') as f: 83 f.writelines(import_lines + non_import1 + non_import2) 84 85 return 86