return ConfigParser._read(self, fptr, fname)
- def _set_into_file(self, section, option, value, replace_opt=None):
+ def _set_into_file(self, section, option, value, replace_opt=None, comment=None):
"""Set the value in the file contents
Parsing logic and lot of the code was copied directly from the
cursect = None # None, or a str
optname = None
new_line = '%s = %s\n' % (option, value)
+ new_lineno = None
new_line_written = False
last_section_line = None
+ # add line break for comment
+ if comment is not None:
+ if not comment.endswith('\n'):
+ comment += '\n'
+
lineno = -1
for lineno in range(len(self._flines)):
line = self._flines[lineno]
(optname == option or optname == replace_opt):
if not new_line_written:
self._flines[lineno] = new_line
+ new_lineno = lineno
new_line_written = True
else:
# Just remove all matching lines, if we've
# Insert new key
if not new_line_written:
if last_section_line is not None:
- self._flines.insert(last_section_line + 1, new_line)
+ if comment is not None:
+ self._flines.insert(last_section_line + 1, comment)
+ self._flines.insert(last_section_line + 2, new_line)
+ else:
+ self._flines.insert(last_section_line + 1, new_line)
else:
if lineno >= 0:
self._flines.insert(lineno + 1, '\n')
self._flines.insert(lineno + 2, '[%s]\n' % section)
- self._flines.insert(lineno + 3, new_line)
+ if comment is not None:
+ self._flines.insert(lineno + 3, comment)
+ self._flines.insert(lineno + 4, new_line)
+ else:
+ self._flines.insert(lineno + 3, new_line)
+ else:
+ if comment is not None and new_lineno is not None:
+ self._flines.insert(new_lineno, comment)
+
- def set_into_file(self, section, option, value, replace_opt=None):
+ def set_into_file(self, section, option, value, replace_opt=None, comment=None):
"""When set new value, need to update the readin file lines,
which can be saved back to file later.
"""
# If the code reach here, it means the section and key are ok
try:
- self._set_into_file(section, option, value, replace_opt)
+ self._set_into_file(section, option, value, replace_opt, comment)
except Exception as err:
# This really shouldn't happen, we've already once parsed the file
# contents successfully.
#For python3.x set() to call add(), it will show error: TypeError: unhashable type: 'BrainConfigParser'
#This is because for set() in python3.x it can only add which can be hashed, such as int, float, tuple, str
dirty = []
+ comment = "# WARNING: passwordx can be decoded, don't expose gbs.conf to the outside"
all_sections = set()
for layer in self._cfgparsers:
cfgparser.set_into_file(sec,
key + 'x',
encode_passwd(plainpass),
- key)
+ key,
+ comment)
if (cfgparser not in dirty):
dirty.append(cfgparser)