Bowgo Tsai | 741a70a | 2018-02-05 17:41:02 +0800 | [diff] [blame] | 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. |
ThiƩbaud Weksteen | b05a1a1 | 2021-12-06 15:23:18 +1100 | [diff] [blame] | 42 | tmp_output = tempfile.NamedTemporaryFile(mode='w+') |
Bowgo Tsai | 741a70a | 2018-02-05 17:41:02 +0800 | [diff] [blame] | 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) |
Felix | 0d6864a | 2020-03-31 17:56:49 +0200 | [diff] [blame] | 46 | # Append empty line because a completely empty file |
| 47 | # will trip up secilc later on: |
| 48 | tmp_output.write("\n") |
Bowgo Tsai | 741a70a | 2018-02-05 17:41:02 +0800 | [diff] [blame] | 49 | tmp_output.flush() |
| 50 | |
| 51 | # Replaces the input_file. |
| 52 | shutil.copyfile(tmp_output.name, input_file) |