1#!/usr/bin/env python 2# coding: utf-8 3 4""" 5Copyright (c) 2023 Huawei Device Co., Ltd. 6Licensed under the Apache License, Version 2.0 (the "License"); 7you may not use this file except in compliance with the License. 8You may obtain a copy of the License at 9 10 http://www.apache.org/licenses/LICENSE-2.0 11 12Unless required by applicable law or agreed to in writing, software 13distributed under the License is distributed on an "AS IS" BASIS, 14WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15See the License for the specific language governing permissions and 16limitations under the License. 17 18""" 19 20import json 21import os 22import subprocess 23 24 25def read_json_file(input_file): 26 data = None 27 try: 28 with open(input_file, 'r') as input_f: 29 data = json.load(input_f) 30 except json.decoder.JSONDecodeError: 31 print('The file \'{}\' format is incorrect.'.format(input_file)) 32 raise 33 except: 34 print('read file \'{}\' failed.'.format(input_file)) 35 raise 36 return data 37 38 39def read_file(input_file): 40 lines = [] 41 with open(input_file, 'r') as fp: 42 for line in fp.readlines(): 43 lines.append(line.strip()) 44 return lines 45 46 47def run_command(in_cmd): 48 ret = subprocess.run(in_cmd, shell=False).returncode 49 if ret != 0: 50 raise Exception(ret) 51 52 53def check_empty_row(policy_file): 54 err = 0 55 with open(policy_file, 'r') as fp: 56 lines = fp.readlines() 57 if len(lines) == 0: 58 return 0 59 last_line = lines[-1] 60 if '\n' not in last_line: 61 print("".join([policy_file, " : need an empty line at end\n"])) 62 err = 1 63 return err 64 65 66def traverse_folder_in_type(search_dir, file_suffix): 67 policy_file_list = [] 68 flag = 0 69 for root, _, files in sorted(os.walk(search_dir)): 70 for each_file in files: 71 if each_file.endswith(file_suffix): 72 path = os.path.join(root, each_file) 73 flag |= check_empty_row(path) 74 policy_file_list.append(path) 75 policy_file_list.sort() 76 return policy_file_list, flag 77 78 79def traverse_file_in_each_type(dir_list, file_suffix): 80 policy_files_list = [] 81 err = 0 82 folder_list = dir_list.split(":") 83 for folder in folder_list: 84 type_file_list, flag = traverse_folder_in_type( 85 folder, file_suffix) 86 err |= flag 87 if len(type_file_list) == 0: 88 continue 89 policy_files_list.extend(type_file_list) 90 if err: 91 raise Exception(err) 92 return policy_files_list 93