Add color to sysout

This commit is contained in:
Christoph Haas 2018-09-05 22:25:54 +02:00
parent f793ba7bb6
commit d7a19bfb59

View File

@ -13,22 +13,32 @@ import grp
CONFIG_SYNC_VERSION = "1.0.0" CONFIG_SYNC_VERSION = "1.0.0"
CONFIG_SYNC_FILE = "/etc/configsync.conf" CONFIG_SYNC_FILE = "/etc/configsync.conf"
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def check_dependencies(): def check_dependencies():
status = True status = True
try: try:
subprocess.call(["git", "version"], stdout=subprocess.DEVNULL) subprocess.call(["git", "version"], stdout=subprocess.DEVNULL)
except OSError: except OSError:
status = False status = False
print("git cannot be found on your system!") print(bcolors.FAIL + "git cannot be found on your system!" + bcolors.ENDC)
print("Install git: pacman -S git") print("Install git: pacman -S git")
return status return status
def print_splash(): def print_splash():
print("---=== CONFIG-SYNC ===---") print(bcolors.HEADER + "---=== CONFIG-SYNC ===---" + bcolors.ENDC)
print("Version: " + CONFIG_SYNC_VERSION) print("Version: " + CONFIG_SYNC_VERSION)
print() print()
print("---=== USAGE ===---") print(bcolors.HEADER + "---=== USAGE ===---" + bcolors.ENDC)
print("configsync init") print("configsync init")
print("configsync add <file path>") print("configsync add <file path>")
print("configsync remove <file path>") print("configsync remove <file path>")
@ -38,7 +48,7 @@ def print_splash():
def validate_or_create_config(config): def validate_or_create_config(config):
if not os.path.exists(CONFIG_SYNC_FILE): if not os.path.exists(CONFIG_SYNC_FILE):
print("Creating default configuration file: " + CONFIG_SYNC_FILE) print(bcolors.OKBLUE + "Creating default configuration file: " + CONFIG_SYNC_FILE + bcolors.ENDC)
config['DEFAULT'] = {} config['DEFAULT'] = {}
config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] = "/opt/configsync/storage" config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] = "/opt/configsync/storage"
config['DEFAULT']['INITIALIZED'] = "" config['DEFAULT']['INITIALIZED'] = ""
@ -64,44 +74,44 @@ def update_config(config):
try: try:
config.write(open(CONFIG_SYNC_FILE, 'w')) config.write(open(CONFIG_SYNC_FILE, 'w'))
except PermissionError as e: except PermissionError as e:
print("Unable to write config file! Error: " + e.strerror) print(bcolors.FAIL + "Unable to write config file! Error: " + e.strerror + bcolors.ENDC)
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print("Unable to write config file! Error: " + str(e)) print(bcolors.FAIL + "Unable to write config file! Error: " + str(e) + bcolors.ENDC)
sys.exit(1) sys.exit(1)
def init_dialog(): def init_dialog():
config = get_config() config = get_config()
print("Welcome to CONFIG-SYNC!") print(bcolors.HEADER + "---=== Welcome to CONFIG-SYNC! ===---" + bcolors.ENDC)
print() print()
if config['DEFAULT']['INITIALIZED']: if config['DEFAULT']['INITIALIZED']:
reinitialize = input("WARNING: CONFIG-SYNC has already been initialized! Do you really want to change the configuration? [y/N]: ") reinitialize = input(bcolors.WARNING + "WARNING: CONFIG-SYNC has already been initialized! Do you really want to change the configuration? [y/N]: " + bcolors.ENDC)
if not reinitialize or reinitialize != "y": if not reinitialize or reinitialize != "y":
print("Skipping new initialization!") print("Skipping new initialization!")
sys.exit(0) sys.exit(0)
local_path = input("Enter the local storage directory for configuration files [" + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "]: ") local_path = input(bcolors.OKBLUE + "Enter the local storage directory for configuration files [" + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "]: " + bcolors.ENDC)
if not local_path: if not local_path:
local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']
config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] = local_path config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] = local_path
remote_repo = input("Enter the remote repository url [" + config['GIT']['REMOTE_REPOSITORY'] + "]: ") remote_repo = input(bcolors.OKBLUE + "Enter the remote repository url [" + config['GIT']['REMOTE_REPOSITORY'] + "]: " + bcolors.ENDC)
if not remote_repo: if not remote_repo:
remote_repo = config['GIT']['REMOTE_REPOSITORY'] remote_repo = config['GIT']['REMOTE_REPOSITORY']
config['GIT']['REMOTE_REPOSITORY'] = remote_repo config['GIT']['REMOTE_REPOSITORY'] = remote_repo
git_ssh_key = input("Enter the path to the ssh key to use [" + config['GIT']['SSHKEY'] + "]: ") git_ssh_key = input(bcolors.OKBLUE + "Enter the path to the ssh key to use [" + config['GIT']['SSHKEY'] + "]: " + bcolors.ENDC)
if not git_ssh_key: if not git_ssh_key:
git_ssh_key = config['GIT']['SSHKEY'] git_ssh_key = config['GIT']['SSHKEY']
config['GIT']['SSHKEY'] = git_ssh_key config['GIT']['SSHKEY'] = git_ssh_key
git_user = input("Enter the git user name (displayname) [" + config['GIT']['USER'] + "]: ") git_user = input(bcolors.OKBLUE + "Enter the git user name (displayname) [" + config['GIT']['USER'] + "]: " + bcolors.ENDC)
if not git_user: if not git_user:
git_user = config['GIT']['USER'] git_user = config['GIT']['USER']
config['GIT']['USER'] = git_user config['GIT']['USER'] = git_user
git_email = input("Enter the git user email address [" + config['GIT']['EMAIL'] + "]: ") git_email = input(bcolors.OKBLUE + "Enter the git user email address [" + config['GIT']['EMAIL'] + "]: " + bcolors.ENDC)
if not git_email: if not git_email:
git_email = config['GIT']['EMAIL'] git_email = config['GIT']['EMAIL']
config['GIT']['EMAIL'] = git_email config['GIT']['EMAIL'] = git_email
@ -115,19 +125,19 @@ def create_initialization_file(path):
with open(path + "/configsync.info", mode='w') as file: with open(path + "/configsync.info", mode='w') as file:
file.write('CONFIG-SYNC Repo initialized: %s.\n' % ( datetime.datetime.now())) file.write('CONFIG-SYNC Repo initialized: %s.\n' % ( datetime.datetime.now()))
except PermissionError as e: except PermissionError as e:
print("Unable to write initialization file! Error: " + e.strerror) print(bcolors.FAIL + "Unable to write initialization file! Error: " + e.strerror + bcolors.ENDC)
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print("Unable to write initialization file! Error: " + str(e)) print(bcolors.FAIL + "Unable to write initialization file! Error: " + str(e) + bcolors.ENDC)
sys.exit(1) sys.exit(1)
try: try:
open(path + "/configsync.db", mode='a').close() open(path + "/configsync.db", mode='a').close()
except PermissionError as e: except PermissionError as e:
print("Unable to write database file! Error: " + e.strerror) print(bcolors.FAIL + "Unable to write database file! Error: " + e.strerror + bcolors.ENDC)
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print("Unable to write database file! Error: " + str(e)) print(bcolors.FAIL + "Unable to write database file! Error: " + str(e) + bcolors.ENDC)
sys.exit(1) sys.exit(1)
def add_file_to_db(file_path): def add_file_to_db(file_path):
@ -143,10 +153,10 @@ def add_file_to_db(file_path):
with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", mode='a') as file: with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", mode='a') as file:
file.write('%s\n' % (file_path)) file.write('%s\n' % (file_path))
except PermissionError as e: except PermissionError as e:
print("Unable to write db file! Error: " + e.strerror) print(bcolors.FAIL + "Unable to write db file! Error: " + e.strerror + bcolors.ENDC)
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print("Unable to write db file! Error: " + str(e)) print(bcolors.FAIL + "Unable to write db file! Error: " + str(e) + bcolors.ENDC)
sys.exit(1) sys.exit(1)
def delete_file_from_db(file_path): def delete_file_from_db(file_path):
@ -160,10 +170,10 @@ def delete_file_from_db(file_path):
search.write(line.rstrip() + "\n") search.write(line.rstrip() + "\n")
search.truncate() search.truncate()
except PermissionError as e: except PermissionError as e:
print("Unable to write db file! Error: " + e.strerror) print(bcolors.FAIL + "Unable to write db file! Error: " + e.strerror + bcolors.ENDC)
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print("Unable to write db file! Error: " + str(e)) print(bcolors.FAIL + "Unable to write db file! Error: " + str(e) + bcolors.ENDC)
sys.exit(1) sys.exit(1)
def setup_git_ssh_environment(): def setup_git_ssh_environment():
@ -208,8 +218,8 @@ def git_pull(path):
def git_check_status(status): def git_check_status(status):
config = get_config() config = get_config()
if not status: if not status:
print("FATAL: Git operation failed! Repository has to be recovered manually!") print(bcolors.FAIL + bcolors.BOLD + "FATAL: Git operation failed! Repository has to be recovered manually!" + bcolors.ENDC)
print("FATAL: Repository path: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']) print(bcolors.FAIL + "FATAL: Repository path: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + bcolors.ENDC)
sys.exit(1) sys.exit(1)
def init_local_repo(): def init_local_repo():
@ -217,11 +227,11 @@ def init_local_repo():
print("Setting up local repository.") print("Setting up local repository.")
if not os.path.exists(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']): if not os.path.exists(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']):
print("Creating new directory: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']) print(bcolors.OKBLUE + "Creating new directory: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + bcolors.ENDC)
try: try:
os.makedirs(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']) os.makedirs(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
except OSError as e: except OSError as e:
print("Failed to create local repository directory: " + e.strerror) print(bcolors.FAIL + "Failed to create local repository directory: " + e.strerror + bcolors.ENDC)
sys.exit(1) sys.exit(1)
# init git repo # init git repo
@ -238,20 +248,23 @@ def init_local_repo():
git_check_status(git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'], "configsync initialized")) git_check_status(git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'], "configsync initialized"))
git_check_status(git_pull(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])) git_check_status(git_pull(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']))
print(bcolors.OKGREEN + "CONFIG-SYNC initialization successfull!" + bcolors.ENDC)
print(bcolors.OKBLUE + "You can now use CONFIG-SYNC to keep your config files up to date." + bcolors.ENDC)
def add_file(filepath): def add_file(filepath):
config = get_config() config = get_config()
abs_path = os.path.abspath(filepath) abs_path = os.path.abspath(filepath)
if not os.path.exists(abs_path): if not os.path.exists(abs_path):
print("Invalid file, skipping!") print(bcolors.WARNING + "Invalid file, skipping!" + bcolors.ENDC)
sys.exit(1) sys.exit(1)
else: else:
print("Adding '" + abs_path + "' to CONFIG-SYNC...") print(bcolors.OKBLUE + "Adding '" + abs_path + "' to CONFIG-SYNC..." + bcolors.ENDC)
local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
if os.path.exists(local_path): if os.path.exists(local_path):
print("File is already registered to CONFIG-SYNC, skipping!") print(bcolors.WARNING + "File is already registered to CONFIG-SYNC, skipping!" + bcolors.ENDC)
sys.exit(1) sys.exit(1)
else: else:
target_directory = os.path.abspath(os.path.join(local_path, os.pardir)) target_directory = os.path.abspath(os.path.join(local_path, os.pardir))
@ -269,10 +282,10 @@ def add_file(filepath):
with open(local_path + ".cfsinfo", mode='w') as file: with open(local_path + ".cfsinfo", mode='w') as file:
file.write('%s;%s;%s;%s;%s' % (file_permissions, file_owner, file_group, file_owner_name, file_group_name)) file.write('%s;%s;%s;%s;%s' % (file_permissions, file_owner, file_group, file_owner_name, file_group_name))
except PermissionError as e: except PermissionError as e:
print("Unable to write stat file! Error: " + e.strerror) print(bcolors.FAIL + "Unable to write stat file! Error: " + e.strerror + bcolors.ENDC)
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print("Unable to write stat file! Error: " + str(e)) print(bcolors.FAIL + "Unable to write stat file! Error: " + str(e) + bcolors.ENDC)
sys.exit(1) sys.exit(1)
shutil.copy2(abs_path, local_path) shutil.copy2(abs_path, local_path)
@ -283,8 +296,8 @@ def add_file(filepath):
add_file_to_db(abs_path) add_file_to_db(abs_path)
print("File added to CONFIG-SYNC!") print(bcolors.OKGREEN + "File added to CONFIG-SYNC!" + bcolors.ENDC)
print("Use configsync store to push the file to the remote repository!") print(bcolors.OKBLUE + "Use configsync store to push the file to the remote repository!" + bcolors.ENDC)
def remove_file(filepath): def remove_file(filepath):
config = get_config() config = get_config()
@ -293,19 +306,19 @@ def remove_file(filepath):
local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
if not os.path.exists(local_path): if not os.path.exists(local_path):
print("File not registered to CONFIG-SYNC, skipping!") print(bcolors.WARNING + "File not registered to CONFIG-SYNC, skipping!" + bcolors.ENDC)
sys.exit(1) sys.exit(1)
else: else:
print("Removing '" + abs_path + "' from CONFIG-SYNC...") print(bcolors.OKBLUE + "Removing '" + abs_path + "' from CONFIG-SYNC..." + bcolors.ENDC)
target_directory = os.path.abspath(os.path.join(abs_path, os.pardir)) target_directory = os.path.abspath(os.path.join(abs_path, os.pardir))
if not os.path.exists(target_directory): if not os.path.exists(target_directory):
os.makedirs(target_directory) os.makedirs(target_directory)
if os.path.exists(abs_path): if os.path.exists(abs_path):
confirmed = input("Do you really want to override the local file '" + abs_path + "'? [y/N]: ") confirmed = input(bcolors.OKBLUE + "Do you really want to override the local file '" + abs_path + "'? [y/N]: " + bcolors.ENDC)
if not confirmed or confirmed != "y": if not confirmed or confirmed != "y":
print("Skipping removal process!") print(bcolors.WARNING + "Skipping removal process!" + bcolors.ENDC)
sys.exit(0) sys.exit(0)
else: else:
os.remove(abs_path) os.remove(abs_path)
@ -324,14 +337,18 @@ def remove_file(filepath):
delete_file_from_db(abs_path) delete_file_from_db(abs_path)
print("File removed from CONFIG-SYNC!") print(bcolors.OKGREEN + "File removed from CONFIG-SYNC!" + bcolors.ENDC)
print("Use configsync store to push the file to the remote repository!") print(bcolors.OKBLUE + "Use configsync store to push the file to the remote repository!" + bcolors.ENDC)
def store(): def store():
config = get_config() config = get_config()
setup_git_ssh_environment() setup_git_ssh_environment()
git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']) git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
print(bcolors.OKGREEN + "CONFIG-SYNC store successfull!" + bcolors.ENDC)
print(bcolors.OKBLUE + "You can now restore the configuration on your other systems." + bcolors.ENDC)
def update_local_metadata(): def update_local_metadata():
config = get_config() config = get_config()
with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", "r") as search: with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", "r") as search:
@ -340,7 +357,7 @@ def update_local_metadata():
local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
if not os.path.exists(local_path): if not os.path.exists(local_path):
print("Invalid file in database, skipping!") print(bcolors.WARNING + "Invalid file in database, skipping! (" + abs_path + ")" + bcolors.ENDC)
else: else:
with open(local_path + ".cfsinfo", "r") as metadata_file: with open(local_path + ".cfsinfo", "r") as metadata_file:
metadata_string = metadata_file.readline().rstrip() metadata_string = metadata_file.readline().rstrip()
@ -360,9 +377,9 @@ def restore():
update_local_metadata() update_local_metadata()
confirmed = input("Do you really want to restore files from the repository? Local files will be overwritten! [y/N]: ") confirmed = input(bcolors.WARNING + "Do you really want to restore files from the repository? Local files will be overwritten! [y/N]: " + bcolors.ENDC)
if not confirmed or confirmed != "y": if not confirmed or confirmed != "y":
print("Skipping restore process!") print(bcolors.WARNING + "Skipping restore process!" + bcolors.ENDC)
sys.exit(0) sys.exit(0)
else: else:
with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", "r") as search: with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", "r") as search:
@ -371,7 +388,7 @@ def restore():
local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
if not os.path.exists(local_path): if not os.path.exists(local_path):
print("Invalid file, skipping!") print(bcolors.WARNING + "Invalid file, skipping!" + bcolors.ENDC)
else: else:
target_directory = os.path.abspath(os.path.join(abs_path, os.pardir)) target_directory = os.path.abspath(os.path.join(abs_path, os.pardir))
if not os.path.exists(target_directory): if not os.path.exists(target_directory):
@ -388,6 +405,9 @@ def restore():
os.chown(abs_path, file_owner, file_group, follow_symlinks=False) os.chown(abs_path, file_owner, file_group, follow_symlinks=False)
print(bcolors.OKGREEN + "CONFIG-SYNC restore successfull!" + bcolors.ENDC)
print(bcolors.OKBLUE + "Configuration files have been updated. A reboot might be required." + bcolors.ENDC)
def main(argv): def main(argv):
if not check_dependencies(): if not check_dependencies():
sys.exit(1) sys.exit(1)