fixed syntax

This commit is contained in:
Alfredo Oliviero 2024-11-26 13:33:13 +01:00
parent 8a8216548f
commit ec3ca118eb
1 changed files with 99 additions and 83 deletions

View File

@ -2,34 +2,58 @@ import psycopg2
import re import re
import os import os
import argparse import argparse
import traceback
_log_filename = "update_log.txt"
DEFAULT_CONTEXT_LENGTH = 20
DEFAULT_CONFIG_FILE = "/home/life/Portal-Bundle/portal-setup-wizard.properties"
# ANSI escape sequences for colors # ANSI escape sequences for colors
BLACK = '\033[30m' COLORS = {
RED = '\033[31m' 'BLACK': '\033[30m',
GREEN = '\033[32m' 'RED': '\033[31m',
YELLOW = '\033[33m' # orange on some systems 'GREEN': '\033[32m',
BLUE = '\033[34m' 'YELLOW': '\033[33m',
MAGENTA = '\033[35m' 'BLUE': '\033[34m',
CYAN = '\033[36m' 'MAGENTA': '\033[35m',
LIGHT_GRAY = '\033[37m' 'CYAN': '\033[36m',
DARK_GRAY = '\033[90m' 'LIGHT_GRAY': '\033[37m',
BRIGHT_RED = '\033[91m' 'DARK_GRAY': '\033[90m',
BRIGHT_GREEN = '\033[92m' 'BRIGHT_RED': '\033[91m',
BRIGHT_YELLOW = '\033[93m' 'BRIGHT_GREEN': '\033[92m',
BRIGHT_BLUE = '\033[94m' 'BRIGHT_YELLOW': '\033[93m',
BRIGHT_MAGENTA = '\033[95m' 'BRIGHT_BLUE': '\033[94m',
BRIGHT_CYAN = '\033[96m' 'BRIGHT_MAGENTA': '\033[95m',
WHITE = '\033[97m' 'BRIGHT_CYAN': '\033[96m',
RESET = '\033[0m' # called to return to standard terminal text color 'WHITE': '\033[97m',
'RESET': '\033[0m'
}
# Function to color a string based on a provided pattern and color # Function to color a string based on a provided pattern and color
def color_string(string, pattern, color=RED): def color_string(string, pattern, color='RED'):
return string.replace(pattern, f'{color}{pattern}{RESET}') color_code = COLORS.get(color.upper(), COLORS['RED'])
return string.replace(pattern, f'{color_code}{pattern}{COLORS["RESET"]}')
DEFAULT_CONTEXT_LENGHT = 20 # Function to log messages to a file and print to console
def log_message(message, log_file=None, color=None):
if color:
message = f"{COLORS[color.upper()]}{message}{COLORS['RESET']}"
print(message)
# Default configuration file path log_file = log_file or _log_filename
DEFAULT_CONFIG_FILE = "/home/life/Portal-Bundle/portal-setup-wizard.properties" if log_file:
with open(log_file, 'a') as filelogs:
filelogs.write(message + '\n')
def error_message(message, log_file=None, exception=None):
log_message(message, log_file, color='RED')
if exception:
log_file = log_file or _log_filename
with open(log_file, 'a') as filelogs:
filelogs.write(traceback.format_exc())
print(traceback.format_exc())
# Function to read database connection parameters from the configuration file # Function to read database connection parameters from the configuration file
def read_db_config(config_file_path): def read_db_config(config_file_path):
@ -43,6 +67,7 @@ def read_db_config(config_file_path):
# Function to connect to the database # Function to connect to the database
def connect_to_db(db_host, db_port, db_name, db_user, db_password): def connect_to_db(db_host, db_port, db_name, db_user, db_password):
try:
conn = psycopg2.connect( conn = psycopg2.connect(
host=db_host, host=db_host,
port=db_port, port=db_port,
@ -51,14 +76,14 @@ def connect_to_db(db_host, db_port, db_name, db_user, db_password):
password=db_password password=db_password
) )
return conn return conn
except Exception as e:
error_message(f"Error connecting to db {e}", e)
exit(1)
# Function to update typesettings # Function to update typesettings
def update_typesettings(cursor, current_pluginid, next_pluginid, log_file): def update_typesettings(cursor, current_pluginid, next_pluginid):
try: try:
search_query = """ search_query = "SELECT layoutid, typesettings FROM layout WHERE typesettings LIKE %s;"
SELECT layoutid, typesettings FROM layout
WHERE typesettings LIKE %s;
"""
cursor.execute(search_query, ('%' + current_pluginid + '%',)) cursor.execute(search_query, ('%' + current_pluginid + '%',))
rows = cursor.fetchall() rows = cursor.fetchall()
@ -72,36 +97,35 @@ def update_typesettings(cursor, current_pluginid, next_pluginid, log_file):
layoutid, typesettings = row layoutid, typesettings = row
updated_typesettings = typesettings.replace(current_pluginid, next_pluginid) updated_typesettings = typesettings.replace(current_pluginid, next_pluginid)
cursor.execute(update_query, (current_pluginid, next_pluginid, layoutid)) cursor.execute(update_query, (current_pluginid, next_pluginid, layoutid))
log_file.write(f"Executed: {cursor.mogrify(update_query, (updated_typesettings, layoutid))}\n") log_message(f"Executed: {cursor.mogrify(update_query, (current_pluginid, next_pluginid, layoutid)).decode('utf-8')}\n")
log_file.write(f"Restore command: {update_query % (typesettings, layoutid)}\n") restore_query = "UPDATE layout SET typesettings = %s WHERE layoutid = %s;"
print(f"Replaced {current_pluginid} with {next_pluginid} in typesettings.") log_message(f"Restore command: {cursor.mogrify(restore_query, (typesettings, layoutid)).decode('utf-8')}\n")
log_message(f"Replaced {current_pluginid} with {next_pluginid} in typesettings.")
except Exception as e: except Exception as e:
print(f"Error during update: {e}") error_message(f"Error during update {e}", e)
log_file.write(f"Error during update: {e}\n") exit(1)
# Function to search for entries containing CURRENT_PLUGINID with context # Function to search for entries containing CURRENT_PLUGINID with context
def search_current_pluginid(cursor, current_pluginid, enable_color, context_size=10): def search_current_pluginid(cursor, current_pluginid, enable_color, context_size=DEFAULT_CONTEXT_LENGTH):
try: try:
search_query = """ search_query = "SELECT layoutid, typesettings FROM layout WHERE typesettings LIKE %s;"
SELECT layoutid, typesettings FROM layout
WHERE typesettings LIKE %s;
"""
cursor.execute(search_query, ('%' + current_pluginid + '%',)) cursor.execute(search_query, ('%' + current_pluginid + '%',))
rows = cursor.fetchall() rows = cursor.fetchall()
print(f"Entries containing {current_pluginid}:") log_message(f"Entries containing {current_pluginid}:")
for layoutid, typesettings in rows: 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(re.escape(current_pluginid), typesettings)]
matches = [(m.start(), m.end()) for m in re.finditer(current_pluginid, typesettings)]
for start, end in matches: for start, end in matches:
context_start = max(0, start - context_size) context_start = max(0, start - context_size)
context_end = min(len(typesettings), end + context_size) context_end = min(len(typesettings), end + context_size)
context_str = typesettings[context_start:context_end] context_str = typesettings[context_start:context_end]
if enable_color: if enable_color:
context_str = color_string(context_str, current_pluginid, BRIGHT_RED) context_str = color_string(context_str, current_pluginid, 'BRIGHT_RED')
print(f"Layout ID: {layoutid}, Context: ...{context_str}...") log_message(f"Layout ID: {layoutid}, Context: ...{context_str}...")
except Exception as e: except Exception as e:
print(f"Error during search: {e}") error_message(f"Error during search {e}", e)
exit(1)
# Parsing command-line arguments # Parsing command-line arguments
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
@ -120,25 +144,21 @@ Examples of usage:
''', ''',
formatter_class=argparse.RawTextHelpFormatter 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('--config-file', default=DEFAULT_CONFIG_FILE, help="Path to the configuration file with database parameters")
parser.add_argument('--db-host', help="Database host") parser.add_argument('--db-host', help="Database host")
parser.add_argument('--db-port', type=int, help="Database port") parser.add_argument('--db-port', type=int, help="Database port")
parser.add_argument('--db-name', help="Database name") parser.add_argument('--db-name', help="Database name")
parser.add_argument('--db-user', help="Database user") parser.add_argument('--db-user', help="Database user")
parser.add_argument('--db-password', help="Database password") 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('--current-pluginid', '-c', 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('--next-pluginid', '-n', 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('--update', '-u', 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('--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)) parser.add_argument('--context-size', '-s', type=int, default=DEFAULT_CONTEXT_LENGTH, help='Number of characters of context to show around the found pattern')
args = parser.parse_args() args = parser.parse_args()
if not any(vars(args).values()): # Initialize database connection parameters
parser.print_help()
exit(1)
# Initialize database connection parameters with None
db_host = db_port = db_name = db_user = db_password = None db_host = db_port = db_name = db_user = db_password = None
# Determine the database connection parameters # Determine the database connection parameters
@ -150,32 +170,28 @@ if args.config_file:
db_user = db_config['jdbc.default.username'] db_user = db_config['jdbc.default.username']
db_password = db_config['jdbc.default.password'] db_password = db_config['jdbc.default.password']
if args.db_host: # Override with command-line arguments if provided
db_host = args.db_host db_host = args.db_host or db_host
db_port = args.db_port or db_port
db_name = args.db_name or db_name
db_user = args.db_user or db_user
db_password = args.db_password or db_password
if args.db_port: # Check if all necessary parameters are available
db_port = args.db_port if not (db_host and db_port and db_name and db_user and db_password):
error_message("Database connection parameters are incomplete.")
if args.db_name: exit(1)
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 # Connect to the database
conn = connect_to_db(db_host, db_port, db_name, db_user, db_password) conn = connect_to_db(db_host, db_port, db_name, db_user, db_password)
cursor = conn.cursor() cursor = conn.cursor()
log_filename = "update_log.txt"
with open(log_filename, 'a') as log_file: if args.update:
if args.update: update_typesettings(cursor, args.current_pluginid, args.next_pluginid)
update_typesettings(cursor, args.current_pluginid, args.next_pluginid, log_file) else:
else:
search_current_pluginid(cursor, args.current_pluginid, args.color, args.context_size) search_current_pluginid(cursor, args.current_pluginid, args.color, args.context_size)
conn.commit() conn.commit()
cursor.close() cursor.close()
conn.close() conn.close()