fixed syntax
This commit is contained in:
parent
8a8216548f
commit
ec3ca118eb
|
@ -2,34 +2,58 @@ import psycopg2
|
|||
import re
|
||||
import os
|
||||
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
|
||||
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
|
||||
COLORS = {
|
||||
'BLACK': '\033[30m',
|
||||
'RED': '\033[31m',
|
||||
'GREEN': '\033[32m',
|
||||
'YELLOW': '\033[33m',
|
||||
'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'
|
||||
}
|
||||
|
||||
# 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}')
|
||||
def color_string(string, pattern, color='RED'):
|
||||
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
|
||||
DEFAULT_CONFIG_FILE = "/home/life/Portal-Bundle/portal-setup-wizard.properties"
|
||||
log_file = log_file or _log_filename
|
||||
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
|
||||
def read_db_config(config_file_path):
|
||||
|
@ -43,6 +67,7 @@ def read_db_config(config_file_path):
|
|||
|
||||
# Function to connect to the database
|
||||
def connect_to_db(db_host, db_port, db_name, db_user, db_password):
|
||||
try:
|
||||
conn = psycopg2.connect(
|
||||
host=db_host,
|
||||
port=db_port,
|
||||
|
@ -51,14 +76,14 @@ def connect_to_db(db_host, db_port, db_name, db_user, db_password):
|
|||
password=db_password
|
||||
)
|
||||
return conn
|
||||
except Exception as e:
|
||||
error_message(f"Error connecting to db {e}", e)
|
||||
exit(1)
|
||||
|
||||
# Function to update typesettings
|
||||
def update_typesettings(cursor, current_pluginid, next_pluginid, log_file):
|
||||
def update_typesettings(cursor, current_pluginid, next_pluginid):
|
||||
try:
|
||||
search_query = """
|
||||
SELECT layoutid, typesettings FROM layout
|
||||
WHERE typesettings LIKE %s;
|
||||
"""
|
||||
search_query = "SELECT layoutid, typesettings FROM layout WHERE typesettings LIKE %s;"
|
||||
cursor.execute(search_query, ('%' + current_pluginid + '%',))
|
||||
rows = cursor.fetchall()
|
||||
|
||||
|
@ -72,36 +97,35 @@ def update_typesettings(cursor, current_pluginid, next_pluginid, log_file):
|
|||
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.")
|
||||
log_message(f"Executed: {cursor.mogrify(update_query, (current_pluginid, next_pluginid, layoutid)).decode('utf-8')}\n")
|
||||
restore_query = "UPDATE layout SET typesettings = %s WHERE layoutid = %s;"
|
||||
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:
|
||||
print(f"Error during update: {e}")
|
||||
log_file.write(f"Error during update: {e}\n")
|
||||
error_message(f"Error during update {e}", e)
|
||||
exit(1)
|
||||
|
||||
# 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:
|
||||
search_query = """
|
||||
SELECT layoutid, typesettings FROM layout
|
||||
WHERE typesettings LIKE %s;
|
||||
"""
|
||||
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}:")
|
||||
log_message(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)]
|
||||
matches = [(m.start(), m.end()) for m in re.finditer(re.escape(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}...")
|
||||
context_str = color_string(context_str, current_pluginid, 'BRIGHT_RED')
|
||||
log_message(f"Layout ID: {layoutid}, Context: ...{context_str}...")
|
||||
except Exception as e:
|
||||
print(f"Error during search: {e}")
|
||||
error_message(f"Error during search {e}", e)
|
||||
exit(1)
|
||||
|
||||
|
||||
# Parsing command-line arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
|
@ -120,25 +144,21 @@ Examples of usage:
|
|||
''',
|
||||
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-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('--current-pluginid', '-c', type=str, required=True, help='Current plugin ID to search for')
|
||||
parser.add_argument('--next-pluginid', '-n', type=str, help='Next plugin ID to replace with')
|
||||
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('--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()
|
||||
|
||||
if not any(vars(args).values()):
|
||||
parser.print_help()
|
||||
exit(1)
|
||||
|
||||
# Initialize database connection parameters with None
|
||||
# Initialize database connection parameters
|
||||
db_host = db_port = db_name = db_user = db_password = None
|
||||
|
||||
# Determine the database connection parameters
|
||||
|
@ -150,32 +170,28 @@ if args.config_file:
|
|||
db_user = db_config['jdbc.default.username']
|
||||
db_password = db_config['jdbc.default.password']
|
||||
|
||||
if args.db_host:
|
||||
db_host = args.db_host
|
||||
# Override with command-line arguments if provided
|
||||
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:
|
||||
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
|
||||
# Check if all necessary parameters are available
|
||||
if not (db_host and db_port and db_name and db_user and db_password):
|
||||
error_message("Database connection parameters are incomplete.")
|
||||
exit(1)
|
||||
|
||||
# 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:
|
||||
|
||||
if args.update:
|
||||
update_typesettings(cursor, args.current_pluginid, args.next_pluginid)
|
||||
else:
|
||||
search_current_pluginid(cursor, args.current_pluginid, args.color, args.context_size)
|
||||
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close()
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
|
Loading…
Reference in New Issue