blob: e3210ed86b27fbb7e51f129ead62b5391bf52a65 [file] [log] [blame]
Bowgo Tsai741a70a2018-02-05 17:41:02 +08001# 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
18import os
19import shutil
20import tempfile
21
22
23def 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
33def 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.
ThiƩbaud Weksteenb05a1a12021-12-06 15:23:18 +110042 tmp_output = tempfile.NamedTemporaryFile(mode='w+')
Bowgo Tsai741a70a2018-02-05 17:41:02 +080043 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)
Felix0d6864a2020-03-31 17:56:49 +020046 # Append empty line because a completely empty file
47 # will trip up secilc later on:
48 tmp_output.write("\n")
Bowgo Tsai741a70a2018-02-05 17:41:02 +080049 tmp_output.flush()
50
51 # Replaces the input_file.
52 shutil.copyfile(tmp_output.name, input_file)