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

@ -1,5 +1,5 @@
# Zielverzeichnis für Operationen # Zielverzeichnis für Operationen
destination_directory: './' destination_directory: './web'
# Kopierregeln # Kopierregeln
copy_rules: copy_rules:
@ -15,6 +15,8 @@ copy_rules:
target: './bc8d51405ec040305a87.ico' target: './bc8d51405ec040305a87.ico'
- source: './img/favicon.ico' - source: './img/favicon.ico'
target: './favicon.ico' target: './favicon.ico'
- source: './img/favicon.png'
target: './assets/img/favicon.png'
mode: 'replace' # Überschreibt vorhandene Dateien/Ordner mode: 'replace' # Überschreibt vorhandene Dateien/Ordner
@ -26,15 +28,13 @@ copy_rules:
- source: './img/background.png' - source: './img/background.png'
target: './assets/img/background.png' target: './assets/img/background.png'
- source: './img/favicon.png'
target: './assets/img/favicon.png'
- source: './img/logo.png' - source: './img/logo.png'
target: './assets/img/logo.png' target: './assets/img/logo.png'
mode: 'copy' # Kopiert Dateien/Ordner mode: 'copy' # Kopiert Dateien/Ordner
# Modifikationsregeln # Modifikationsregeln
modification_rules: modification_rules:
- file_pattern: 'session-login-index-html..*.bundle.js' - file_pattern: 'session-login-index-html..*.chunk.js'
insert_rules: insert_rules:
- after_text: '<div class="padded-left padded-right padded-bottom-page margin-auto-y">' - after_text: '<div class="padded-left padded-right padded-bottom-page margin-auto-y">'
insert_text: '<img id="login-logo" src="/web/assets/img/banner-dark.png" width=350px style="padding: 0px;display:block; margin-left: auto; margin-right: auto;">' insert_text: '<img id="login-logo" src="/web/assets/img/banner-dark.png" width=350px style="padding: 0px;display:block; margin-left: auto; margin-right: auto;">'
@ -48,7 +48,7 @@ modification_rules:
insert_text: '<div class="seasonals-container"></div><script src="seasonals.js"></script><link rel="stylesheet" href="seasonals.css">' insert_text: '<div class="seasonals-container"></div><script src="seasonals.js"></script><link rel="stylesheet" href="seasonals.css">'
# Page title and requests tab # Page title and requests tab
- before_text: '<link href=".*" rel="stylesheet">' - before_text: '<link href="main.jellyfin.1ed46a7a22b550acaef3.css?1a23c104c65d0a7517c7" rel="stylesheet">'
insert_text: > insert_text: >
<script> <script>
document.addEventListener("DOMContentLoaded", function () { document.addEventListener("DOMContentLoaded", function () {
@ -96,11 +96,12 @@ modification_rules:
new_text: '<title>SpaceCloud - Cinema</title>' new_text: '<title>SpaceCloud - Cinema</title>'
# Instancename, Jellyseer I-Frame # Instancename, Jellyseer I-Frame
- file_pattern: 'main.jellyfin.bundle.js' #- file_pattern: 'main.jellyfin.bundle.js' # would also match 'home-html.123456.chunk.js.LICENSE.txt'
- file_pattern: '^main.jellyfin.bundle.js$' #file_pattern: '^main\.jellyfin\.bundle\.js$'
replace_rules: replace_rules:
# Set limit on how many days items should be in the next up section (last number) # Set limit on how many days items should be in the next up section (last number)
- old_text: 't("maxDaysForNextUp",e.toString(),!1);var t=parseInt(this.get("maxDaysForNextUp",!1),10);return 0===t?0:t||365}}' - old_text: 'this.set("maxDaysForNextUp",e.toString(),!1);var t=parseInt(this.get("maxDaysForNextUp",!1),10);return 0===t?0:t||365}}'
new_text: 't("maxDaysForNextUp",e.toString(),!1);var t=parseInt(this.get("maxDaysForNextUp",!1),10);return 0===t?0:t||28}}' new_text: 'this.set("maxDaysForNextUp",e.toString(),!1);var t=parseInt(this.get("maxDaysForNextUp",!1),10);return 0===t?0:t||28}}'
# Default user page size (last number), 99 fits perfect on most desktops # Default user page size (last number), 99 fits perfect on most desktops
- old_text: 'this.get("libraryPageSize",!1),10);return 0===t?0:t||100}' - old_text: 'this.get("libraryPageSize",!1),10);return 0===t?0:t||100}'
new_text: 'this.get("libraryPageSize",!1),10);return 0===t?0:t||99}' new_text: 'this.get("libraryPageSize",!1),10);return 0===t?0:t||99}'

View File

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

View File

@ -5,7 +5,7 @@ destination_directory: './web'
copy_rules: copy_rules:
- sources: - sources:
- source: './img/icon-transparent.png' - source: './img/icon-transparent.png'
target: 'assets/img/icon-transparent.png' target: './assets/img/icon-transparent.png'
mode: 'replace' # Überschreibt vorhandene Dateien/Ordner mode: 'replace' # Überschreibt vorhandene Dateien/Ordner
@ -13,7 +13,7 @@ copy_rules:
- './ui' # Gesamter Ordner/Datei wird in destination_directory kopiert - './ui' # Gesamter Ordner/Datei wird in destination_directory kopiert
- source: './img/background.png' - source: './img/background.png'
target: 'assets/img/background.png' target: './assets/img/background.png'
mode: 'copy' # Kopiert Dateien/Ordner mode: 'copy' # Kopiert Dateien/Ordner
# Modifikationsregeln # Modifikationsregeln
@ -24,6 +24,8 @@ modification_rules:
insert_text: ' added after text ' insert_text: ' added after text '
- before_text: 'This is a before text' - before_text: 'This is a before text'
insert_text: ' added before text ' insert_text: ' added before text '
replace_rules:
- old_text: 'Replace this text' - old_text: 'Replace this text'
new_text: 'Replaced text' new_text: 'Replaced text'