shows current plugin versions in layout.typesettings and performs the update to new version

This commit is contained in:
Alfredo Oliviero 2024-07-18 12:41:27 +02:00
parent f22deb4426
commit 7969f8373d
1 changed files with 181 additions and 0 deletions

View File

@ -0,0 +1,181 @@
import psycopg2
import re
import os
import argparse
# ANSI escape sequences for colors
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m' # orange on some systems
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
LIGHT_GRAY = '\033[37m'
DARK_GRAY = '\033[90m'
BRIGHT_RED = '\033[91m'
BRIGHT_GREEN = '\033[92m'
BRIGHT_YELLOW = '\033[93m'
BRIGHT_BLUE = '\033[94m'
BRIGHT_MAGENTA = '\033[95m'
BRIGHT_CYAN = '\033[96m'
WHITE = '\033[97m'
RESET = '\033[0m' # called to return to standard terminal text color
# Function to color a string based on a provided pattern and color
def color_string(string, pattern, color=RED):
return string.replace(pattern, f'{color}{pattern}{RESET}')
DEFAULT_CONTEXT_LENGHT = 20
# Default configuration file path
DEFAULT_CONFIG_FILE = "/home/life/Portal-Bundle/portal-setup-wizard.properties"
# Function to read database connection parameters from the configuration file
def read_db_config(config_file_path):
config = {}
with open(config_file_path, 'r') as file:
for line in file:
if line.strip() and '=' in line and not line.startswith("#"):
key, value = line.strip().split('=', 1)
config[key.strip()] = value.strip()
return config
# Function to connect to the database
def connect_to_db(db_host, db_port, db_name, db_user, db_password):
conn = psycopg2.connect(
host=db_host,
port=db_port,
dbname=db_name,
user=db_user,
password=db_password
)
return conn
# Function to update typesettings
def update_typesettings(cursor, current_pluginid, next_pluginid, log_file):
try:
search_query = """
SELECT layoutid, typesettings FROM layout
WHERE typesettings LIKE %s;
"""
cursor.execute(search_query, ('%' + current_pluginid + '%',))
rows = cursor.fetchall()
update_query = """
UPDATE layout
SET typesettings = replace(typesettings, %s, %s)
WHERE layoutid = %s;
"""
for row in rows:
layoutid, typesettings = row
updated_typesettings = typesettings.replace(current_pluginid, next_pluginid)
cursor.execute(update_query, (current_pluginid, next_pluginid, layoutid))
log_file.write(f"Executed: {cursor.mogrify(update_query, (updated_typesettings, layoutid))}\n")
log_file.write(f"Restore command: {update_query % (typesettings, layoutid)}\n")
print(f"Replaced {current_pluginid} with {next_pluginid} in typesettings.")
except Exception as e:
print(f"Error during update: {e}")
log_file.write(f"Error during update: {e}\n")
# Function to search for entries containing CURRENT_PLUGINID with context
def search_current_pluginid(cursor, current_pluginid, enable_color, context_size=10):
try:
search_query = """
SELECT layoutid, typesettings FROM layout
WHERE typesettings LIKE %s;
"""
cursor.execute(search_query, ('%' + current_pluginid + '%',))
rows = cursor.fetchall()
print(f"Entries containing {current_pluginid}:")
for layoutid, typesettings in rows:
# Find all occurrences of the pattern and print with context
matches = [(m.start(), m.end()) for m in re.finditer(current_pluginid, typesettings)]
for start, end in matches:
context_start = max(0, start - context_size)
context_end = min(len(typesettings), end + context_size)
context_str = typesettings[context_start:context_end]
if enable_color:
context_str = color_string(context_str, current_pluginid, BRIGHT_RED)
print(f"Layout ID: {layoutid}, Context: ...{context_str}...")
except Exception as e:
print(f"Error during search: {e}")
# Parsing command-line arguments
parser = argparse.ArgumentParser(
description='Update and search layout typesettings.',
epilog='''
Examples of usage:
1. Update typesettings:
python3 update_layout.py --current-pluginid CURRENT_PLUGINID --next-pluginid NEXT_PLUGINID --update
2. Search for entries with current plugin ID (default action):
python3 update_layout.py --current-pluginid CURRENT_PLUGINID
3. Use a configuration file for database parameters:
python3 update_layout.py --config-file /path/to/portal-setup-wizard.properties --current-pluginid CURRENT_PLUGINID
''',
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument('--config-file', default=DEFAULT_CONFIG_FILE, help="Path to the configuration file with database parameters (default: {})".format(DEFAULT_CONFIG_FILE))
parser.add_argument('--db-host', help="Database host")
parser.add_argument('--db-port', type=int, help="Database port")
parser.add_argument('--db-name', help="Database name")
parser.add_argument('--db-user', help="Database user")
parser.add_argument('--db-password', help="Database password")
parser.add_argument('--current-pluginid', type=str, required=True, help='Current plugin ID to search for')
parser.add_argument('--next-pluginid', type=str, help='Next plugin ID to replace with')
parser.add_argument('--update', action='store_true', help='Update the typesettings by replacing CURRENT_PLUGINID with NEXT_PLUGINID')
parser.add_argument('--color', type=bool, default=True, help='Enable colored output (default: true)')
parser.add_argument('--context-size', type=int, default=DEFAULT_CONTEXT_LENGHT, help='Number of characters of context to show around the found pattern (default: {})'.format(DEFAULT_CONTEXT_LENGHT))
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
exit(1)
# Initialize database connection parameters with None
db_host = db_port = db_name = db_user = db_password = None
# Determine the database connection parameters
if args.config_file:
db_config = read_db_config(args.config_file)
db_host = db_config['jdbc.default.url'].split('/')[2].split(':')[0]
db_port = int(db_config['jdbc.default.url'].split('/')[2].split(':')[1])
db_name = db_config['jdbc.default.url'].split('/')[-1]
db_user = db_config['jdbc.default.username']
db_password = db_config['jdbc.default.password']
if args.db_host:
db_host = args.db_host
if args.db_port:
db_port = args.db_port
if args.db_name:
db_name = args.db_name
if args.db_user:
db_user = args.db_user
if args.db_password:
db_password = args.db_password
# Connect to the database
conn = connect_to_db(db_host, db_port, db_name, db_user, db_password)
cursor = conn.cursor()
log_filename = "update_log.txt"
with open(log_filename, 'a') as log_file:
if args.update:
update_typesettings(cursor, args.current_pluginid, args.next_pluginid, log_file)
else:
search_current_pluginid(cursor, args.current_pluginid, args.color, args.context_size)
conn.commit()
cursor.close()
conn.close()