Compare commits
39 Commits
cba08629cb
...
main
Author | SHA1 | Date | |
---|---|---|---|
bfb82a7f9c | |||
d304e67089 | |||
3ee87bbb12 | |||
206398ab8d | |||
1f12b78ef3 | |||
f28e231185 | |||
875e6a4831 | |||
1ea2450261 | |||
f67a8ed01f | |||
3b747f56ba | |||
378ebcebf6 | |||
5cd56f5f97 | |||
1a32b4e096 | |||
e43dd9013c | |||
a986a70800 | |||
e6d2b9a7bc | |||
37954e432c | |||
4640a5edc3 | |||
c6405e9c2a | |||
6171ca5bb1 | |||
7684033903 | |||
015ea337f2 | |||
3cd4e224d1 | |||
ac41bc7fb6 | |||
d8bb56cb7b | |||
ee19f4b1b1 | |||
7ed282057f | |||
b5c898035a | |||
2c06ecca77 | |||
e82fd99a16 | |||
4790429f24 | |||
57b3600d47 | |||
e46c8249de | |||
16020e8fbb | |||
d747df7aa4 | |||
81d38a93a0 | |||
baebb052b8 | |||
3048437081 | |||
ef0efba96a |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,6 +1,7 @@
|
||||
/__pycache__/
|
||||
*.pyc
|
||||
build/
|
||||
.idea/workspace.xml
|
||||
.idea/
|
||||
.venv
|
||||
userconfig.egg-info/
|
||||
*.swp
|
||||
|
4
.idea/misc.xml
generated
4
.idea/misc.xml
generated
@@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (pyuserconfig)" project-jdk-type="Python SDK" />
|
||||
</project>
|
8
.idea/modules.xml
generated
8
.idea/modules.xml
generated
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/pyuserconfig.iml" filepath="$PROJECT_DIR$/.idea/pyuserconfig.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
11
.idea/pyuserconfig.iml
generated
11
.idea/pyuserconfig.iml
generated
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="jdk" jdkName="Python 3.7 (pyuserconfig)" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="TestRunnerService">
|
||||
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
|
||||
</component>
|
||||
</module>
|
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
@@ -1,158 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# encoding: utf-8
|
||||
|
||||
"""
|
||||
Tools.py
|
||||
|
||||
Created by Marcus Stoegbauer on 2013-01-12.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import Userconfig.cfgfile as cfgfile
|
||||
import re
|
||||
import time
|
||||
import shutil
|
||||
|
||||
|
||||
class Debug(object):
|
||||
verbose = 0
|
||||
|
||||
def __init__(self, verbose=0):
|
||||
self.setverbose(verbose)
|
||||
|
||||
def setverbose(self, verbose):
|
||||
"""docstring for setverbose"""
|
||||
self.verbose = verbose
|
||||
|
||||
def addverbose(self):
|
||||
"""docstring for setverbose"""
|
||||
self.verbose += 1
|
||||
|
||||
def debug(self, out, level=0):
|
||||
"""docstring for debug"""
|
||||
if self.verbose >= level:
|
||||
print(out)
|
||||
|
||||
|
||||
def error(out):
|
||||
"""Print error on stderr"""
|
||||
print(str(out)+"\n", file=sys.stderr)
|
||||
|
||||
|
||||
def get_config(filename):
|
||||
"""reads filename as config, checks for DEST parameter and returns cfgfile object"""
|
||||
ret = None
|
||||
try:
|
||||
ret = cfgfile.Conf(filename)
|
||||
except:
|
||||
error("Error reading config file %s" % filename)
|
||||
return False
|
||||
|
||||
# check for DEST parameter
|
||||
if not ret.check("Main", "dest"):
|
||||
error("No DEST in config file %s" % filename)
|
||||
return False
|
||||
|
||||
# replace $HOME with real home directory
|
||||
if ret.get("Main", "dest") == "$HOME":
|
||||
ret.set("Main", "dest", os.environ['HOME'])
|
||||
|
||||
# make sure DEST ends with /
|
||||
if not ret.get("Main", "dest").endswith("/"):
|
||||
ret.set("Main", "dest", ret.get("Main", "dest")+"/")
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
def read_skip_comment(fp, commentstring):
|
||||
"""Read line from filehandle fp and skip all empty (whitespace) lines and lines starting with commentstring
|
||||
"""
|
||||
for line in fp:
|
||||
line = line[:-1]
|
||||
if (commentstring != "" and not re.match("^"+re.escape(commentstring), line)) and line !="" and not re.match("^\s+$", line):
|
||||
yield line
|
||||
|
||||
|
||||
def diff(destfile, tempfile, commentstring, debug):
|
||||
"""diff destfile and tempfile, returns True if files differ, False if they are the same"""
|
||||
debug.debug("Diffing %s and %s" % (destfile, tempfile), 3)
|
||||
if not os.path.isfile(destfile):
|
||||
debug.debug("Destfile %s does not exist, returning True." % destfile, 3)
|
||||
# destfile does not exist -> copy tempfile over
|
||||
return True
|
||||
# if not destfile
|
||||
if not os.path.isfile(tempfile):
|
||||
# tempfile does not exist, this should never happen
|
||||
error("Temporary file %s does not exist, this should not happen." % tempfile)
|
||||
sys.exit(1)
|
||||
# if not tempfile
|
||||
|
||||
fp1 = open(tempfile)
|
||||
fp2 = open(destfile)
|
||||
|
||||
for line1, line2 in zip(read_skip_comment(fp1, commentstring), read_skip_comment(fp2, commentstring)):
|
||||
if line1 != line2:
|
||||
fp1.close()
|
||||
fp2.close()
|
||||
debug.debug("%s differs, return true" % destfile, 3)
|
||||
return True
|
||||
# if differ
|
||||
# for line
|
||||
fp1.close()
|
||||
fp2.close()
|
||||
debug.debug("%s is the same, return false" % destfile, 3)
|
||||
return False
|
||||
|
||||
|
||||
def user_config_generated(filename, cfg):
|
||||
"""returns True if filename has been generated by userconfig, False else"""
|
||||
|
||||
if not os.path.isfile(filename):
|
||||
# filename does not exist, so it was not generated by userconfig
|
||||
return False
|
||||
|
||||
if not cfg.check("Main","stamp"):
|
||||
# no STAMP in userconfig.cfg, so no way to check if file was generated by userconfig
|
||||
return False
|
||||
|
||||
fp = open(filename, "r")
|
||||
|
||||
for line in fp:
|
||||
if re.search(re.escape(cfg.get("Main","stamp")), line):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def backup_file(filename, debug):
|
||||
"""make backup of filename, returns True if backup is successful, False else"""
|
||||
if os.path.isfile(filename):
|
||||
debug.debug("%s exists, finding backup name." % filename, 3)
|
||||
backupname = filename+".userconfig."+time.strftime("%F")
|
||||
testbackupname = backupname
|
||||
counter = 0
|
||||
while os.path.isfile(testbackupname):
|
||||
counter+=1
|
||||
testbackupname=backupname+"."+str(counter)
|
||||
debug.debug("Renaming %s to %s" % (filename, testbackupname), 1)
|
||||
os.rename(filename, testbackupname)
|
||||
return True
|
||||
else:
|
||||
debug.debug("%s does not exist, do not need backup." % filename, 3)
|
||||
return False
|
||||
|
||||
|
||||
def copy_file(sourcefile, destfile, debug):
|
||||
"""copy sourcefile to destfile, returns True if successful, False else"""
|
||||
|
||||
if os.path.isfile(sourcefile):
|
||||
# sourcefile exists
|
||||
debug.debug("Source file %s exists, proceeding with copy." % sourcefile, 3)
|
||||
if not os.path.isfile(destfile) or os.access(destfile, os.W_OK):
|
||||
debug.debug("Copying %s to %s" % (sourcefile, destfile), 1)
|
||||
shutil.copy(sourcefile, destfile)
|
||||
return True
|
||||
# destfile is writable
|
||||
else:
|
||||
debug.debug("Destination file %s does not exist or is not writable." % destfile, 3)
|
||||
return False
|
@@ -1,77 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# encoding: utf-8
|
||||
#
|
||||
|
||||
"""
|
||||
cfgfile.py
|
||||
|
||||
Created by Marcus Stoegbauer on 2013-01-12.
|
||||
"""
|
||||
import configparser
|
||||
import os
|
||||
import re
|
||||
|
||||
class Conf(object):
|
||||
confobj = configparser.RawConfigParser()
|
||||
cfgfile = ''
|
||||
debug = None
|
||||
|
||||
def __init__(self, filename=None):
|
||||
"""if filename is set, open config file and initialize the ConfigParser
|
||||
"""
|
||||
self.confobj = configparser.RawConfigParser()
|
||||
if filename:
|
||||
self.setfilename(filename)
|
||||
|
||||
def setdebug(self, debug):
|
||||
"""docstring for setdebug"""
|
||||
self.debug = debug
|
||||
|
||||
def setfilename(self, filename):
|
||||
"""initialize the ConfigParser
|
||||
"""
|
||||
ret = self.confobj.read(filename)
|
||||
if len(ret) == 0 or ret[0] != filename:
|
||||
raise Exception('Cannot read config file ' + filename)
|
||||
self.cfgfile = filename
|
||||
if self.debug:
|
||||
self.debug.debug("Read config file %s" % filename, 2)
|
||||
self.debug.debug("Replacing environment variables in %s." % filename, 3)
|
||||
|
||||
for s in self.confobj.sections():
|
||||
for (i, val) in self.confobj.items(s):
|
||||
tempre = re.search(r"\$([A-Z]+)[^A-Z]*", val)
|
||||
if tempre:
|
||||
varname = tempre.group(1)
|
||||
if self.debug:
|
||||
self.debug.debug("Found variable %s in %s." % (varname, i), 3)
|
||||
if varname in os.environ:
|
||||
if self.debug:
|
||||
self.debug.debug("%s exists in environment, replacing with %s." %
|
||||
(varname, os.environ[varname]), 3)
|
||||
self.set(s, i, val.replace("$"+varname, os.environ[varname]))
|
||||
|
||||
def get(self, section, option):
|
||||
"""returns the value of option in section
|
||||
"""
|
||||
if not self.cfgfile:
|
||||
raise Exception('No config file set')
|
||||
try:
|
||||
return self.confobj.get(section, option)
|
||||
except configparser.NoOptionError:
|
||||
raise ValueError('Option does not exist')
|
||||
|
||||
def set(self, section, option, value):
|
||||
"""docstring for update"""
|
||||
self.confobj.set(section, option, value)
|
||||
|
||||
def getitems(self, section):
|
||||
"""returns all items in section
|
||||
"""
|
||||
if not self.cfgfile:
|
||||
raise Exception('No config file set')
|
||||
return self.confobj.items(section)
|
||||
|
||||
def check(self, section, option):
|
||||
"""checks for option in section"""
|
||||
return self.confobj.has_option(section, option)
|
@@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# encoding: utf-8
|
||||
#
|
||||
"""
|
||||
checks.py
|
||||
|
||||
Created by Marcus Stoegbauer on 2013-01-10.
|
||||
"""
|
||||
|
||||
import platform
|
||||
from operator import itemgetter
|
||||
|
||||
class Checks(object):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def get_short_hostname(self):
|
||||
"""docstring for getShortHostname"""
|
||||
hostname = platform.node()
|
||||
if hostname.count("."):
|
||||
hostname = hostname.split(".")[0]
|
||||
return hostname
|
||||
|
||||
# def getShortHostname
|
||||
|
||||
def __classes_for_host__(self, reverse=False):
|
||||
"""docstring for __classesForHost"""
|
||||
classes = []
|
||||
for c in dir(self):
|
||||
if c.startswith("__"):
|
||||
continue
|
||||
ret = getattr(self, c)()
|
||||
if type(ret) == tuple and len(ret) == 3:
|
||||
classes.append(ret)
|
||||
return map(lambda k: (k[1], k[2]), sorted(classes, key=itemgetter(0), reverse=reverse))
|
||||
|
||||
def header(self):
|
||||
"""docstring for header"""
|
||||
return (0, "", "header")
|
||||
|
||||
def footer(self):
|
||||
"""docstring for footer"""
|
||||
return (1000, "", "footer")
|
||||
|
||||
def all(self):
|
||||
"""docstring for all"""
|
||||
return (998, "", "all")
|
||||
|
||||
def arch(self):
|
||||
"""docstring for arch"""
|
||||
return (800, "Arch", platform.system())
|
||||
|
||||
def hostname(self):
|
||||
"""docstring for hostname"""
|
||||
hostname = self.get_short_hostname()
|
||||
return (10, "Host", hostname)
|
||||
|
||||
def app(self):
|
||||
"""docstring for app"""
|
||||
hostname = self.get_short_hostname()
|
||||
if hostname == "glitters":
|
||||
return (500, "", "rancid_hosts")
|
||||
else:
|
||||
return ()
|
||||
# def app
|
||||
# def checks
|
167
cli/__init__.py
Executable file
167
cli/__init__.py
Executable file
@@ -0,0 +1,167 @@
|
||||
import os
|
||||
import argparse
|
||||
from userconfig.cfgfile import Conf
|
||||
from userconfig import Userconfig
|
||||
import sys
|
||||
import subprocess
|
||||
|
||||
|
||||
class Debug:
|
||||
_verbose = 0
|
||||
|
||||
_COLOR_RED = '\033[91m'
|
||||
_COLOR_BLUE = '\33[34m'
|
||||
_COLOR_GREEN = '\33[32m'
|
||||
_COLOR_YELLOW = '\033[93m'
|
||||
_COLOR_END = '\33[0m'
|
||||
|
||||
_FORMAT = {'STANDARD': 'INFO: ',
|
||||
'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):
|
||||
self.set_verbose(verbose)
|
||||
|
||||
def set_verbose(self, verbose):
|
||||
self._verbose = verbose
|
||||
|
||||
def add_verbose(self):
|
||||
self._verbose += 1
|
||||
|
||||
def get_verbose(self):
|
||||
return self._verbose
|
||||
|
||||
def stdout(self, out, verbose_level=0, category='STANDARD'):
|
||||
spaces = ''
|
||||
if verbose_level > 1:
|
||||
spaces = ' '*(verbose_level-1)
|
||||
|
||||
if self._verbose >= verbose_level:
|
||||
if category in self._FORMAT:
|
||||
print(f'{spaces}{self._FORMAT[category]}{out}')
|
||||
else:
|
||||
print(f'{spaces}[category {category} unknown]:{out}')
|
||||
|
||||
def stderr(self, out, verbose_level=0, category='STANDARD'):
|
||||
if self._verbose >= verbose_level:
|
||||
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 red(self, out):
|
||||
return f'{self._COLOR_RED}{out}{self._COLOR_END}'
|
||||
|
||||
def green(self, out):
|
||||
return f'{self._COLOR_GREEN}{out}{self._COLOR_END}'
|
||||
|
||||
def blue(self, out):
|
||||
return f'{self._COLOR_BLUE}{out}{self._COLOR_END}'
|
||||
|
||||
def yellow(self, out):
|
||||
return f'{self._COLOR_YELLOW}{out}{self._COLOR_END}'
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(prog='userconfig',
|
||||
description='Manages configuration files, usually in the user home directory')
|
||||
|
||||
parser.add_argument('-v',
|
||||
help='Verbosity level (multiple v for higher level)',
|
||||
dest='verbose', action='count', default=0)
|
||||
parser.add_argument('-f', '--file',
|
||||
help='userconfig2.cfg config file',
|
||||
dest='file', action='store')
|
||||
cmdline = parser.parse_args()
|
||||
debug = Debug()
|
||||
debug.set_verbose(cmdline.verbose)
|
||||
cfg = Conf(filename=cmdline.file, debug=debug)
|
||||
uc = Userconfig(cfg)
|
||||
|
||||
cfg.debug.stdout(f'Verbose level: {cfg.debug.get_verbose()}', 1)
|
||||
configdir = cfg.get('configdir')
|
||||
# configdir is the root of the userconfig files
|
||||
# Directory structure:
|
||||
# configdir/
|
||||
# |-- userconfig2.conf
|
||||
# |-- package1/
|
||||
# |- package.conf
|
||||
# |- 001_Arch_Linux/
|
||||
# |- file1
|
||||
# |- file2
|
||||
# |- 002_Host_glitters/
|
||||
# |- file1
|
||||
# |- 003_all/
|
||||
# |- file2
|
||||
#
|
||||
# Terminology:
|
||||
# directories below configdir are packages, packages contain directories categorizing for which host/arch they
|
||||
# are fitted, below that are files which are installed at the destination
|
||||
#
|
||||
# directory names in packages:
|
||||
# [Number]_[category]_[value]
|
||||
# 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 an input value, 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):
|
||||
# Skip on non-production files
|
||||
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')
|
||||
continue
|
||||
if os.path.isfile(f'{package.path}/.ignore'):
|
||||
cfg.debug.stdout(f'{package.path} contains .ignore, skipping', 2, 'WARNING')
|
||||
continue
|
||||
# Start processing
|
||||
cfg.debug.stdout(f'Start Package {cfg.debug.green(package.path)}', 1, 'NOTICE')
|
||||
# Get all category directories for package
|
||||
(category_dirs, dir_config) = uc.process_package_dir(package.path)
|
||||
if not category_dirs:
|
||||
cfg.debug.stdout(f'Could not get category_dirs for package {package.name}, skipping package.', 0, 'ERROR')
|
||||
continue
|
||||
if not dir_config:
|
||||
cfg.debug.stdout(f'Could not get dir_config for package {package.name}, skipping package.', 0, 'ERROR')
|
||||
continue
|
||||
cfg.debug.stdout(f'Got categories: {category_dirs}', 2)
|
||||
host_category_dirs = uc.filter_categories(category_dirs)
|
||||
cfg.debug.stdout('Host uses categories: %s' % ", ".join([f'{v[1]}_{v[2]}' for v in 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}'
|
||||
cfg.debug.stdout('Generating %s from:\n %s' % (dest, "\n ".join(file_list[file])), 1)
|
||||
|
||||
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
|
||||
if uc.create_destination_directories(dir_config.get(section="Main", option="dest")):
|
||||
cfg.debug.stdout(f'Created target directories {cfg.debug.green(dir_config.get(section="Main", option="dest"))}',
|
||||
0, 'SUCCESS')
|
||||
else:
|
||||
cfg.debug.stdout(f'All target directories exist', 2)
|
||||
temp_filename = uc.build_file(file_list[file], dest, comment_string)
|
||||
if uc.diff_and_copy_file(temp_filename, dest, comment_string):
|
||||
cfg.debug.stdout(f'Copy {temp_filename} -> {cfg.debug.green(dest)} (changed)\n', 0, 'SUCCESS')
|
||||
else:
|
||||
cfg.debug.stdout(f'Generated file and destination are the same.\n', 1)
|
||||
|
||||
cfg.debug.stdout(f'End Package {cfg.debug.green(package.path)}\n\n', 1, 'NOTICE')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
11
install.sh
11
install.sh
@@ -1,10 +1,11 @@
|
||||
#!/bin/sh
|
||||
|
||||
if type pip3 >/dev/null 2>&1; then
|
||||
pip3 install --user git+https://git.lys.is/lysis/pyuserconfig.git
|
||||
if type pipx >/dev/null 2>&1; then
|
||||
pipx install git+https://git.lys.is/lysis/pyuserconfig.git
|
||||
if [ ! -e ~/.userconfig ]; then
|
||||
git clone git@git.lys.is:lysis/userconfig.git ~/.userconfig
|
||||
mkdir ~/.config
|
||||
PYTHONPATH=~/.local/lib ~/.local/bin/userconfig.py
|
||||
fi
|
||||
userconfig
|
||||
else
|
||||
echo "No pip3 installed, cannot proceed."
|
||||
echo "No pipx installed, cannot proceed."
|
||||
fi
|
||||
|
19
pyproject.toml
Normal file
19
pyproject.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[build-system]
|
||||
requires = ["setuptools", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "userconfig"
|
||||
version = "2.1"
|
||||
authors = [ {name = "Marcus Stoegbauer", email = "marcus@grmpf.org"} ]
|
||||
maintainers = [ {name = "Marcus Stoegbauer", email = "marcus@grmpf.org"} ]
|
||||
description = "Generate config files for user home"
|
||||
|
||||
[project.scripts]
|
||||
userconfig = "cli:main"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = [ "userconfig", "cli" ]
|
||||
|
||||
[tool.setuptools.data-files]
|
||||
"etc" = [ "userconfig2.conf" ]
|
16
setup.py
16
setup.py
@@ -1,13 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# migrated to pyproject.toml
|
||||
# as reccomended: https://packaging.python.org/en/latest/guides/modernize-setup-py-project/#what-if-something-that-can-not-be-changed-expects-a-setup-py-file
|
||||
from setuptools import setup
|
||||
|
||||
from distutils.core import setup
|
||||
|
||||
setup(name="userconfig",
|
||||
version="0.1",
|
||||
description="Generate config files for user home",
|
||||
author="Marcus Stoegbauer",
|
||||
author_email="marcus@grmpf.org",
|
||||
packages=["Userconfig"],
|
||||
scripts=["userconfig.py"],
|
||||
data_files=[('etc', ['userconfig.cfg'])]
|
||||
)
|
||||
setup()
|
@@ -1,6 +0,0 @@
|
||||
[Main]
|
||||
configdir = $HOME/.userconfig
|
||||
configfile = userconfig.cfg
|
||||
debug = 0
|
||||
stamp = %userconfig_generated 1.0%
|
||||
stampreplace = $userconfig_stamp$
|
270
userconfig.py
270
userconfig.py
@@ -1,270 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# encoding: utf-8
|
||||
#
|
||||
|
||||
"""
|
||||
userconfig.py
|
||||
|
||||
Created by Marcus Stoegbauer on 2013-01-10.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import tempfile
|
||||
import re
|
||||
import getopt
|
||||
import time
|
||||
import subprocess
|
||||
|
||||
#
|
||||
import Userconfig.cfgfile as cfgfile
|
||||
from Userconfig.checks import Checks
|
||||
import Userconfig.Tools as Tools
|
||||
|
||||
debug = Tools.Debug()
|
||||
|
||||
classchecks = Checks()
|
||||
cfg = cfgfile.Conf()
|
||||
|
||||
help_message = """
|
||||
-h help
|
||||
-v verbose level (multiple v for higher level)
|
||||
-c userconfig.cfg config file
|
||||
"""
|
||||
|
||||
|
||||
class Usage(Exception):
|
||||
def __init__(self, msg):
|
||||
self.msg = msg
|
||||
|
||||
|
||||
def workconf(directory, depth=2):
|
||||
"""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)
|
||||
for d in dirs:
|
||||
name = directory+"/"+d
|
||||
if os.path.isdir(name):
|
||||
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)
|
||||
return ret
|
||||
|
||||
|
||||
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(" ================ workdir ===============", 1)
|
||||
debug.debug(" Working on directory %s" % directory, 3)
|
||||
# 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
|
||||
|
||||
# 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)
|
||||
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"])
|
||||
|
||||
# walk through all know classes in directory and find filenames
|
||||
for h in classchecks.__classes_for_host__(reverse_sort):
|
||||
# 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)
|
||||
# if class directory exists
|
||||
if os.path.isdir(classdir):
|
||||
debug.debug(" +++ Found directory %s, getting files." % classdir, 4)
|
||||
# get list of files within this class directory
|
||||
tempfiles = workconf(classdir)
|
||||
debug.debug(" +++ Got %d files: %s." % (len(tempfiles), str(tempfiles)), 4)
|
||||
# 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)
|
||||
|
||||
debug.debug(" === workdir: %s, Files: %s" % (directory, str(destfiles)), 3)
|
||||
debug.debug(" ================ workdir ===============", 1)
|
||||
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)
|
||||
if commentstring != "":
|
||||
debug.debug(" +++ commentstring found, adding header.", 3)
|
||||
content.append(commentstring + " " + cfg.get("Main","stamp") + " " + time.strftime("%+") + "\n")
|
||||
|
||||
for f in classfiles:
|
||||
debug.debug(" +++ 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(cfg.get("Main","stampreplace")), filecontent):
|
||||
debug.debug(" +++ commentstring empty, replacing stamp in file", 3)
|
||||
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)
|
||||
for block in content:
|
||||
fp.write(block)
|
||||
fp.write("\n")
|
||||
fp.close()
|
||||
debug.debug(" ================ build_file ===============", 1)
|
||||
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)
|
||||
for df in destfiles.keys():
|
||||
debug.debug(" ??? Processing source files for %s." % df, 2)
|
||||
if not os.path.exists(os.path.dirname(df)):
|
||||
debug.debug(" +++ Directory %s does not exist, creating" % os.path.dirname(df), 1)
|
||||
os.mkdir(os.path.dirname(df))
|
||||
if not os.path.isdir(os.path.dirname(df)):
|
||||
debug.debug(" --- Destination directory %s does not exist, skipping." % os.path.dirname(df), 1)
|
||||
return False
|
||||
# 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)
|
||||
|
||||
tempfilename = build_file(destfiles[df], df, commentstring)
|
||||
if not tempfilename:
|
||||
debug.debug(" --- Error while creating temp file for %s, skipping." % df, 1)
|
||||
continue
|
||||
debug.debug(" +++ Merged files %s for %s into %s" % (str(destfiles[df]), df, tempfilename), 2)
|
||||
|
||||
# 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)
|
||||
# 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)
|
||||
os.remove(tempfilename)
|
||||
debug.debug(" ================ process_all_files ===============", 1)
|
||||
|
||||
def main():
|
||||
configfile_destinations = [os.environ['HOME'] + "/etc/",
|
||||
os.environ['HOME'] + "/.local/etc"]
|
||||
configfile = ''
|
||||
for directory in configfile_destinations:
|
||||
if os.path.isfile(directory + "/userconfig.cfg"):
|
||||
configfile = directory + "/userconfig.cfg"
|
||||
break
|
||||
try:
|
||||
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)
|
||||
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)
|
||||
configdir = cfg.get("Main", "configdir")
|
||||
for d in os.listdir(configdir):
|
||||
destfiles = {}
|
||||
name = configdir+"/"+d
|
||||
debug.debug("+++ Working in %s" % name, 1)
|
||||
if not os.path.isdir(name):
|
||||
debug.debug("--- %s is not a directory, skipping." % name, 3)
|
||||
continue
|
||||
elif d.startswith(".svn") or d.startswith(".git"):
|
||||
debug.debug("--- %s is .svn or .git, skipping." % name, 3)
|
||||
continue
|
||||
elif os.path.isfile(name+"/.ignore"):
|
||||
debug.debug("--- %s contains file .ignore, skipping." % name, 3)
|
||||
continue
|
||||
else:
|
||||
debug.debug("+++ Processing files in %s" % name, 2)
|
||||
(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)
|
||||
process_all_files(destfiles, dirConfig)
|
||||
else:
|
||||
debug.debug("--- No files found for %s, skipping." % name, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
287
userconfig/__init__.py
Normal file
287
userconfig/__init__.py
Normal file
@@ -0,0 +1,287 @@
|
||||
from userconfig.checks import check_class
|
||||
from userconfig.cfgfile import Conf
|
||||
import os
|
||||
import time
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
class Userconfig:
|
||||
_cfg = None
|
||||
|
||||
def __init__(self, cfg):
|
||||
self._cfg = cfg
|
||||
|
||||
def process_package_dir(self, package_dir):
|
||||
"""
|
||||
Walk through package_dir, collect all directories inside, parse them according to our specs and return
|
||||
a sorted list with entries (prio, category, value, path)
|
||||
|
||||
:param package_dir: root of package directory
|
||||
:return: list of tuples (prio, category, value, path), sorted with prio
|
||||
"""
|
||||
self._cfg.debug.stdout(f'process package_dir {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',
|
||||
0, 'ERROR')
|
||||
return None, None
|
||||
dir_config = self.get_config(package_config_file)
|
||||
if not dir_config:
|
||||
self._cfg.debug.stdout(f'Cannot read config file {package_config_file}, skipping', 0, 'ERROR')
|
||||
return None, 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)
|
||||
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', 0, 'ERROR')
|
||||
continue
|
||||
try:
|
||||
prio = int(prio_string)
|
||||
except ValueError:
|
||||
self._cfg.debug.stdout(f'Cannot convert prio to integer ({category.path}, skipping', 0, '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', 0, 'ERROR')
|
||||
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.endswith('.swp'):
|
||||
self._cfg.debug.stdout(f'Ignoring swap file {file.name}', 3)
|
||||
continue
|
||||
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, dest_file, comment_string):
|
||||
"""
|
||||
merge all files in files[] and write contents into a temporary file
|
||||
|
||||
:param files:
|
||||
:param dest_file:
|
||||
:param comment_string:
|
||||
:return: temporary filename
|
||||
"""
|
||||
|
||||
content = []
|
||||
self._cfg.debug.stdout(f'building file for {dest_file}', 3)
|
||||
if comment_string:
|
||||
content.append(f'{comment_string} {self._cfg.get("stamp")} {time.strftime("%+")}\n')
|
||||
for file in files:
|
||||
self._cfg.debug.stdout(f'Merging {file}', 3)
|
||||
fp = open(file, "r")
|
||||
file_content = fp.read()
|
||||
fp.close()
|
||||
# if comment_string exists, add comment with category dir and filename
|
||||
if comment_string:
|
||||
content.append(f'{comment_string} {"/".join(file.split("/")[-2:])}')
|
||||
content.append(file_content)
|
||||
|
||||
(temp_fd, temp_filename) = tempfile.mkstemp(prefix=os.path.basename(dest_file), dir="/tmp")
|
||||
try:
|
||||
fp = os.fdopen(temp_fd, "w")
|
||||
except Exception as e:
|
||||
self._cfg.debug.stderr(f'Cannot write to temporary file {temp_filename}: {e}', 0, 'ERROR')
|
||||
os.remove(temp_filename)
|
||||
return False
|
||||
self._cfg.debug.stdout(f'Writing merged files into temporary file {temp_filename}', 3)
|
||||
for block in content:
|
||||
fp.write(block)
|
||||
fp.write("\n")
|
||||
fp.close()
|
||||
return temp_filename
|
||||
|
||||
def diff_and_copy_file(self, temp_filename, dest_filename, comment_string):
|
||||
ret = False
|
||||
if self.diff(dest_filename, temp_filename, comment_string):
|
||||
if not self.user_config_generated(dest_filename):
|
||||
self._cfg.debug.stdout(f'{dest_filename} not generated by userconfig, running back_up.', 3)
|
||||
self.backup_file(dest_filename)
|
||||
self.copy_file(temp_filename, dest_filename)
|
||||
ret = True
|
||||
os.remove(temp_filename)
|
||||
self._cfg.debug.stdout(f'Removed temporary file {temp_filename}', 3, 'SUCCESS')
|
||||
return ret
|
||||
|
||||
def create_destination_directories(self, dest_directory):
|
||||
path = Path(dest_directory)
|
||||
if not path.exists():
|
||||
path.mkdir(parents=True)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def get_config(self, filename):
|
||||
"""reads filename as config, checks for DEST parameter and returns cfgfile object"""
|
||||
try:
|
||||
ret = Conf(filename=filename, debug=self._cfg.debug, force_filename=True)
|
||||
except ValueError:
|
||||
self._cfg.debug.stderr(f'Error reading config file {filename}', 0, 'ERROR')
|
||||
return False
|
||||
# check for DEST parameter
|
||||
if not ret.check(section="Main", option="dest"):
|
||||
self._cfg.debug.stderr(f'No dest in config file {filename}', 0, 'ERROR')
|
||||
return False
|
||||
# make sure DEST ends with /
|
||||
if not ret.get(section="Main", option="dest").endswith("/"):
|
||||
ret.set(section="Main", option="dest", value=ret.get(section="Main", option="dest")+"/")
|
||||
return ret
|
||||
|
||||
# FIXME remove, unused now
|
||||
@staticmethod
|
||||
def read_skip_comment(fp, comment_string):
|
||||
"""Read line from filehandle fp and skip all empty (whitespace) lines and lines starting with comment_string
|
||||
"""
|
||||
for line in fp:
|
||||
line = line[:-1]
|
||||
if ((comment_string != "" and not re.match("^"+re.escape(comment_string), line)) and line != "" and
|
||||
not re.match(r"^\s+$", line)):
|
||||
yield line
|
||||
|
||||
# FIXME remove, unused now
|
||||
def diff_old(self, dest_file, temp_file, comment_string):
|
||||
"""diff dest_file and temp_file, returns True if files differ, False if they are the same"""
|
||||
self._cfg.debug.stdout(f'Diffing {dest_file} and {temp_file}, comment: {comment_string}', 3)
|
||||
if not os.path.isfile(dest_file):
|
||||
self._cfg.debug.stdout(f'dest_file {dest_file} does not exist.', 3)
|
||||
return True
|
||||
if not os.path.isfile(temp_file):
|
||||
self._cfg.debug.stderr(f'Temporary file {temp_file} does not exist, this should not happen.', 0, 'ERROR')
|
||||
sys.exit(1)
|
||||
|
||||
fp1 = open(temp_file)
|
||||
fp2 = open(dest_file)
|
||||
|
||||
for line1, line2 in zip(self.read_skip_comment(fp1, comment_string), self.read_skip_comment(fp2, comment_string)):
|
||||
if line1 != line2:
|
||||
fp1.close()
|
||||
fp2.close()
|
||||
self._cfg.debug.stdout(f'{dest_file} differs from generated config', 3)
|
||||
return True
|
||||
fp1.close()
|
||||
fp2.close()
|
||||
self._cfg.debug.stdout(f'{dest_file} is the same as generated config', 3)
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def sanitize_input(fp, comment_string):
|
||||
"""Read line from filehandle fp and skip all empty (whitespace) lines and lines starting with comment_string
|
||||
return result as set
|
||||
"""
|
||||
ret = set()
|
||||
for line in fp:
|
||||
line = line[:-1]
|
||||
if ((comment_string != "" and not re.match("^"+re.escape(comment_string), line)) and line != "" and
|
||||
not re.match(r"^\s+$", line)):
|
||||
ret.add(line)
|
||||
return ret
|
||||
|
||||
def diff(self, dest_file, temp_file, comment_string):
|
||||
"""diff dest_file and temp_file, returns True if files differ, False if they are the same"""
|
||||
self._cfg.debug.stdout(f'Diffing {dest_file} and {temp_file}, comment: {comment_string}', 3)
|
||||
if not os.path.isfile(dest_file):
|
||||
self._cfg.debug.stdout(f'dest_file {dest_file} does not exist.', 3)
|
||||
return True
|
||||
if not os.path.isfile(temp_file):
|
||||
self._cfg.debug.stderr(f'Temporary file {temp_file} does not exist, this should not happen.', 0, 'ERROR')
|
||||
sys.exit(1)
|
||||
|
||||
# get temp_file and dest_file, remove comments and whitespaces
|
||||
temp_lines = self.sanitize_input(open(temp_file), comment_string)
|
||||
dest_lines = self.sanitize_input(open(dest_file), comment_string)
|
||||
# differences of temp_file and dest_file in both directions, if != 0: files differ
|
||||
return len(temp_lines.symmetric_difference(dest_lines)) != 0
|
||||
|
||||
def user_config_generated(self, filename):
|
||||
"""returns True if filename has been generated by userconfig, False else"""
|
||||
|
||||
if not os.path.isfile(filename):
|
||||
# filename does not exist, so it was not generated by userconfig
|
||||
return False
|
||||
|
||||
if not self._cfg.check("stamp"):
|
||||
# no STAMP in userconfig.cfg, so no way to check if file was generated by userconfig
|
||||
return False
|
||||
|
||||
fp = open(filename, "r")
|
||||
|
||||
for line in fp:
|
||||
if re.search(re.escape(self._cfg.get("stamp")), line):
|
||||
return True
|
||||
return False
|
||||
|
||||
def backup_file(self, filename):
|
||||
"""make backup of filename, returns True if backup is successful, False else"""
|
||||
if os.path.isfile(filename):
|
||||
self._cfg.debug.stdout(f'{filename} exists, finding backup name.', 3)
|
||||
backup_name = filename+".userconfig."+time.strftime("%F")
|
||||
test_backup_name = backup_name
|
||||
counter = 0
|
||||
while os.path.isfile(test_backup_name):
|
||||
counter += 1
|
||||
test_backup_name = backup_name+"."+str(counter)
|
||||
os.rename(filename, test_backup_name)
|
||||
self._cfg.debug.stdout(f'Renamed {filename} to {test_backup_name}', 1, 'SUCCESS')
|
||||
return True
|
||||
else:
|
||||
self._cfg.debug.stdout(f'{filename} does not exist, do not need backup.', 3)
|
||||
return False
|
||||
|
||||
def copy_file(self, sourcefile, dest_file):
|
||||
"""copy sourcefile to dest_file, returns True if successful, False else"""
|
||||
|
||||
if os.path.isfile(sourcefile):
|
||||
# sourcefile exists
|
||||
self._cfg.debug.stdout(f'Source file {sourcefile} exists, proceeding with copy.', 3)
|
||||
if not os.path.isfile(dest_file) or os.access(dest_file, os.W_OK):
|
||||
shutil.copy(sourcefile, dest_file)
|
||||
return True
|
||||
else:
|
||||
self._cfg.debug.stdout('Destination {dest_file} is not a file or not writable.', 0, 'ERROR')
|
||||
return False
|
67
userconfig/cfgfile.py
Normal file
67
userconfig/cfgfile.py
Normal file
@@ -0,0 +1,67 @@
|
||||
import configparser
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
class Conf(object):
|
||||
_confobj = None
|
||||
_cfgfiles = []
|
||||
debug = None
|
||||
|
||||
def __init__(self, filename=None, debug=None, force_filename=False):
|
||||
if debug:
|
||||
self.set_debug(debug)
|
||||
self._confobj = configparser.ConfigParser(dict(HOME=os.environ.get('HOME')))
|
||||
filenames = []
|
||||
if not force_filename:
|
||||
# default config files are $HOME/etc/userconfig2.conf and
|
||||
# {sys.prefix}/etc/userconfig2.conf
|
||||
if os.path.isfile(f'{os.environ.get("HOME")}/etc/userconfig2.conf'):
|
||||
filenames.append(f'{os.environ.get("HOME")}/etc/userconfig2.conf')
|
||||
if os.path.isfile(f'{sys.prefix}/etc/userconfig2.conf'):
|
||||
filenames.append(f'{sys.prefix}/etc/userconfig2.conf')
|
||||
# supplied filename will be read last, has highest priority
|
||||
if filename:
|
||||
filenames.append(filename)
|
||||
ret = self.set_filenames(filenames)
|
||||
if not ret:
|
||||
raise ValueError(f'Cannot open either configuration file: {",".join(filenames)}')
|
||||
|
||||
def set_debug(self, debug):
|
||||
self.debug = debug
|
||||
|
||||
def set_filenames(self, filenames):
|
||||
ret = self._confobj.read(filenames)
|
||||
if len(ret) == 0:
|
||||
return None
|
||||
self._cfgfiles = ret
|
||||
if self.debug:
|
||||
self.debug.stdout("Read config files: %s" % ", ".join(filenames), 2)
|
||||
return ret
|
||||
|
||||
def get(self, option, boolean=False, section='userconfig'):
|
||||
try:
|
||||
if boolean:
|
||||
return self._confobj.getboolean(section, option)
|
||||
else:
|
||||
return self._confobj.get(section, option)
|
||||
except (configparser.NoOptionError, configparser.NoSectionError) as e:
|
||||
raise ValueError(f'Option {option} does not exist in section {section}: {e}')
|
||||
|
||||
def set(self, option, value, section='userconfig'):
|
||||
try:
|
||||
self._confobj.set(section, option, value)
|
||||
except configparser.NoSectionError as e:
|
||||
raise ValueError(f'Section {section} does not exist: {e}')
|
||||
|
||||
def get_items(self, section='userconfig'):
|
||||
try:
|
||||
return self._confobj.items(section)
|
||||
except configparser.NoSectionError as e:
|
||||
raise ValueError(f'Section {section} does not exist: {e}')
|
||||
|
||||
def check(self, option, section='userconfig'):
|
||||
return self._confobj.has_option(section, option)
|
||||
|
||||
def sections(self):
|
||||
return self._confobj.sections()
|
35
userconfig/checks.py
Normal file
35
userconfig/checks.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import platform
|
||||
|
||||
|
||||
def get_hostname():
|
||||
node_name = platform.node()
|
||||
if node_name.count("."):
|
||||
return node_name.split(".")[0]
|
||||
else:
|
||||
return node_name
|
||||
|
||||
|
||||
def get_arch():
|
||||
return platform.system()
|
||||
|
||||
|
||||
def get_domain():
|
||||
node_name = platform.node()
|
||||
if node_name.count("."):
|
||||
return '.'.join(node_name.split('.')[1:])
|
||||
else:
|
||||
return ''
|
||||
|
||||
|
||||
def check_class(class_tuple):
|
||||
(prio, category, value, path) = class_tuple
|
||||
if category == 'Arch':
|
||||
return get_arch() == value
|
||||
elif category == 'Host':
|
||||
return get_hostname() == value
|
||||
elif category == 'Domain':
|
||||
return get_domain() == value
|
||||
elif value == '': # if value is empty, we cannot filter anything, so it matches always
|
||||
return True
|
||||
else:
|
||||
return False
|
6
userconfig2.conf
Normal file
6
userconfig2.conf
Normal file
@@ -0,0 +1,6 @@
|
||||
[userconfig]
|
||||
configdir = %(HOME)s/.userconfig
|
||||
configfile = userconfig2.cfg
|
||||
debug = 0
|
||||
stamp = %%userconfig_generated 1.0%%
|
||||
stampreplace = $userconfig_stamp$
|
Reference in New Issue
Block a user