import sys import re def replace_func(content, func_name, new_content): regex = r'(^(@.*? )*def ' + func_name + r'\(.*\):.*?)(\n+(?=@|def |class )|\Z)' pattern = re.compile(regex, re.MULTILINE | re.DOTALL) if pattern.search(content): return pattern.sub(new_content.strip() + '\n\n', content) regex = r'(^def ' + func_name + r'\(.*\):.*?)(\n+(?=@|def |class )|\Z)' pattern = re.compile(regex, re.MULTILINE | re.DOTALL) if pattern.search(content): return pattern.sub(new_content.strip() + '\n\n', content) print(f"Warning: Could not find function {func_name}") return content file_path = 'core/views.py' with open(file_path, 'r') as f: content = f.read() with open('core/filter_helper.py', 'r') as f: helper = f.read().strip() if 'def get_filtered_voter_queryset' not in content: if '@role_required' in content and 'def voter_advanced_search' in content: content = content.replace('@role_required', helper + '\n\n' + '@role_required', 1) else: content = content.replace('def voter_advanced_search', helper + '\n\n' + 'def voter_advanced_search', 1) with open('core/views_new.py', 'r') as f: voter_advanced_search_new = f.read().strip() with open('core/bulk_sms_new.py', 'r') as f: bulk_send_sms_new = f.read().strip() with open('core/bulk_email_new.py', 'r') as f: voter_bulk_send_email_new = f.read().strip() with open('core/export_new.py', 'r') as f: export_voters_csv_new = f.read().strip() content = replace_func(content, 'voter_advanced_search', voter_advanced_search_new) content = replace_func(content, 'bulk_send_sms', bulk_send_sms_new) content = replace_func(content, 'voter_bulk_send_email', voter_bulk_send_email_new) content = replace_func(content, 'export_voters_csv', export_voters_csv_new) with open(file_path, 'w') as f: f.write(content)