pyuserconfig/userconfig.py

257 lines
7.1 KiB
Python
Executable File

#!/usr/bin/env python
# encoding: utf-8
#
# $Id$
# $URL$
"""
userconfig.py
Created by Marcus Stoegbauer on 2013-01-10.
Copyright (c) 2013 __MyCompanyName__. All rights reserved.
"""
import sys
import os
import tempfile
import re
import getopt
import time
#
import userconfig.cfgfile as cfgfile
from userconfig.checks import checks
import userconfig.Tools as Tools
debug = Tools.Debug()
classchecks = checks()
cfg = cfgfile.Conf()
hostclasses = classchecks.__classesForHost__()
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
# def __init__
help_message = """
-h help
-d debug
-c userconfig.cfg config file
"""
# class Usage
def workconf(directory, depth=2):
"""walks through directory, collecting all filenames, returns list of all filenames"""
dirs = os.listdir(directory)
ret = []
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 dir
if not name.endswith(".swp"):
ret.append(name)
debug.debug("workconf: found file %s" % name, depth)
# if not .swp
# for d
return ret
# def workconf
def workdir(directory):
"""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("===============================", 1)
# 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)
return ({},None)
# if not DEST
# get config file for directory
dirConfig = Tools.getConfig(directory+"/"+cfg.get("Main", "CONFIGFILE"))
if not dirConfig:
debug.debug("Cannot read %s in %s, skipping." % (cfg.get("Main", "CONFIGFILE"), directory), 1)
return ({},None)
# if not dirConfig
destdir = dirConfig.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 = {}
# walk through all know classes in directory and find filenames
for h in hostclasses:
# build classes directory
if h[0] != "":
classdir = directory+"/"+h[0]+"_"+h[1]
else:
classdir = directory+"/"+h[1]
# if all
# if class directory exists
if os.path.isdir(classdir):
debug.debug("workdir: %s" % classdir, 1)
# get list of files within this class directory
tempfiles = workconf(classdir)
# put files into dict
for f in tempfiles:
destname = destdir+os.path.basename(f) # destination filename
if not destfiles.has_key(destname):
destfiles[destname] = []
# if not destname, create key with empty list
destfiles[destname].append(f) # append each file to dict
# for tempfiles
# if classdir
# for hostclasses
debug.debug("workdir: %s, Files: %s" % (directory, str(destfiles)))
debug.debug("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^", 1)
return (destfiles, dirConfig)
# def work
def buildFile(classfiles, destfile, commentstring):
"""open all classfiles, assemble them and write the contents into a tempfile
returns the name of tempfile"""
content = []
if commentstring != "":
content.append(commentstring + " " + cfg.get("Main","STAMP") + " " + time.strftime("%+") + "\n")
# if commentstring not empty
for f in classfiles:
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):
filecontent = re.sub(re.escape(cfg.get("Main","STAMPREPLACE")), cfg.get("Main","STAMP"), filecontent)
# if search
# if commentstring empty
content.append(filecontent)
# end f
(tempfd, tempfilename) = tempfile.mkstemp(prefix=os.path.basename(destfile), dir="/tmp")
fp = None
try:
fp = os.fdopen(tempfd, "w")
except:
Tools.error("Cannot write to temporary file %s" % tempfilename)
os.remove(tempfilename)
return False
# try
for block in content:
fp.write(block)
fp.write("\n")
# for content
fp.close()
return tempfilename
# def buildFile
def processAllFiles(destfiles, dirConfig):
"""processes all files in destfiles, generate files from classes, compare and copy if necessary"""
debug.debug("processAllFiles, dirConfig: %s" % (str(dirConfig.getitems("Main"))))
for df in destfiles.keys():
# assemble file to tmp
commentstring = ""
if dirConfig.check("Main", "commentstring"):
commentstring = dirConfig.get("Main", "commentstring")
debug.debug("Found commentstring %s in %s" % (commentstring, df))
# if COMMENTSTRNIG
tempfilename = buildFile(destfiles[df], df, commentstring)
if not tempfilename:
debug.debug("Error while creating temp file for %s, skipping." % df)
continue
# if not tempfilename
# diff assembled file and config file
if Tools.diff(df, tempfilename, commentstring, debug):
debug.debug("%s changed." % df)
if not Tools.userConfigGenerated(df, cfg):
debug.debug("%s not generated by userconfig, backing up." % df)
# file not generated from userconfig -> back up
Tools.backupFile(df, debug)
# if not userConfigGenerated
# copy tmp file to real location
Tools.copyFile(tempfilename, df, debug)
# if diff
# remove tmp
os.remove(tempfilename)
# for df
# def buildAllFiles
def main():
configfile = ""
global verbose
try:
try:
opts, args = getopt.getopt(sys.argv[1:], "hdc:v", ["help", "debug", "config="])
except getopt.error, msg:
raise Usage(msg)
# try getopt
for option, value in opts:
if option == "-v":
debug.setverbose(1)
if option in ("-h", "--help"):
raise Usage(help_message)
if option in ("-d", "--debug.debug"):
pass
if option in ("-c", "--config"):
configfile = value
# if
# for option, value
except Usage, err:
Tools.error(sys.argv[0].split("/")[-1] + ": " + str(err.msg))
Tools.error("\t for help use --help")
return 2
# try
if configfile == "":
Tools.error( "No config file specified.")
return 2
# if configfile
cfg.setfilename(configfile)
debug.debug("Classes for host: %s" % hostclasses)
configdir = cfg.get("Main", "CONFIGDIR")
for d in os.listdir(configdir):
destfiles = {}
name = configdir+d
if not os.path.isdir(name):
continue
elif d.startswith(".svn"):
continue
elif os.path.isfile(name+"/.ignore"):
continue
else:
debug.debug("main: %s" % name)
(destfiles, dirConfig) = workdir(name)
if isinstance(destfiles, dict):
if len(destfiles.keys()) > 0:
processAllFiles(destfiles, dirConfig)
# if > 0
else:
debug.debug("No destfiles for %s, skipping." % d)
# if
# for d
# def main
if __name__ == '__main__':
main()