Replace content in a file based on a predefined dictionary using byte-level operations. If the replaced content contains a forbidden string (as a regex pattern), do not replace and return failure.
(file_path,
replacement_dict,
inplace=False,
check_regex=None)
| 9 | |
| 10 | |
| 11 | def replace_content(file_path, |
| 12 | replacement_dict, |
| 13 | inplace=False, |
| 14 | check_regex=None): |
| 15 | """ |
| 16 | Replace content in a file based on a predefined dictionary using byte-level operations. |
| 17 | If the replaced content contains a forbidden string (as a regex pattern), do not replace and return failure. |
| 18 | """ |
| 19 | with open(file_path, 'rb') as file: |
| 20 | original_content = file.read() |
| 21 | content = original_content |
| 22 | |
| 23 | # Convert replacement_dict to bytes |
| 24 | replacement_dict_bytes = { |
| 25 | k.encode('utf-8'): v.encode('utf-8') |
| 26 | for k, v in replacement_dict.items() |
| 27 | } |
| 28 | |
| 29 | # Perform replacements |
| 30 | for old_text, new_text in replacement_dict_bytes.items(): |
| 31 | content = content.replace(old_text, new_text) |
| 32 | |
| 33 | # Check if the replaced content contains the forbidden pattern |
| 34 | if check_regex and check_regex.search(content): |
| 35 | logging.error('%s: "%s" exist after replace' % |
| 36 | (file_path, check_regex.pattern.decode('utf-8'))) |
| 37 | return False |
| 38 | |
| 39 | if content == original_content: |
| 40 | return True |
| 41 | |
| 42 | if inplace: |
| 43 | # Create a temporary file in the same directory as the original file |
| 44 | temp_dir = os.path.dirname(file_path) |
| 45 | with tempfile.NamedTemporaryFile(mode='wb', delete=False, |
| 46 | dir=temp_dir) as temp_file: |
| 47 | temp_file.write(content) |
| 48 | temp_file_path = temp_file.name |
| 49 | |
| 50 | # Replace the original file with the temporary file |
| 51 | os.replace(temp_file_path, file_path) |
| 52 | |
| 53 | return True |
| 54 | |
| 55 | |
| 56 | def main(): |