fixes
This commit is contained in:
@ -1,150 +1,113 @@
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import shutil
|
||||
import yaml
|
||||
import re
|
||||
|
||||
def load_configuration(config_path):
|
||||
"""
|
||||
Load configuration from a YAML file.
|
||||
|
||||
:param config_path: Path to the configuration file
|
||||
:return: Loaded configuration dictionary
|
||||
"""
|
||||
with open(config_path, 'r', encoding='utf-8') as config_file:
|
||||
return yaml.safe_load(config_file)
|
||||
def loadConfig(config_path):
|
||||
"""Load YAML configuration."""
|
||||
print(f"Loading configuration from {config_path}")
|
||||
with open(config_path, 'r', encoding='utf-8') as file:
|
||||
config = yaml.safe_load(file)
|
||||
print("Configuration loaded successfully.")
|
||||
return config
|
||||
|
||||
def matches_file_pattern(filename, pattern):
|
||||
"""
|
||||
Check if filename matches the given pattern.
|
||||
|
||||
:param filename: Name of the file
|
||||
:param pattern: Regex pattern to match
|
||||
:return: Boolean indicating if filename matches
|
||||
"""
|
||||
return re.search(pattern, filename) is not None
|
||||
def ensureDirectory(path):
|
||||
"""Ensure that a directory exists."""
|
||||
print(f"Checking/creating directory: {path}")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
def apply_insert_rules(content, insert_rules):
|
||||
"""
|
||||
Apply insertion rules to the content.
|
||||
|
||||
:param content: Original file content
|
||||
:param insert_rules: List of insertion rules
|
||||
:return: Modified content and modification flag
|
||||
"""
|
||||
modified_content = content
|
||||
modified = False
|
||||
def copySources(config, destination_directory):
|
||||
"""Copy files and folders according to copy rules."""
|
||||
print("Starting source file/folder copy process...")
|
||||
for rule in config.get('copy_rules', []):
|
||||
for source in rule.get('sources', []):
|
||||
# Distinguish between sources with explicit target and without
|
||||
if isinstance(source, dict):
|
||||
src_path = source['source']
|
||||
target_path = os.path.join(destination_directory, source['target'])
|
||||
else:
|
||||
src_path = source
|
||||
target_path = os.path.join(destination_directory, os.path.basename(src_path))
|
||||
|
||||
# Create target directory
|
||||
ensureDirectory(os.path.dirname(target_path))
|
||||
|
||||
# Copy or replace mode
|
||||
if rule.get('mode') == 'replace' and os.path.exists(target_path):
|
||||
print(f"Replacing existing path: {target_path}")
|
||||
shutil.rmtree(target_path) if os.path.isdir(target_path) else os.remove(target_path)
|
||||
|
||||
# Copy files or directories
|
||||
if os.path.isdir(src_path):
|
||||
print(f"Copying directory: {src_path} -> {target_path}")
|
||||
shutil.copytree(src_path, target_path)
|
||||
else:
|
||||
print(f"Copying file: {src_path} -> {target_path}")
|
||||
shutil.copy2(src_path, target_path)
|
||||
print("Source file/folder copy process completed.")
|
||||
|
||||
for rule in insert_rules:
|
||||
insert_text = rule.get('insert_text')
|
||||
def modifyFiles(config, destination_directory):
|
||||
"""Modify files according to modification rules."""
|
||||
print("Starting file modification process...")
|
||||
for rule in config.get('modification_rules', []):
|
||||
file_pattern = rule.get('file_pattern', '*')
|
||||
print(f"Processing files matching pattern: {file_pattern}")
|
||||
|
||||
# Insert after specific text
|
||||
if 'after_text' in rule:
|
||||
search_text = rule.get('after_text')
|
||||
if insert_text not in modified_content:
|
||||
modified_content = modified_content.replace(
|
||||
search_text,
|
||||
f'{search_text}\n{insert_text}'
|
||||
)
|
||||
modified = True
|
||||
|
||||
# Insert before specific text
|
||||
elif 'before_text' in rule:
|
||||
search_text = rule.get('before_text')
|
||||
if insert_text not in modified_content:
|
||||
modified_content = modified_content.replace(
|
||||
search_text,
|
||||
f'{insert_text}\n{search_text}'
|
||||
)
|
||||
modified = True
|
||||
|
||||
return modified_content, modified
|
||||
|
||||
def apply_replace_rules(content, replace_rules):
|
||||
"""
|
||||
Apply replacement rules to the content.
|
||||
|
||||
:param content: Original file content
|
||||
:param replace_rules: List of replacement rules
|
||||
:return: Modified content and modification flag
|
||||
"""
|
||||
modified_content = content
|
||||
modified = False
|
||||
|
||||
for rule in replace_rules:
|
||||
old_text = rule.get('old_text')
|
||||
new_text = rule.get('new_text')
|
||||
|
||||
# Replace text if found
|
||||
if old_text in modified_content:
|
||||
modified_content = modified_content.replace(old_text, new_text)
|
||||
modified = True
|
||||
|
||||
return modified_content, modified
|
||||
|
||||
def modify_files(config):
|
||||
"""
|
||||
Modify files based on configuration rules.
|
||||
|
||||
:param config: Configuration dictionary
|
||||
:return: Number of modified files
|
||||
"""
|
||||
files_modified = 0
|
||||
start_directory = config.get('start_directory', '.')
|
||||
|
||||
# Process each modification entry
|
||||
for entry in config.get('modifications', []):
|
||||
search_pattern = entry.get('file_pattern')
|
||||
insert_rules = entry.get('insert_rules', [])
|
||||
replace_rules = entry.get('replace_rules', [])
|
||||
|
||||
# Walk through directory
|
||||
for root, _, files in os.walk(start_directory):
|
||||
# Recursively search the destination directory
|
||||
for root, _, files in os.walk(destination_directory):
|
||||
for filename in files:
|
||||
# Check if file matches pattern
|
||||
if matches_file_pattern(filename, search_pattern):
|
||||
full_path = os.path.join(root, filename)
|
||||
if re.match(file_pattern, filename):
|
||||
file_path = os.path.join(root, filename)
|
||||
print(f"Modifying file: {file_path}")
|
||||
|
||||
try:
|
||||
# Read file content
|
||||
with open(full_path, 'r', encoding='utf-8') as file:
|
||||
content = file.read()
|
||||
|
||||
# Apply insert rules
|
||||
content_after_insert, insert_modified = apply_insert_rules(
|
||||
content, insert_rules
|
||||
)
|
||||
|
||||
# Apply replace rules
|
||||
final_content, replace_modified = apply_replace_rules(
|
||||
content_after_insert, replace_rules
|
||||
)
|
||||
|
||||
# Save modified file
|
||||
if insert_modified or replace_modified:
|
||||
with open(full_path, 'w', encoding='utf-8') as file:
|
||||
file.write(final_content)
|
||||
|
||||
files_modified += 1
|
||||
print(f'Modified: {full_path}')
|
||||
# Read file content
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
except Exception as e:
|
||||
print(f'Error processing file {full_path}: {e}')
|
||||
|
||||
return files_modified
|
||||
# Perform text replacements
|
||||
for insert_rule in rule.get('insert_rules', []):
|
||||
if 'after_text' in insert_rule:
|
||||
print(f" Inserting text after: {insert_rule['after_text']}")
|
||||
content = content.replace(
|
||||
insert_rule['after_text'],
|
||||
insert_rule['after_text'] + insert_rule['insert_text']
|
||||
)
|
||||
|
||||
if 'before_text' in insert_rule:
|
||||
print(f" Inserting text before: {insert_rule['before_text']}")
|
||||
content = content.replace(
|
||||
insert_rule['before_text'],
|
||||
insert_rule['insert_text'] + insert_rule['before_text']
|
||||
)
|
||||
|
||||
if 'old_text' in insert_rule:
|
||||
print(f" Replacing text: {insert_rule['old_text']} -> {insert_rule['new_text']}")
|
||||
content = content.replace(
|
||||
insert_rule['old_text'],
|
||||
insert_rule['new_text']
|
||||
)
|
||||
|
||||
# Write modified contents
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
print("File modification process completed.")
|
||||
|
||||
def main():
|
||||
# Check command-line argument
|
||||
if len(sys.argv) < 2:
|
||||
print("Please provide the path to the configuration file.")
|
||||
sys.exit(1)
|
||||
def main(config_path):
|
||||
"""Main function to execute all operations."""
|
||||
# Load configuration
|
||||
config = loadConfig(config_path)
|
||||
|
||||
config_path = sys.argv[1]
|
||||
# Ensure destination directory
|
||||
destination_directory = config.get('destination_directory', './web')
|
||||
ensureDirectory(destination_directory)
|
||||
|
||||
# Load configuration and modify files
|
||||
config = load_configuration(config_path)
|
||||
total_modified = modify_files(config)
|
||||
# Copy files and folders
|
||||
copySources(config, destination_directory)
|
||||
|
||||
print(f'\nTotal files modified: {total_modified}')
|
||||
# Modify files
|
||||
modifyFiles(config, destination_directory)
|
||||
|
||||
print(f"All operations in {destination_directory} completed successfully.")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
main('config.yaml')
|
Reference in New Issue
Block a user