From 2978e72e6ae4d4606efbc3d7b0d72f1ac74de440 Mon Sep 17 00:00:00 2001 From: Alexander Bokovoy Date: Wed, 1 Feb 2012 14:20:53 +0200 Subject: Add management of inifiles to allow manipulation of systemd units inifile_replace_variables() works similar to config_replace_variables() but allows to apply changes to specific section of an inifile. Inifiles are commonly used by freedesktop.org software and particularly used by systemd. When modifying inifile, all changes will be applied to specific section. Also fixes corner case in config_replace_variables() which would dublicate variables when adding them. --- ipapython/ipautil.py | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 99 insertions(+), 1 deletion(-) diff --git a/ipapython/ipautil.py b/ipapython/ipautil.py index 44580be8e..fc0010d6e 100644 --- a/ipapython/ipautil.py +++ b/ipapython/ipautil.py @@ -1259,7 +1259,7 @@ $)''', re.VERBOSE) new_vars = replacevars.copy() new_vars.update(appendvars) newvars_view = set(new_vars.keys()) - set(old_values.keys()) - append_view = (set(appendvars.keys()) - set(replacevars.keys())) - set(old_values.keys()) + append_view = (set(appendvars.keys()) - newvars_view) for item in newvars_view: new_config.write("%s=%s\n" % (item,new_vars[item])) for item in append_view: @@ -1276,6 +1276,104 @@ $)''', re.VERBOSE) return old_values +def inifile_replace_variables(filepath, section, replacevars=dict(), appendvars=dict()): + """ + Take a section-structured key=value based configuration file, and write new version + with certain values replaced or appended within the section + + All (key,value) pairs from replacevars and appendvars that were not found + in the configuration file, will be added there. + + It is responsibility of a caller to ensure that replacevars and + appendvars do not overlap. + + It is responsibility of a caller to back up file. + + returns dictionary of affected keys and their previous values + + One have to run restore_context(filepath) afterwards or + security context of the file will not be correct after modification + """ + pattern = re.compile(''' +(^ + \[ + (?P
.+) \] + (\s+((\#|;).*)?)? +$)|(^ + \s* + (?P