first revision

This commit is contained in:
Marcus Stoegbauer 2024-03-31 22:20:47 +02:00
parent a986a70800
commit e43dd9013c
5 changed files with 382 additions and 185 deletions

View File

@ -2,9 +2,9 @@ import os
import argparse import argparse
from userconfig.cfgfile import Conf from userconfig.cfgfile import Conf
from userconfig.tools import Debug from userconfig.tools import Debug
from userconfig.checks import classes_for_host
from userconfig import Userconfig from userconfig import Userconfig
import sys
import subprocess
def main(): def main():
parser = argparse.ArgumentParser(prog='userconfig', parser = argparse.ArgumentParser(prog='userconfig',
@ -18,39 +18,74 @@ def main():
dest='file', action='store') dest='file', action='store')
cmdline = parser.parse_args() cmdline = parser.parse_args()
debug = Debug() debug = Debug()
debug.set_verbose(cmdline.verbose) # debug.set_verbose(cmdline.verbose)
cfg = Conf(filename=cmdline.file, debug=debug) # cfg = Conf(filename=cmdline.file, debug=debug)
debug.set_verbose(4)
cfg = Conf(filename='/Users/lysis/userconfig2-test.conf', debug=debug)
# cfg = Conf(filename='/Users/lysis/etc/userconfig2.conf', debug=debug)
uc = Userconfig(cfg) uc = Userconfig(cfg)
cfg.debug.stdout(f"Verbose level is {cfg.debug.get_verbose()}", 1) cfg.debug.stdout(f"Verbose level is {cfg.debug.get_verbose()}", 1, 'STANDARD')
cfg.debug.stdout("================ main ===============", 1)
temp_classes = ""
for h in classes_for_host():
temp_classes = temp_classes + str(h) + ","
cfg.debug.stdout("+++ Current host is in classes %s" % temp_classes, 1)
configdir = cfg.get("configdir") configdir = cfg.get("configdir")
for d in os.listdir(configdir): # configdir is the root of the userconfig files
name = configdir+"/"+d # Directory structure:
cfg.debug.stdout("+++ Working in %s" % name, 1) # configdir/
if not os.path.isdir(name): # |-- userconfig2.conf
cfg.debug.stdout("--- %s is not a directory, skipping." % name, 3) # |-- package1/
continue # |- package.conf
elif d.startswith(".svn") or d.startswith(".git"): # |- 001_Arch_Linux/
cfg.debug.stdout("--- %s is .svn or .git, skipping." % name, 3) # |- file1
continue # |- file2
elif os.path.isfile(name+"/.ignore"): # |- 002_Host_glitters/
cfg.debug.stdout("--- %s contains file .ignore, skipping." % name, 3) # |- file1
continue # |- 003_all/
else: # |- file2
cfg.debug.stdout("+++ Processing files in %s" % name, 2) #
(destfiles, dirConfig) = uc.workdir(name) # Terminology:
if isinstance(destfiles, dict): # directories below configdir are packages, packages contain directories categorizing for which host/arch they
if len(destfiles.keys()) > 0: # are fitted, below that are files which are installed at the destination
cfg.debug.stdout("+++ Building %d files: %s" % (len(destfiles.keys()), destfiles.keys()), 3) #
uc.process_all_files(destfiles, dirConfig) # directory names in packages:
else: # [Number]_[category]_[value]
cfg.debug.stdout("--- No files found for %s, skipping." % name, 1) # Number: can have leading zeros for better sorting in directory structure, will be used for sorting and priority
# category: which kind of match we are looking for. currently: Arch for `uname -s`, Host for `hostname -s`
# value: optional, if category requires input, for example: Arch_Linux
# can be empty for example if category is all (no match needed, we want this always to be applied)
cfg.debug.stdout(f'configdir: {configdir}', 1)
for package in os.scandir(configdir):
if not package.is_dir():
cfg.debug.stdout(f'{package.path} is not a directory, skipping', 2, 'WARNING')
continue
if package.name in ['.svn', '.git']:
cfg.debug.stdout(f'{package.path} is a svn or git data directory, skipping', 2, 'WARNING')
if os.path.isfile(f'{package.path}/.ignore'):
cfg.debug.stdout(f'{package.path} contains .ignore, skipping', 2, 'WARNING')
continue
cfg.debug.stdout(f'============ start {package.path} ============', 2)
(category_dirs, dir_config) = uc.process_package_dir(package.path)
cfg.debug.stdout(f'Got categories: {category_dirs}', 2)
host_category_dirs = uc.filter_categories(category_dirs)
cfg.debug.stdout(f'Filtered categories for host: {host_category_dirs}', 2)
file_list = dict()
for c in host_category_dirs:
file_list = uc.process_category_dir(c, file_list)
cfg.debug.stdout(f'Found files: {file_list}', 2)
if len(file_list) and os.access(f'{package.path}/install.sh', os.X_OK):
cfg.debug.stdout(f'Execute {package.path}/install.sh', 2)
subprocess.call([f'{package.path}/install.sh'])
for file in file_list:
dest = f'{dir_config.get(section="Main", option="dest")}/{file}'
try:
comment_string = dir_config.get(section="Main", option="commentstring")
except ValueError:
cfg.debug.stdout(f'commentstring does not exist in config file {dir_config._cfgfiles}', 0, 'ERROR')
sys.exit(1)
# Make sure all directories for destination file exist
uc.create_destination_directories(dir_config.get(section="Main", option="dest"))
temp_filename = uc.build_file(file_list[file], dest, comment_string)
uc.copy_file(temp_filename, dest, comment_string)
cfg.debug.stdout(f'============ end {package.path} ============\n\n', 2)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

