When restoring files, first, clear the entire directory of previously created files + while updating a file, create a parent directory if it doesn't exist

This commit is contained in:
Zvonimir Sabljic
2023-08-04 10:13:23 +02:00
parent 400281fb66
commit 68a847a827
2 changed files with 25 additions and 1 deletions

View File

@@ -3,7 +3,7 @@ import os
from termcolor import colored
from const.common import IGNORE_FOLDERS
from utils.questionary import styled_text
from helpers.files import get_files_content
from helpers.files import get_files_content, clear_directory
from helpers.cli import build_directory_tree
from helpers.agents.TechLead import TechLead
from helpers.agents.Developer import Developer
@@ -91,6 +91,7 @@ class Project:
development_step = DevelopmentSteps.get(DevelopmentSteps.id == development_step_id)
file_snapshots = FileSnapshot.select().where(FileSnapshot.development_step == development_step)
clear_directory(self.root_path, IGNORE_FOLDERS)
for file_snapshot in file_snapshots:
full_path = self.root_path + '/' + file_snapshot.name
# Ensure directory exists

View File

@@ -6,6 +6,12 @@ from database.models.file_snapshot import FileSnapshot
def update_file(path, new_content):
# Ensure the directory exists; if not, create it
dir_name = os.path.dirname(path)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
# Write content to the file
with open(path, 'w') as file:
file.write(new_content)
print(colored(f"Updated file {path}", "green"))
@@ -32,3 +38,20 @@ def get_files_content(directory, ignore=[]):
return return_array
def clear_directory(dir_path, ignore=[]):
for root, dirs, files in os.walk(dir_path, topdown=True):
# Remove ignored directories from dirs so os.walk doesn't traverse them
dirs[:] = [d for d in dirs if d not in ignore]
for file in files:
if file in ignore:
continue
path = os.path.join(root, file)
os.remove(path)
# Delete directories not in ignore list
for d in dirs:
dir_path = os.path.join(root, d)
if not os.listdir(dir_path): # Check if directory is empty
os.rmdir(dir_path)