fix replace rules

This commit is contained in:
MLH
2024-12-12 00:17:25 +01:00
parent baf406eb96
commit 3584482967
3 changed files with 33 additions and 25 deletions

View File

@ -18,7 +18,7 @@ errorList = {"copies": 0, "modifications": 0, "copyWarnings": 0, "modWarnings":
# Initialize results
results = {"copies": 0, "modifications": 0}
# MARK: Load configuration
def loadConfig(configPath):
"""Load YAML configuration."""
try:
@ -49,6 +49,7 @@ def ensureDirectory(path):
os.makedirs(path, exist_ok=True)
# MARK: Copy sources
def copySources(config, destinationDirectory):
"""Copy files and folders according to copy rules."""
print("Starting source file & folder copy and replace process...")
@ -122,17 +123,17 @@ def copySources(config, destinationDirectory):
errorList['copyWarnings'] += 1
except FileNotFoundError as e:
print(f"{Colors.RED}Error: {e}{Colors.RESET}")
print(f"\n{Colors.RED}Error: {e}{Colors.RESET}")
errorList["copies"] += 1
continue
except ValueError as e:
print(f"{Colors.RED}Configuration error: {e}{Colors.RESET}")
print(f"\n{Colors.RED}Configuration error: {e}{Colors.RESET}")
errorList["copies"] += 1
continue
except PermissionError:
print(f"{Colors.RED}Error: Permission denied when copying {sourcePath}{Colors.RESET}")
print(f"\n{Colors.RED}Error: Permission denied when copying {sourcePath}{Colors.RESET}")
errorList["copies"] += 1
continue
@ -144,12 +145,13 @@ def copySources(config, destinationDirectory):
print(f"\n{Colors.GREEN}Source file & folder copy/replace process completed{Colors.RESET} with {Colors.RED}{errorList['copies']} errors{Colors.RESET} and {Colors.YELLOW}{errorList['copyWarnings']} warnings{Colors.RESET}.\n")
# MARK: Modify files
def modifyFiles(config, destinationDirectory):
"""Modify files according to modification rules."""
print("Starting file modification process...")
for rule in config.get('modification_rules', []):
filePattern = rule.get('file_pattern', '*')
print(f"Processing files matching pattern: {filePattern}")
print(f"\nProcessing files matching pattern: {filePattern}")
# Recursively search the destination directory
for root, _, files in os.walk(destinationDirectory):
@ -168,10 +170,10 @@ def modifyFiles(config, destinationDirectory):
if 'after_text' in insertRule:
after_text = insertRule['after_text']
insert_text = insertRule['insert_text']
if after_text not in content:
if after_text not in content: #if not re.search(after_text, content): # for use of * wildcard in text
raise ValueError(f"Text '{after_text}' not found in file: {filePath}")
elif insert_text not in content:
print(f" {Colors.GREEN}Inserting text after: {after_text}{Colors.RESET}")
print(f" {Colors.GREEN}Inserting text after: {after_text} + -> {insert_text}{Colors.RESET}")
content = content.replace(after_text, after_text + insert_text)
else:
print(f" {Colors.YELLOW}Text already present after: {after_text}{Colors.RESET}")
@ -184,16 +186,16 @@ def modifyFiles(config, destinationDirectory):
if before_text not in content:
raise ValueError(f"Text '{before_text}' not found in file: {filePath}")
elif insert_text not in content:
print(f" {Colors.GREEN}Inserting text before: {before_text}{Colors.RESET}")
print(f" {Colors.GREEN}Inserting text before: {insert_text} + <- {before_text}{Colors.RESET}")
content = content.replace(before_text, insert_text + before_text)
else:
print(f" {Colors.YELLOW}Text already present before: {before_text}{Colors.RESET}")
errorList['modWarnings'] += 1
if 'old_text' in insertRule:
old_text = insertRule['old_text']
new_text = insertRule['new_text']
for replaceRules in rule.get('replace_rules', []):
if 'old_text' in replaceRules:
old_text = replaceRules['old_text']
new_text = replaceRules['new_text']
if old_text not in content and new_text not in content:
raise ValueError(f"Text '{old_text}' not found in file: {filePath}")
elif new_text not in content:
@ -209,25 +211,28 @@ def modifyFiles(config, destinationDirectory):
f.write(content)
results['modifications'] += 1
#else:
# print(f"Skipping file: {filename} (not found)")
except ValueError as e:
print(f"{Colors.RED}Error: {e}{Colors.RESET}")
print(f"\n{Colors.RED}Error: {e}{Colors.RESET}")
errorList["modifications"] += 1
continue
except PermissionError:
print(f"{Colors.RED}Error: Permission denied when modifying {filePath}{Colors.RESET}")
print(f"\n{Colors.RED}Error: Permission denied when modifying {filePath}{Colors.RESET}")
errorList["modifications"] += 1
continue
except IOError as e:
print(f"{Colors.RED}Error reading/writing file {filePath}: {e}{Colors.RESET}")
print(f"\n{Colors.RED}Error reading/writing file {filePath}: {e}{Colors.RESET}")
errorList["modifications"] += 1
continue
print(f"\n{Colors.GREEN}File modification process completed{Colors.RESET} with {Colors.RED}{errorList['modifications']} errors{Colors.RESET} and {Colors.YELLOW}{errorList['modWarnings']} warnings{Colors.RESET}.\n")
# MARK: Main function
def main():
"""Main function to execute all operations."""
# Check command-line argument