2
test.py Normal file
View File

@ -0,0 +1,2 @@
import cli
cli.main()

View File

@ -1,11 +1,10 @@
from userconfig.tools import get_config from userconfig.tools import get_config
import subprocess from userconfig.checks import check_class
from userconfig.checks import classes_for_host
import os import os
from userconfig.tools import diff, user_config_generated, backup_file, copy_file from userconfig.tools import diff, user_config_generated, backup_file, copy_file
import time import time
import re
import tempfile import tempfile
from pathlib import Path
class Userconfig: class Userconfig:
@ -14,160 +13,297 @@ class Userconfig:
def __init__(self, cfg): def __init__(self, cfg):
self._cfg = cfg self._cfg = cfg
def build_file(self, classfiles, destfile, commentstring): """ This is NEW """
"""open all classfiles, assemble them and write the contents into a tempfile def process_package_dir(self, package_dir):
returns the name of tempfile """
:param classfiles: Walk through package_dir, collect all directories inside, parse them according to our specs and return
:param destfile: a sorted list with entries (prio, category, value, path)
:param commentstring:
:return: str
"""
content = []
self._cfg.debug.stdout(f" ================ build_file {destfile} ===============", 1)
if commentstring != "":
self._cfg.debug.stdout(" +++ commentstring found, adding header.", 3)
content.append(commentstring + " " + self._cfg.get("stamp") + " " + time.strftime("%+") + "\n")
for f in classfiles: :param package_dir: root of package directory
self._cfg.debug.stdout(" +++ Merging %s." % f, 4) :return: list of tuples (prio, category, value, path), sorted with prio
fp = open(f, "r") """
self._cfg.debug.stdout(f'*** process package {package_dir}', 3)
package_config_file = f'{package_dir}/{self._cfg.get("configfile")}'
if not os.path.isfile(package_config_file):
self._cfg.debug.stdout(f'No config file {self._cfg.get("configfile")} in {package_dir}, skipping',
1, 'ERROR')
return None
dir_config = get_config(package_config_file, self._cfg)
if not dir_config:
self._cfg.debug.stdout(f'Cannot read config file {package_config_file}, skipping', 1, 'ERROR')
return None
classes = []
for category in os.scandir(package_dir):
if category.path == package_config_file:
continue
if not category.is_dir():
self._cfg.debug.stdout(f'{category.path} is not a directory, skipping', 3, 'WARNING')
continue
self._cfg.debug.stdout(f'****** process category {category.path}', 3)
content = category.name.split('_')
# Format: <number>_<category>_<value>
if len(content) == 3:
prio_string = content[0]
category_name = content[1]
value = content[2]
elif len(content) == 2:
prio_string = content[0]
category_name = content[1]
value = ''
else:
self._cfg.debug.stdout(f'Format of package directory {category.path} wrong, skipping', 1, 'ERROR')
continue
try:
prio = int(prio_string)
except ValueError:
self._cfg.debug.stdout(f'Cannot convert prio to integer ({category.path}, skipping', 1, 'ERROR')
continue
# self._cfg.debug.stdout(f'****** Got class: {(prio, category_name, value)}', 3)
classes.append((prio, category_name, value, category.path))
classes.sort(key=lambda k: k[0])
return classes, dir_config
def filter_categories(self, categories):
"""
Get classes list of tuples from process_package_dir and filter it for host running the command
:param categories: list of tuples from process_package_dir
:return: matching classes for this host
"""
ret = []
for c in categories:
if not c[1]:
self._cfg.debug.stdout(f'category not set for {c[3]}, skipping', 3, 'WARNING')
continue
if check_class(c):
ret.append(c)
return ret
def process_category_dir(self, category_dir_tuple, file_list):
"""
Walk through category_dir, collect all files
:param category_dir_tuple:
:param file_list:
:return:
"""
(prio, category, value, category_dir) = category_dir_tuple
self._cfg.debug.stdout(f'*** process category {category_dir}', 3)
for file in os.scandir(category_dir):
if file.name not in file_list:
file_list[file.name] = []
file_list[file.name].append(file.path)
return file_list
def build_file(self, files, destfile, commentstring):
"""
merge all files in files[] and write contents into a tempfile
:param files:
:param destfile:
:param commentstring:
:return: tempfile name
"""
content = []
self._cfg.debug.stdout(f'*** building file for {destfile}', 3)
if commentstring:
content.append(f'{commentstring} {self._cfg.get("stamp")} {time.strftime("%+")}\n')
for file in files:
self._cfg.debug.stdout(f'Merging {file}', 3)
fp = open(file, "r")
filecontent = fp.read() filecontent = fp.read()
fp.close() fp.close()
if commentstring == "": # if commentstring exists, add comment with category dir and filename
# look for stamp in content, replace with real stamp if commentstring:
if re.search(re.escape(self._cfg.get("stampreplace")), filecontent): content.append(f'{commentstring} {"/".join(file.split("/")[-2:])}')
self._cfg.debug.stdout(" +++ commentstring empty, replacing stamp in file", 3)
filecontent = re.sub(re.escape(self._cfg.get("stampreplace")), self._cfg.get("stamp"),
filecontent)
content.append(filecontent) content.append(filecontent)
(tempfd, tempfilename) = tempfile.mkstemp(prefix=os.path.basename(destfile), dir="/tmp") (tempfd, tempfilename) = tempfile.mkstemp(prefix=os.path.basename(destfile), dir="/tmp")
try: try:
fp = os.fdopen(tempfd, "w") fp = os.fdopen(tempfd, "w")
except Exception as e: except Exception as e:
self._cfg.debug.stderr(f"Cannot write to temporary file {tempfilename}: {e}") self._cfg.debug.stderr(f"Cannot write to temporary file {tempfilename}: {e}", 0, 'ERROR')
os.remove(tempfilename) os.remove(tempfilename)
return False return False
self._cfg.debug.stdout(" +++ Writing merged files into tempfile %s." % tempfilename, 3) self._cfg.debug.stdout(f'Writing merged files into tempfile {tempfilename}', 3)
for block in content: for block in content:
fp.write(block) fp.write(block)
fp.write("\n") fp.write("\n")
fp.close() fp.close()
self._cfg.debug.stdout(f" ================ done: build_file {destfile} ===============", 1)
return tempfilename return tempfilename
def process_all_files(self, destfiles, dir_config): def copy_file(self, temp_filename, dest_filename, commentstring):
"""processes all files in destfiles, generate files from classes, compare and copy if necessary""" if diff(dest_filename, temp_filename, commentstring, self._cfg):
self._cfg.debug.stdout(" ================ process_all_files ===============", 1) self._cfg.debug.stdout(f"File {dest_filename} has changed", 0, 'NOTICE')
for df in destfiles.keys(): if not user_config_generated(dest_filename, self._cfg):
self._cfg.debug.stdout(" ??? Processing source files for %s." % df, 2) self._cfg.debug.stdout(f"{dest_filename} not generated by userconfig, backing up.", 3)
if not os.path.exists(os.path.dirname(df)): backup_file(dest_filename, self._cfg)
self._cfg.debug.stdout(" +++ Directory %s does not exist, creating" % os.path.dirname(df), 1) self._cfg.debug.stdout(f"Copy {temp_filename} to {dest_filename}", 0, 'NOTICE')
os.mkdir(os.path.dirname(df)) copy_file(temp_filename, dest_filename, self._cfg)
if not os.path.isdir(os.path.dirname(df)): self._cfg.debug.stdout(f"Removing temporary file {temp_filename}", 3)
self._cfg.debug.stdout(f" --- Destination directory {os.path.dirname(df)} does not exist, skipping.", os.remove(temp_filename)
1)
return False
# assemble file to tmp
commentstring = ""
if dir_config.check(section="Main", option="commentstring"):
commentstring = dir_config.get(section="Main", option="commentstring")
self._cfg.debug.stdout(" +++ Found commentstring %s in %s" % (commentstring, df), 3)
tempfilename = self.build_file(destfiles[df], df, commentstring) def create_destination_directories(self, dest_directory):
if not tempfilename: self._cfg.debug.stdout(f'*** Creating {dest_directory} if needed', 3)
self._cfg.debug.stdout(" --- Error while creating temp file for %s, skipping." % df, 1) path = Path(dest_directory)
continue if not path.exists():
self._cfg.debug.stdout(" +++ Merged files %s for %s into %s" % (str(destfiles[df]), df, tempfilename), 2) path.mkdir(parents=True)
# diff assembled file and config file # def build_file_old(self, classfiles, destfile, commentstring):
if diff(df, tempfilename, commentstring, self._cfg): # """open all classfiles, assemble them and write the contents into a tempfile
self._cfg.debug.stdout("File %s has changed" % df, 0) # returns the name of tempfile
if not user_config_generated(df, self._cfg): # :param classfiles:
self._cfg.debug.stdout(" +++ %s not generated by userconfig, backing up." % df, 2) # :param destfile:
# file not generated from userconfig -> back up # :param commentstring:
backup_file(df, self._cfg) # :return: str
# copy tmp file to real location # """
self._cfg.debug.stdout("Copy %s to %s." % (tempfilename, df), 0) # content = []
copy_file(tempfilename, df, self._cfg) # self._cfg.debug.stdout(f" ================ build_file {destfile} ===============", 1)
# remove tmp # if commentstring != "":
self._cfg.debug.stdout(" +++ Removing temporary file %s." % tempfilename, 2) # self._cfg.debug.stdout(" +++ commentstring found, adding header.", 3)
os.remove(tempfilename) # content.append(commentstring + " " + self._cfg.get("stamp") + " " + time.strftime("%+") + "\n")
self._cfg.debug.stdout(" ================ process_all_files ===============", 1) #
# for f in classfiles:
# self._cfg.debug.stdout(" +++ Merging %s." % f, 4)
# fp = open(f, "r")
# filecontent = fp.read()
# fp.close()
# if commentstring == "":
# # look for stamp in content, replace with real stamp
# if re.search(re.escape(self._cfg.get("stampreplace")), filecontent):
# self._cfg.debug.stdout(" +++ commentstring empty, replacing stamp in file", 3)
# filecontent = re.sub(re.escape(self._cfg.get("stampreplace")), self._cfg.get("stamp"),
# filecontent)
# content.append(filecontent)
#
# (tempfd, tempfilename) = tempfile.mkstemp(prefix=os.path.basename(destfile), dir="/tmp")
#
# try:
# fp = os.fdopen(tempfd, "w")
# except Exception as e:
# self._cfg.debug.stderr(f"Cannot write to temporary file {tempfilename}: {e}")
# os.remove(tempfilename)
# return False
# self._cfg.debug.stdout(" +++ Writing merged files into tempfile %s." % tempfilename, 3)
# for block in content:
# fp.write(block)
# fp.write("\n")
# fp.close()
# self._cfg.debug.stdout(f" ================ done: build_file {destfile} ===============", 1)
# return tempfilename
def workconf(self, directory, depth=2): # def process_all_files(self, destfiles, dir_config):
"""walks through directory, collecting all filenames, returns list of all filenames""" # """processes all files in destfiles, generate files from classes, compare and copy if necessary"""
dirs = os.listdir(directory) # self._cfg.debug.stdout(" ================ process_all_files ===============", 1)
ret = [] # for df in destfiles.keys():
self._cfg.debug.stdout(f" ================ workconf {directory} ===============", 1) # self._cfg.debug.stdout(" ??? Processing source files for %s." % df, 2)
for d in dirs: # if not os.path.exists(os.path.dirname(df)):
name = directory + "/" + d # self._cfg.debug.stdout(" +++ Directory %s does not exist, creating" % os.path.dirname(df), 1)
if os.path.isdir(name): # os.mkdir(os.path.dirname(df))
self.workconf(name, depth + 1) # if not os.path.isdir(os.path.dirname(df)):
if name.endswith(".swp"): # self._cfg.debug.stdout(f" --- Destination directory {os.path.dirname(df)} does not exist, skipping.",
continue # 1)
if d == ".svn": # return False
continue # # assemble file to tmp
ret.append(name) # commentstring = ""
self._cfg.debug.stdout(" +++ Found file %s in directory %s" % (name, directory), 4) # if dir_config.check(section="Main", option="commentstring"):
self._cfg.debug.stdout(f" ================ done: workconf {directory} ===============", 1) # commentstring = dir_config.get(section="Main", option="commentstring")
return ret # self._cfg.debug.stdout(" +++ Found commentstring %s in %s" % (commentstring, df), 3)
#
# tempfilename = self.build_file(destfiles[df], df, commentstring)
# if not tempfilename:
# self._cfg.debug.stdout(" --- Error while creating temp file for %s, skipping." % df, 1)
# continue
# self._cfg.debug.stdout(" +++ Merged files %s for %s into %s" % (str(destfiles[df]), df, tempfilename), 2)
#
# # diff assembled file and config file
# if diff(df, tempfilename, commentstring, self._cfg):
# self._cfg.debug.stdout("File %s has changed" % df, 0)
# if not user_config_generated(df, self._cfg):
# self._cfg.debug.stdout(" +++ %s not generated by userconfig, backing up." % df, 2)
# # file not generated from userconfig -> back up
# backup_file(df, self._cfg)
# # copy tmp file to real location
# self._cfg.debug.stdout("Copy %s to %s." % (tempfilename, df), 0)
# copy_file(tempfilename, df, self._cfg)
# # remove tmp
# self._cfg.debug.stdout(" +++ Removing temporary file %s." % tempfilename, 2)
# os.remove(tempfilename)
# self._cfg.debug.stdout(" ================ process_all_files ===============", 1)
def workdir(self, directory): # def workconf(self, directory, depth=2):
"""walks through all host classes, checking if the classes directory exists in directory # """walks through directory, collecting all filenames, returns list of all filenames"""
then collect all filenames within this directory and return a dict of all files for this # dirs = os.listdir(directory)
directory # ret = []
""" # self._cfg.debug.stdout(f" ================ workconf {directory} ===============", 1)
self._cfg.debug.stdout(f" ================ workdir {directory} ===============", 1) # for d in dirs:
# skip directory if no CONFIGFILE present # name = directory + "/" + d
if not os.path.isfile(directory+"/"+self._cfg.get("configfile")): # if os.path.isdir(name):
self._cfg.debug.stdout(f' --- No file {self._cfg.get("configfile")} in {directory}, skipping.', 1) # self.workconf(name, depth + 1)
return {}, None # if name.endswith(".swp"):
# continue
# if d == ".svn":
# continue
# ret.append(name)
# self._cfg.debug.stdout(" +++ Found file %s in directory %s" % (name, directory), 4)
# self._cfg.debug.stdout(f" ================ done: workconf {directory} ===============", 1)
# return ret
# get config file for directory # def workdir(self, directory):
dir_config = get_config(directory + "/" + self._cfg.get("configfile"), self._cfg) # """walks through all host classes, checking if the classes directory exists in directory
if not dir_config: # then collect all filenames within this directory and return a dict of all files for this
self._cfg.debug.stdout(f' --- Cannot read config file {self._cfg.get("configfile")} in {directory}, ' # directory
f'skipping.', 1) # """
return {}, None # self._cfg.debug.stdout(f" ================ workdir {directory} ===============", 1)
# # skip directory if no CONFIGFILE present
destdir = dir_config.get(section="Main", option="dest") # if not os.path.isfile(directory+"/"+self._cfg.get("configfile")):
# destfiles is a dict of all files that will be created from the classes config # self._cfg.debug.stdout(f' --- No file {self._cfg.get("configfile")} in {directory}, skipping.', 1)
# key is the destination filename, values are all classes filenames that are used to # return {}, None
# build the file #
destfiles = {} # # get config file for directory
try: # dir_config = get_config(directory + "/" + self._cfg.get("configfile"), self._cfg)
reverse_sort = dir_config.get(section="Main", option="reverse", boolean=True) # if not dir_config:
except ValueError: # self._cfg.debug.stdout(f' --- Cannot read config file {self._cfg.get("configfile")} in {directory}, '
reverse_sort = False # f'skipping.', 1)
self._cfg.debug.stdout(f' +++ reverse_sort is {reverse_sort}', 3) # return {}, None
if os.access(directory + "/install.sh", os.X_OK): #
subprocess.call([directory + "/install.sh"]) # destdir = dir_config.get(section="Main", option="dest")
# # destfiles is a dict of all files that will be created from the classes config
# walk through all know classes in directory and find filenames # # key is the destination filename, values are all classes filenames that are used to
for h in classes_for_host(reverse_sort): # # build the file
# build classes directory # destfiles = {}
if h[0] != "": # try:
classdir = directory+"/"+h[0]+"_"+h[1] # reverse_sort = dir_config.get(section="Main", option="reverse", boolean=True)
else: # except ValueError:
classdir = directory+"/"+h[1] # reverse_sort = False
self._cfg.debug.stdout(" ??? Looking for directory %s." % classdir, 4) # self._cfg.debug.stdout(f' +++ reverse_sort is {reverse_sort}', 3)
# if class directory exists # if os.access(directory + "/install.sh", os.X_OK):
if os.path.isdir(classdir): # subprocess.call([directory + "/install.sh"])
self._cfg.debug.stdout(" +++ Found directory %s, getting files." % classdir, 4) #
# get list of files within this class directory # # walk through all know classes in directory and find filenames
tempfiles = self.workconf(classdir) # for h in classes_for_host(reverse_sort):
self._cfg.debug.stdout(" +++ Got %d files: %s." % (len(tempfiles), str(tempfiles)), 4) # # build classes directory
# put files into dict # if h[0] != "":
for f in tempfiles: # classdir = directory+"/"+h[0]+"_"+h[1]
destname = destdir+os.path.basename(f) # destination filename # else:
if destname not in destfiles: # classdir = directory+"/"+h[1]
destfiles[destname] = [] # self._cfg.debug.stdout(" ??? Looking for directory %s." % classdir, 4)
destfiles[destname].append(f) # append each file to dict # # if class directory exists
self._cfg.debug.stdout(f" +++ Added file to {destname}, now {len(destfiles[destname])} files: " # if os.path.isdir(classdir):
f"{destfiles[destname]}", 4) # self._cfg.debug.stdout(" +++ Found directory %s, getting files." % classdir, 4)
# # get list of files within this class directory
self._cfg.debug.stdout(" === workdir: %s, Files: %s" % (directory, str(destfiles)), 3) # tempfiles = self.workconf(classdir)
self._cfg.debug.stdout(f" ================ done: workdir {directory} ===============", 1) # self._cfg.debug.stdout(" +++ Got %d files: %s." % (len(tempfiles), str(tempfiles)), 4)
return destfiles, dir_config # # put files into dict
# for f in tempfiles:
# destname = destdir+os.path.basename(f) # destination filename
# if destname not in destfiles:
# destfiles[destname] = []
# destfiles[destname].append(f) # append each file to dict
# self._cfg.debug.stdout(f" +++ Added file to {destname}, now {len(destfiles[destname])} files: "
# f"{destfiles[destname]}", 4)
#
# self._cfg.debug.stdout(" === workdir: %s, Files: %s" % (directory, str(destfiles)), 3)
# self._cfg.debug.stdout(f" ================ done: workdir {directory} ===============", 1)
# return destfiles, dir_config

