From c3c5f36ffccc22670a1254ad4e6861dd91985f97 Mon Sep 17 00:00:00 2001 From: Kumi Date: Thu, 18 Jul 2024 18:46:05 +0200 Subject: [PATCH] refactor(config): replace temp file usage with temp dir Updated the saving mechanism for temporary configuration files by utilizing a temporary directory instead of a named temporary file. This change streamlines file handling and avoids potential issues related to file name collisions. Improves reliability of configuration updates by ensuring a cleaner and more isolated temporary workspace, which enhances process safety and consistency. --- update_local_config.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/update_local_config.py b/update_local_config.py index 4807c43..3bc88ac 100644 --- a/update_local_config.py +++ b/update_local_config.py @@ -62,16 +62,19 @@ def main(): updated_content = replace_peer_section(config_content, new_peer_section) # Step 4: Save the updated configuration file - with tempfile.NamedTemporaryFile(delete=False, mode='w') as temp_file: - temp_file.write(updated_content) - temp_file_path = temp_file.name + with tempfile.TemporaryDirectory(delete=False, mode='w') as tempdir: + temp_file = pathlib.Path(tempdir) / f"{interface}.conf" + temp_file_path = str(temp_file) - # Step 5: Apply the updated Wireguard configuration - subprocess.run(["wg-quick", "down", interface], stderr=subprocess.DEVNULL) - subprocess.run(["wg-quick", "up", temp_file_path]) + with open(temp_file_path, 'w') as file: + file.write(updated_content) - # Overwrite the original config file with the updated content - os.replace(temp_file_path, config_path) + # Step 5: Apply the updated Wireguard configuration + subprocess.run(["wg-quick", "down", interface], stderr=subprocess.DEVNULL) + subprocess.run(["wg-quick", "up", temp_file_path]) + + # Overwrite the original config file with the updated content + os.replace(temp_file_path, config_path) print(f"Local Wireguard configuration for {interface} updated and applied successfully.")