Comments not preserved on merge
tkeffer opened this issue · comments
Tom Keffer commented
Using ConfigObj v5.0.6, consider this:
import sys
from StringIO import StringIO
from configobj import ConfigObj
c = ConfigObj(StringIO("""[Section1]"""))
d = ConfigObj(StringIO("""[Section1]
# This is a Section2 comment
[[Section2]]
option2 = foo
"""))
c.merge(d)
c.write(sys.stdout)
The output is:
[Section1]
[[Section2]]
option2 = foo
while I would have expected
[Section1]
# This is a Section2 comment
[[Section2]]
option2 = foo
Irina Truong commented
+1, we have this issue in pgcli: dbcli/pgcli#1240.
Rob Dennis commented
makes sense and thanks for the MR; adding to 5.1.0 milestone
Tom Keffer commented
I should add that parentage is also not preserved on merge. This is what we do to get around these V5 limitations:
from configobj import Section
def merge_config(self_config, indict):
"""Merge and patch a config file"""
# Do a ConfigObj merge:
self_config.merge(indict)
# Then fix comments and parentage:
patch_config(self_config, indict)
def patch_config(self_config, indict):
"""The ConfigObj merge does not transfer over parentage, nor comments. This function
fixes these limitations.
"""
for key in self_config:
if isinstance(self_config[key], Section) \
and key in indict and isinstance(indict[key], Section):
self_config[key].parent = self_config
self_config[key].main = self_config.main
self_config.comments[key] = indict.comments[key]
self_config.inline_comments[key] = indict.inline_comments[key]
patch_config(self_config[key], indict[key])