From f5e546c6fa7cba166284a0976887d6b82451d3e8 Mon Sep 17 00:00:00 2001 From: Kelly Brazil Date: Fri, 24 Jul 2020 16:16:24 -0700 Subject: [PATCH] add support for simple key/value pairs --- jc/parsers/ini.py | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/jc/parsers/ini.py b/jc/parsers/ini.py index fc162d49..86f8237d 100644 --- a/jc/parsers/ini.py +++ b/jc/parsers/ini.py @@ -2,7 +2,9 @@ Usage: - specify --ini as the first argument if the piped input is coming from an INI file + Specify --ini as the first argument if the piped input is coming from an INI file or any + simple key/value pair file. Delimiter can be '=' or ':'. Missing values are supported. + Comment prefix can be '#' or ';'. Comments must be on their own line. Compatibility: @@ -47,8 +49,8 @@ import configparser class info(): - version = '1.1' - description = 'INI file parser' + version = '1.2' + description = 'INI file parser. Also parses files/output containing simple key/value pairs' author = 'Kelly Brazil' author_email = 'kellyjonbrazil@gmail.com' details = 'Using configparser from the standard library' @@ -73,12 +75,26 @@ def process(proc_data): Dictionary representing an ini document: { - ini document converted to a dictionary - see configparser standard library documentation for more details + ini or key/value document converted to a dictionary - see configparser standard + library documentation for more details. + + Note: Values starting and ending with quotation marks will have the marks removed. + If you would like to keep the quotation markes, use the -r or raw=True argument. } """ + # remove quotation marks from beginning and end of values + for heading in proc_data: + # standard ini files with headers + if isinstance(proc_data[heading], dict): + for key, value in proc_data[heading].items(): + if value.startswith('"') and value.endswith('"'): + proc_data[heading][key] = value.lstrip('"').rstrip('"') + + # simple key/value files with no headers + else: + if proc_data[heading].startswith('"') and proc_data[heading].endswith('"'): + proc_data[heading] = proc_data[heading].lstrip('"').rstrip('"') - # No further processing return proc_data @@ -103,9 +119,17 @@ def parse(data, raw=False, quiet=False): if jc.utils.has_data(data): - ini = configparser.ConfigParser() - ini.read_string(data) - raw_output = {s: dict(ini.items(s)) for s in ini.sections()} + ini = configparser.ConfigParser(allow_no_value=True) + try: + ini.read_string(data) + raw_output = {s: dict(ini.items(s)) for s in ini.sections()} + + except configparser.MissingSectionHeaderError: + data = '[data]\n' + data + ini.read_string(data) + output_dict = {s: dict(ini.items(s)) for s in ini.sections()} + for key, value in output_dict['data'].items(): + raw_output[key] = value if raw: return raw_output