View File

@ -1,19 +1,24 @@
import platform import platform
def get_short_hostname(): def get_hostname():
hostname = platform.node() hostname = platform.node()
if hostname.count("."): if hostname.count("."):
hostname = hostname.split(".")[0] hostname = hostname.split(".")[0]
return hostname return hostname
def classes_for_host(reverse=False): def get_arch():
classes = [(0, "", "header"), return platform.system()
(1000, "", "footer"),
(998, "", "all"),
(800, "Arch", platform.system()), def check_class(class_tuple):
(10, "Host", get_short_hostname()) (prio, category, value, path) = class_tuple
] if category == 'Arch':
classes.sort(key=lambda k: k[0], reverse=reverse) return get_arch() == value
return [(k[1], k[2]) for k in classes] elif category == 'Host':
return get_hostname() == value
elif value == '': # if value is empty, we cannot filter anything, so it matches always
return True
else:
return False

View File

@ -9,6 +9,19 @@ import shutil
class Debug: class Debug:
_verbose = 0 _verbose = 0
_COLOR_RED = '\033[91m'
_COLOR_BLUE = '\33[34m'
_COLOR_GREEN = '\33[32m'
_COLOR_YELLOW = '\033[93m'
_COLOR_END = '\33[0m'
_FORMAT = { 'STANDARD': '',
'ERROR': f'{_COLOR_RED}ERROR:{_COLOR_END} ',
'NOTICE': f'{_COLOR_BLUE}NOTICE:{_COLOR_END} ',
'WARNING': f'{_COLOR_YELLOW}WARNING:{_COLOR_END} ',
'SUCCESS': f'{_COLOR_GREEN}SUCCESS:{_COLOR_END} '
}
def __init__(self, verbose=0): def __init__(self, verbose=0):
self.set_verbose(verbose) self.set_verbose(verbose)
@ -21,13 +34,19 @@ class Debug:
def get_verbose(self): def get_verbose(self):
return self._verbose return self._verbose
def stdout(self, out, level=0): def stdout(self, out, verbose_level=0, category='STANDARD'):
if self._verbose >= level: if self._verbose >= verbose_level:
print(out) if category in self._FORMAT:
print(f'{self._FORMAT[category]}{out}')
else:
print(f'[category {category} unknown]:{out}')
def stderr(self, out, level=0): def stderr(self, out, verbose_level=0, category='STANDARD'):
if self._verbose >= level: if self._verbose >= verbose_level:
print(str(out)+"\n", file=sys.stderr) if category in self._FORMAT:
print(f'{self._FORMAT[category]}{out}', file=sys.stderr)
else:
print(f'[category {category} unknown]:{out}', file=sys.stderr)
def get_config(filename, cfg): def get_config(filename, cfg):