Skip to content

Commit

Permalink
fix: check before truncating new line
Browse files Browse the repository at this point in the history
  • Loading branch information
hetangmodi-crest committed Aug 12, 2024
1 parent 9762c65 commit f881c4f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
12 changes: 8 additions & 4 deletions addonfactory_splunk_conf_parser_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,8 @@ def _read(self, fp, fpname):
if isinstance(val, list):
options[name] = "\n".join(val)

# As the type of fp is not defined in RawConfigParser which is the parent class so we have to go with Any.
# As the type of `fp` is not defined in RawConfigParser (parent class)
# we define the type of `fp` as Any
def write(self, fp: Any, *args) -> None:
"""
Override the write() method to write comments
Expand Down Expand Up @@ -193,9 +194,12 @@ def write(self, fp: Any, *args) -> None:
# write the separator line for stanza
fp.write("\n")

# remove the trailing lines in a file, as the content should be written as-is
fp.seek(fp.tell() - 1, SEEK_SET)
fp.truncate()
# multiple lines are added when there are stanzas/sections and its properties,
# hence we check if there are stanzas/sections before truncating the trailing newline
if self._defaults or self._sections:
# remove the trailing lines in a file, as the content should be written as-is
fp.seek(fp.tell() - 1, SEEK_SET)
fp.truncate()

def optionxform(self, optionstr):
return optionstr
Expand Down
48 changes: 48 additions & 0 deletions test_addonfactory_splunk_conf_parser_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,54 @@ def test_write(self):
[eventtype=some_eventtype]
tag = enabled
"""
parser = conf_parser.TABConfigParser()
parser.read_string(conf)
output = io.StringIO()
parser.write(output)
self.assertEqual(conf, output.getvalue())

def test_write_empty(self):
conf = ""
parser = conf_parser.TABConfigParser()
parser.read_string(conf)
output = io.StringIO()
parser.write(output)
self.assertEqual(conf, output.getvalue())

def test_write_only_comments(self):
conf = """
#
# some comment here
#
"""
parser = conf_parser.TABConfigParser()
parser.read_string(conf)
output = io.StringIO()
parser.write(output)
self.assertEqual(conf, output.getvalue())

def test_write_only_default_section(self):
conf = """
#
# some comment here
#
[DEFAULT]
attrib_one = value_one
attrib_two = value_two
"""
parser = conf_parser.TABConfigParser()
parser.read_string(conf)
output = io.StringIO()
parser.write(output)
self.assertEqual(conf, output.getvalue())

def test_write_fields_outside(self):
conf = """
#
#
out_field = out_value
out_field_two = out_value_two
"""
parser = conf_parser.TABConfigParser()
parser.read_string(conf)
Expand Down

0 comments on commit f881c4f

Please sign in to comment.