1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3# Copyright (c) 2022 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 logging 17import os 18import re 19import typing 20 21 22class GnCommon: 23 """ 24 处理BUILD.gn文件的通用方法 25 """ 26 27 @staticmethod 28 def contains_keywords(key_words: tuple, target: str) -> bool: 29 """ 30 判断target中是否包含key_words中的元素 31 """ 32 for k in key_words: 33 if k in target: 34 return True 35 return False 36 37 @staticmethod 38 def find_files(project_path: str, 39 target_filename=None, 40 black_keywords: tuple = tuple(), 41 black_dirs: tuple = tuple()) -> set: 42 """ 43 基于linux的find命令查找文件 44 """ 45 if target_filename is None: 46 target_filename = ["BUILD.gn"] 47 cmd = "find {}".format(project_path) 48 cmd += " -name {}".format(target_filename[0]) 49 result_set = set() 50 for black_dir in black_dirs: 51 bd_path = os.path.join(project_path, black_dir) 52 cmd += " -o -path '{}' -prune".format(bd_path) 53 output = os.popen(cmd) 54 for file in output: 55 if GnCommon.contains_keywords(black_keywords, file): 56 continue 57 result_set.add(file.strip()) 58 logging.info("total: %s", len(result_set)) 59 return result_set 60 61 @staticmethod 62 def grep_one(grep_pattern: str, 63 grep_path: str, 64 excludes: tuple = tuple(), 65 black_keyword: tuple = tuple(), 66 includes=None, 67 grep_parameter='Ern'): 68 """ 69 调用linux的grep命令,开启了通用的正则匹配 70 grep_path:可以是路径,也可以是文件 71 没有grep到内容,返回None 72 """ 73 if includes is None: 74 includes = ["BUILD.gn"] 75 cmd = "grep -{} -s '{}' {}".format(grep_parameter, 76 grep_pattern, grep_path) 77 for include in includes: 78 cmd += " --include={}".format(include) 79 for exclude in excludes: 80 cmd += " --exclude-dir={}".format(exclude) 81 if len(black_keyword) != 0: 82 cmd += " | grep -Ev '{}'".format("|".join(black_keyword)) 83 logging.info(cmd) 84 result = None 85 output = os.popen(cmd).read().strip() 86 if len(output) != 0: 87 result = output 88 return result 89 90 @staticmethod 91 def find_paragraph_iter(pattern: str, content: str) -> typing.Iterator: 92 """ 93 匹配所有pattern 94 pattern: 要 95 example: 匹配ohos_shared_library 96 iter = GnCommon.find_paragraph_iter(start_pattern="ohos_shared_library", end_pattern="\}", content=filecontent) 97 for i in iter: 98 print(i.group()) 99 caution:如果是嵌套内容,则只能匹配外层的 100 """ 101 ptrn = re.compile(pattern, flags=re.S | re.M) 102 result = re.finditer(ptrn, content) 103 return result 104