pyuserconfig/userconfig.py

261 lines
9.7 KiB
Python
Raw Normal View History

2019-06-12 23:32:05 +02:00
#!/usr/bin/env python3
2013-01-11 00:35:09 +01:00
# encoding: utf-8
#
"""
userconfig.py
Created by Marcus Stoegbauer on 2013-01-10.
"""
import sys
import os
2013-01-12 17:17:12 +01:00
import tempfile
2013-01-12 23:04:52 +01:00
import re
import getopt
import time
import subprocess
2013-01-12 23:04:52 +01:00
#
2013-01-13 22:49:18 +01:00
import Userconfig.cfgfile as cfgfile
2019-06-12 23:32:05 +02:00
from Userconfig.checks import Checks
2013-01-13 22:49:18 +01:00
import Userconfig.Tools as Tools
2013-01-13 00:21:20 +01:00
debug = Tools.Debug()
2013-01-11 00:35:09 +01:00
2019-06-12 23:32:05 +02:00
classchecks = Checks()
2013-01-12 23:04:52 +01:00
cfg = cfgfile.Conf()
2019-06-12 23:32:05 +02:00
help_message = """
2013-01-12 23:04:52 +01:00
-h help
-v verbose level (multiple v for higher level)
2013-01-12 23:04:52 +01:00
-c userconfig.cfg config file
"""
2019-06-12 23:32:05 +02:00
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
2013-01-11 00:35:09 +01:00
2013-01-12 23:04:52 +01:00
def workconf(directory, depth=2):
2019-06-12 23:32:05 +02:00
"""walks through directory, collecting all filenames, returns list of all filenames"""
dirs = os.listdir(directory)
ret = []
debug.debug(" ================ workconf ===============", 1)
debug.debug(" Finding files in directory %s." % directory, 4)
2019-06-12 23:32:05 +02:00
for d in dirs:
name = directory+"/"+d
if os.path.isdir(name):
# fixme: create name if it does not exist
workconf(name, depth+1)
if name.endswith(".swp"):
continue
if d == ".svn":
continue
ret.append(name)
debug.debug(" +++ Found file %s in directory %s" % (name, directory), 4)
debug.debug(" ================ workconf ===============", 1)
2019-06-12 23:32:05 +02:00
return ret
2013-01-12 17:17:12 +01:00
def workdir(directory):
2019-06-12 23:32:05 +02:00
"""walks through all host classes, checking if the classes directory exists in directory
then collect all filenames within this directory and return a dict of all files for this
directory
"""
debug.debug(" ================ workdir ===============", 1)
debug.debug(" Working on directory %s" % directory, 3)
2019-06-12 23:32:05 +02:00
# skip directory if no CONFIGFILE present
if not os.path.isfile(directory+"/"+cfg.get("Main", "configfile")):
debug.debug(" --- No %s in %s, skipping." % (cfg.get("Main", "configfile"), directory), 1)
2019-06-12 23:32:05 +02:00
return {},None
# get config file for directory
dir_config = Tools.get_config(directory + "/" + cfg.get("Main", "configfile"))
if not dir_config:
debug.debug(" --- Cannot read %s in %s, skipping." % (cfg.get("Main", "configfile"), directory), 1)
2019-06-12 23:32:05 +02:00
return {},None
destdir = dir_config.get("Main","dest")
# destfiles is a dict of all files that will be created from the classes config
# key is the destination filename, values are all classes filenames that are used to
# build the file
destfiles = {}
# FIXME: reverse_order should really be a bool in .cfg, implement variable types in cfg file
reverse_sort = False
try:
reverse_sort = (dir_config.get("Main", "reverse") == 'True')
except ValueError:
reverse_sort = False
if os.access(directory + "/install.sh", os.X_OK):
subprocess.call([directory + "/install.sh"])
2019-06-12 23:32:05 +02:00
# walk through all know classes in directory and find filenames
for h in classchecks.__classes_for_host__(reverse_sort):
2019-06-12 23:32:05 +02:00
# build classes directory
if h[0] != "":
classdir = directory+"/"+h[0]+"_"+h[1]
else:
classdir = directory+"/"+h[1]
debug.debug(" ??? Looking for directory %s." % classdir, 4)
2019-06-12 23:32:05 +02:00
# if class directory exists
if os.path.isdir(classdir):
debug.debug(" +++ Found directory %s, getting files." % classdir, 4)
2019-06-12 23:32:05 +02:00
# get list of files within this class directory
tempfiles = workconf(classdir)
debug.debug(" +++ Got %d files: %s." % (len(tempfiles), str(tempfiles)), 4)
2019-06-12 23:32:05 +02:00
# put files into dict
for f in tempfiles:
destname = destdir+os.path.basename(f) # destination filename
if not destname in destfiles:
destfiles[destname] = []
destfiles[destname].append(f) # append each file to dict
debug.debug(" +++ Added file to %s, now %d files: %s" % (destname, len(destfiles[destname]), destfiles[destname]), 4)
2019-06-12 23:32:05 +02:00
debug.debug(" === workdir: %s, Files: %s" % (directory, str(destfiles)), 3)
debug.debug(" ================ workdir ===============", 1)
2019-06-12 23:32:05 +02:00
return destfiles, dir_config
def build_file(classfiles, destfile, commentstring):
"""open all classfiles, assemble them and write the contents into a tempfile
returns the name of tempfile
:param classfiles:
:param destfile:
:param commentstring:
:return: str
"""
content = []
debug.debug(" ================ build_file ===============", 1)
2019-06-12 23:32:05 +02:00
if commentstring != "":
debug.debug(" +++ commentstring found, adding header.", 3)
2019-06-12 23:32:05 +02:00
content.append(commentstring + " " + cfg.get("Main","stamp") + " " + time.strftime("%+") + "\n")
for f in classfiles:
debug.debug(" +++ Merging %s." % f, 4)
2019-06-12 23:32:05 +02:00
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(cfg.get("Main","stampreplace")), filecontent):
debug.debug(" +++ commentstring empty, replacing stamp in file", 3)
2019-06-12 23:32:05 +02:00
filecontent = re.sub(re.escape(cfg.get("Main","stampreplace")), cfg.get("Main","stamp"), filecontent)
content.append(filecontent)
(tempfd, tempfilename) = tempfile.mkstemp(prefix=os.path.basename(destfile), dir="/tmp")
try:
fp = os.fdopen(tempfd, "w")
except:
Tools.error("Cannot write to temporary file %s" % tempfilename)
os.remove(tempfilename)
return False
debug.debug(" +++ Writing merged files into tempfile %s." % tempfilename, 3)
2019-06-12 23:32:05 +02:00
for block in content:
fp.write(block)
fp.write("\n")
2013-01-12 17:17:12 +01:00
fp.close()
debug.debug(" ================ build_file ===============", 1)
2019-06-12 23:32:05 +02:00
return tempfilename
def process_all_files(destfiles, dir_config):
"""processes all files in destfiles, generate files from classes, compare and copy if necessary"""
debug.debug(" ================ process_all_files ===============", 1)
2019-06-12 23:32:05 +02:00
for df in destfiles.keys():
debug.debug(" ??? Processing source files for %s." % df, 2)
2019-06-12 23:32:05 +02:00
# assemble file to tmp
commentstring = ""
if dir_config.check("Main", "commentstring"):
commentstring = dir_config.get("Main", "commentstring")
debug.debug(" +++ Found commentstring %s in %s" % (commentstring, df), 3)
2019-06-12 23:32:05 +02:00
tempfilename = build_file(destfiles[df], df, commentstring)
if not tempfilename:
debug.debug(" --- Error while creating temp file for %s, skipping." % df, 1)
2019-06-12 23:32:05 +02:00
continue
debug.debug(" +++ Merged files %s for %s into %s" % (str(destfiles[df]), df, tempfilename), 2)
2019-06-12 23:32:05 +02:00
# diff assembled file and config file
if Tools.diff(df, tempfilename, commentstring, debug):
debug.debug("File %s has changed" % df, 0)
if not Tools.user_config_generated(df, cfg):
debug.debug(" +++ %s not generated by userconfig, backing up." % df, 2)
2019-06-12 23:32:05 +02:00
# file not generated from userconfig -> back up
Tools.backup_file(df, debug)
# copy tmp file to real location
debug.debug("Copy %s to %s." % (tempfilename, df), 0)
Tools.copy_file(tempfilename, df, debug)
# remove tmp
debug.debug(" +++ Removing temporary file %s." % tempfilename, 2)
2019-06-12 23:32:05 +02:00
os.remove(tempfilename)
debug.debug(" ================ process_all_files ===============", 1)
2013-01-12 17:17:12 +01:00
2013-01-11 00:35:09 +01:00
def main():
2019-06-12 23:32:05 +02:00
configfile = os.environ['HOME']+"/etc/userconfig.cfg"
2013-01-12 23:04:52 +01:00
try:
2019-06-12 23:32:05 +02:00
try:
opts, args = getopt.getopt(sys.argv[1:], "hdc:v", ["help", "debug", "config="])
except getopt.GetoptError as msg:
raise Usage(msg)
for option, value in opts:
if option == "-v":
debug.addverbose()
if option in ("-h", "--help"):
raise Usage(help_message)
if option in ("-d", "--debug.debug"):
pass
if option in ("-c", "--config"):
configfile = value
except Usage as err:
Tools.error(sys.argv[0].split("/")[-1] + ": " + str(err.msg))
Tools.error("\t for help use --help")
return 2
debug.debug("Verbose level is %d" % debug.verbose, 1)
2019-06-12 23:32:05 +02:00
debug.debug("Using configfile %s." % configfile, 1)
if not os.path.isfile(configfile):
Tools.error("No config file specified.")
return 2
cfg.setdebug(debug)
cfg.setfilename(configfile)
debug.debug("================ main ===============", 1)
tempclasses = ""
for h in classchecks.__classes_for_host__():
tempclasses=tempclasses + str(h) + ","
debug.debug("+++ Current host is in classes %s" % tempclasses, 1)
2019-06-12 23:32:05 +02:00
configdir = cfg.get("Main", "configdir")
for d in os.listdir(configdir):
destfiles = {}
name = configdir+"/"+d
debug.debug("+++ Working in %s" % name, 1)
2019-06-12 23:32:05 +02:00
if not os.path.isdir(name):
debug.debug("--- %s is not a directory, skipping." % name, 3)
2019-06-12 23:32:05 +02:00
continue
elif d.startswith(".svn") or d.startswith(".git"):
debug.debug("--- %s is .svn or .git, skipping." % name, 3)
2019-06-12 23:32:05 +02:00
continue
elif os.path.isfile(name+"/.ignore"):
debug.debug("--- %s contains file .ignore, skipping." % name, 3)
2019-06-12 23:32:05 +02:00
continue
else:
debug.debug("+++ Processing files in %s" % name, 2)
2019-06-12 23:32:05 +02:00
(destfiles, dirConfig) = workdir(name)
if isinstance(destfiles, dict):
if len(destfiles.keys()) > 0:
debug.debug("+++ Building %d files: %s" % (len(destfiles.keys()), destfiles.keys()), 3)
2019-06-12 23:32:05 +02:00
process_all_files(destfiles, dirConfig)
else:
debug.debug("--- No files found for %s, skipping." % name, 1)
2013-01-11 00:35:09 +01:00
if __name__ == '__main__':
2019-06-12 23:32:05 +02:00
main()