1 # Copyright 2018 - The Android Open Source Project 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 """File-related utilities.""" 16 17 18 import os 19 import shutil 20 import tempfile 21 22 23 def make_parent_dirs(file_path): 24 """Creates parent directories for the file_path.""" 25 if os.path.exists(file_path): 26 return 27 28 parent_dir = os.path.dirname(file_path) 29 if parent_dir and not os.path.exists(parent_dir): 30 os.makedirs(parent_dir) 31 32 33 def filter_out(pattern_files, input_file): 34 """"Removes lines in input_file that match any line in pattern_files.""" 35 36 # Prepares patterns. 37 patterns = [] 38 for f in pattern_files: 39 patterns.extend(open(f).readlines()) 40 41 # Copy lines that are not in the pattern. 42 tmp_output = tempfile.NamedTemporaryFile() 43 with open(input_file, 'r') as in_file: 44 tmp_output.writelines(line for line in in_file.readlines() 45 if line not in patterns) 46 tmp_output.flush() 47 48 # Replaces the input_file. 49 shutil.copyfile(tmp_output.name, input_file) 50