1
0
mirror of https://github.com/kellyjonbrazil/jc.git synced 2025-07-13 01:20:24 +02:00

fix ini parser for edge cases with non-value keys

This commit is contained in:
Kelly Brazil
2024-02-09 17:13:19 -08:00
parent 082d4a3f80
commit 3cfc5e3e3c
2 changed files with 21 additions and 13 deletions

View File

@ -75,7 +75,7 @@ import uuid
class info(): class info():
"""Provides parser metadata (version, author, etc.)""" """Provides parser metadata (version, author, etc.)"""
version = '2.1' version = '2.2'
description = 'INI file parser' description = 'INI file parser'
author = 'Kelly Brazil' author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com' author_email = 'kellyjonbrazil@gmail.com'
@ -87,14 +87,10 @@ class info():
__version__ = info.version __version__ = info.version
class MyDict(dict): def _none_to_empty_string(data):
def __setitem__(self, key, value): if data is None:
# convert None values to empty string return ''
if value is None: return data
self[key] = ''
else:
super().__setitem__(key, value)
def _process(proc_data): def _process(proc_data):
@ -110,13 +106,18 @@ def _process(proc_data):
Dictionary representing the INI file. Dictionary representing the INI file.
""" """
# remove quotation marks from beginning and end of values # remove quotation marks from beginning and end of values
# and convert None to empty string
for k, v in proc_data.items(): for k, v in proc_data.items():
if isinstance(v, dict): if isinstance(v, dict):
for key, value in v.items(): for key, value in v.items():
v[key] = jc.utils.remove_quotes(value) value = _none_to_empty_string(value)
value = jc.utils.remove_quotes(value)
v[key] = value
continue continue
proc_data[k] = jc.utils.remove_quotes(v) v = _none_to_empty_string(v)
v = jc.utils.remove_quotes(v)
proc_data[k] = v
return proc_data return proc_data
@ -143,7 +144,6 @@ def parse(data, raw=False, quiet=False):
if jc.utils.has_data(data): if jc.utils.has_data(data):
ini_parser = configparser.ConfigParser( ini_parser = configparser.ConfigParser(
dict_type = MyDict,
allow_no_value=True, allow_no_value=True,
interpolation=None, interpolation=None,
default_section=None, default_section=None,
@ -175,4 +175,3 @@ def parse(data, raw=False, quiet=False):
raw_output.update(temp_dict) raw_output.update(temp_dict)
return raw_output if raw else _process(raw_output) return raw_output if raw else _process(raw_output)

View File

@ -104,6 +104,15 @@ key5 = "quoted"
""" """
self.assertEqual(jc.parsers.ini.parse(self.generic_ini_single_quote, quiet=True), self.generic_ini_single_quote_json) self.assertEqual(jc.parsers.ini.parse(self.generic_ini_single_quote, quiet=True), self.generic_ini_single_quote_json)
def test_ini_single_key_no_value(self):
"""
Test ini file with a single item with no value. This caused issues in jc v.1.25.0
"""
data = '''[data]
novalue
'''
expected = {"data":{"novalue":""}}
self.assertEqual(jc.parsers.ini.parse(data, quiet=True), expected)
if __name__ == '__main__': if __name__ == '__main__':