pax_global_header00006660000000000000000000000064136263130070014513gustar00rootroot0000000000000052 comment=68e3ca863b59ba2247d94b56db85c1a38a8bbb36 python-libconf-2.0.1/000077500000000000000000000000001362631300700144465ustar00rootroot00000000000000python-libconf-2.0.1/.gitignore000066400000000000000000000000731362631300700164360ustar00rootroot00000000000000__pycache__ *.egg-info/ *.pyc /.tox /build/ /dist/ /venv/ python-libconf-2.0.1/.travis.yml000066400000000000000000000002171362631300700165570ustar00rootroot00000000000000language: python python: - "2.7" - "3.4" - "3.5" - "3.6" - "3.7" dist: xenial sudo: yes install: - pip install tox-travis script: - tox python-libconf-2.0.1/LICENSE000066400000000000000000000020701362631300700154520ustar00rootroot00000000000000Copyright (c) 2016 Christian Aichinger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-libconf-2.0.1/MANIFEST.in000066400000000000000000000000511362631300700162000ustar00rootroot00000000000000include *.rst LICENSE tox.ini test/*.cfg python-libconf-2.0.1/README.rst000066400000000000000000000147061362631300700161450ustar00rootroot00000000000000======= libconf ======= libconf is a pure-Python reader/writer for configuration files in `libconfig format`_, which is often used in C/C++ projects. It's interface is similar to the `json`_ module: the four main methods are ``load()``, ``loads()``, ``dump()``, and ``dumps()``. Example usage:: import io, libconf >>> with io.open('example.cfg') as f: ... config = libconf.load(f) >>> config {'capabilities': {'can-do-arrays': [3, 'yes', True], 'can-do-lists': (True, 14880, ('sublist',), {'subgroup': 'ok'})}, 'version': 7, 'window': {'position': {'h': 600, 'w': 800, 'x': 375, 'y': 210}, 'title': 'libconfig example'}} >>> config['window']['title'] 'libconfig example' >>> config.window.title 'libconfig example' >>> print(libconf.dumps({'size': [10, 15], 'flag': True})) flag = True; size = [ 10, 15 ]; The data can be accessed either via indexing (``['title']``) or via attribute access ``.title``. Character encoding and escape sequences --------------------------------------- The recommended way to use libconf is with Unicode objects (``unicode`` on Python2, ``str`` on Python3). Input strings or streams for ``load()`` and ``loads()`` should be Unicode, as should be all strings contained in data structures passed to ``dump()`` and ``dumps()``. In ``load()`` and ``loads()``, escape sequences (such as ``\n``, ``\r``, ``\t``, or ``\xNN``) are decoded. Hex escapes (``\xNN``) are mapped to Unicode characters U+0000 through U+00FF. All other characters are passed though as-is. In ``dump()`` and ``dumps()``, unprintable characters below U+0080 are escaped as ``\n``, ``\r``, ``\t``, ``\f``, or ``\xNN`` sequences. Characters U+0080 and above are passed through as-is. Writing libconfig files ----------------------- Reading libconfig files is easy. Writing is made harder by two factors: * libconfig's distinction between `int and int64`_: ``2`` vs. ``2L`` * libconfig's distinction between `lists`_ and `arrays`_, and the limitations on arrays The first point concerns writing Python ``int`` values. Libconf dumps values that fit within the C/C++ 32bit ``int`` range without an "L" suffix. For larger values, an "L" suffix is automatically added. To force the addition of an "L" suffix even for numbers within the 32 bit integer range, wrap the integer in a ``LibconfInt64`` class. Examples:: dumps({'value': 2}) # Returns "value = 2;" dumps({'value': 2**32}) # Returns "value = 4294967296L;" dumps({'value': LibconfInt64(2)}) # Explicit int64, returns "value = 2L;" The second complication arises from distinction between `lists`_ and `arrays`_ in the libconfig language. Lists are enclosed by ``()`` parenthesis, and can contain arbitrary values within them. Arrays are enclosed by ``[]`` brackets, and have significant limitations: all values must be scalar (int, float, bool, string) and must be of the same type. Libconf uses the following convention: * it maps libconfig ``()``-lists to Python tuples, which also use the ``()`` syntax. * it maps libconfig ``[]``-arrays to Python lists, which also use the ``[]`` syntax. This provides nice symmetry between the two languages, but has the drawback that dumping Python lists inherits the limitations of libconfig's arrays. To explicitly control whether lists or arrays are dumped, wrap the Python list/tuple in a ``LibconfList`` or ``LibconfArray``. Examples:: # Libconfig lists (=Python tuples) can contain arbitrary complex types: dumps({'libconf_list': (1, True, {})}) # Libconfig arrays (=Python lists) must contain scalars of the same type: dumps({'libconf_array': [1, 2, 3]}) # Equivalent, but more explit by using LibconfList/LibconfArray: dumps({'libconf_list': LibconfList([1, True, {}])}) dumps({'libconf_array': LibconfArray([1, 2, 3])}) Comparison to other Python libconfig libraries ---------------------------------------------- `Pylibconfig2`_ is another pure-Python libconfig reader. It's API is based on the C++ interface, instead of the Python `json`_ module. It's licensed under GPLv3, which makes it unsuitable for use in a large number of projects. `Python-libconfig`_ is a library that provides Python bindings for the libconfig++ C++ library. While permissively licensed (BSD), it requires a compilation step upon installation, which can be a drawback. I wrote libconf (this library) because both of the existing libraries didn't fit my requirements. I had a work-related project which is not open source (ruling out pylibconfig2) and I didn't want the deployment headache of python-libconfig. Further, I enjoy writing parsers and this seemed like a nice opportunity :-) Release notes ------------- * **2.0.1**, released on 2019-11-21 - Allow trailing commas in lists and arrays for improved compatibility with the libconfig C implementation. Thanks to nibua-r for reporting this issue. * **2.0.0**, released on 2018-11-23 - Output validation for ``dump()`` and ``dumps()``: raise an exception when dumping data that can not be read by the C libconfig implementation. *This change may raise exceptions on code that worked with <2.0.0!* - Add ``LibconfList``, ``LibconfArray``, ``LibconfInt64`` classes for more fine-grained control of the ``dump()``/``dumps()`` output. - Fix ``deepcopy()`` of ``AttrDict`` classes (thanks AnandTella). * **1.0.1**, released on 2017-01-06 - Drastically improve performance when reading larger files - Several smaller improvements and fixes * **1.0.0**, released on 2016-10-26: - Add the ability to write libconf files (``dump()`` and ``dumps()``, thanks clarkli86 and eatsan) - Several smaller improvements and fixes * **0.9.2**, released on 2016-09-09: - Fix compatibility with Python versions older than 2.7.6 (thanks AnandTella) .. _libconfig format: http://www.hyperrealm.com/libconfig/libconfig_manual.html#Configuration-Files .. _json: https://docs.python.org/3/library/json.html .. _lists: https://hyperrealm.github.io/libconfig/libconfig_manual.html#Lists .. _arrays: https://hyperrealm.github.io/libconfig/libconfig_manual.html#Arrays .. _int and int64: https://hyperrealm.github.io/libconfig/libconfig_manual.html#g_t64_002dbit-Integer-Values .. _Pylibconfig2: https://github.com/heinzK1X/pylibconfig2 .. _Python-libconfig: https://github.com/cnangel/python-libconfig python-libconf-2.0.1/libconf.py000066400000000000000000000543171362631300700164460ustar00rootroot00000000000000#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evaluate basestring def isstr(s): return isinstance(s, basestring) def isint(i): return isinstance(i, (int, long)) LONGTYPE = long except NameError: def isstr(s): return isinstance(s, str) def isint(i): return isinstance(i, int) LONGTYPE = int # Bounds to determine when an "L" suffix should be used during dump(). SMALL_INT_MIN = -2**31 SMALL_INT_MAX = 2**31 - 1 ESCAPE_SEQUENCE_RE = re.compile(r''' ( \\x.. # 2-digit hex escapes | \\[\\'"abfnrtv] # Single-character escapes )''', re.UNICODE | re.VERBOSE) SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE) UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]') # load() logic ############## def decode_escapes(s): '''Unescape libconfig string literals''' def decode_match(match): return codecs.decode(match.group(0), 'unicode-escape') return ESCAPE_SEQUENCE_RE.sub(decode_match, s) class AttrDict(collections.OrderedDict): '''OrderedDict subclass giving access to string keys via attribute access This class derives from collections.OrderedDict. Thus, the original order of the config entries in the input stream is maintained. ''' def __getattr__(self, attr): # Take care that getattr() raises AttributeError, not KeyError. # Required e.g. for hasattr(), deepcopy and OrderedDict. try: return self.__getitem__(attr) except KeyError: raise AttributeError("Attribute %r not found" % attr) class ConfigParseError(RuntimeError): '''Exception class raised on errors reading the libconfig input''' pass class ConfigSerializeError(TypeError): '''Exception class raised on errors serializing a config object''' pass class Token(object): '''Base class for all tokens produced by the libconf tokenizer''' def __init__(self, type, text, filename, row, column): self.type = type self.text = text self.filename = filename self.row = row self.column = column def __str__(self): return "%r in %r, row %d, column %d" % ( self.text, self.filename, self.row, self.column) class FltToken(Token): '''Token subclass for floating point values''' def __init__(self, *args, **kwargs): super(FltToken, self).__init__(*args, **kwargs) self.value = float(self.text) class IntToken(Token): '''Token subclass for integral values''' def __init__(self, *args, **kwargs): super(IntToken, self).__init__(*args, **kwargs) self.is_long = self.text.endswith('L') self.is_hex = (self.text[1:2].lower() == 'x') self.value = int(self.text.rstrip('L'), 0) if self.is_long: self.value = LibconfInt64(self.value) class BoolToken(Token): '''Token subclass for booleans''' def __init__(self, *args, **kwargs): super(BoolToken, self).__init__(*args, **kwargs) self.value = (self.text[0].lower() == 't') class StrToken(Token): '''Token subclass for strings''' def __init__(self, *args, **kwargs): super(StrToken, self).__init__(*args, **kwargs) self.value = decode_escapes(self.text[1:-1]) def compile_regexes(token_map): return [(cls, type, re.compile(regex)) for cls, type, regex in token_map] class Tokenizer: '''Tokenize an input string Typical usage: tokens = list(Tokenizer("").tokenize("""a = 7; b = ();""")) The filename argument to the constructor is used only in error messages, no data is loaded from the file. The input data is received as argument to the tokenize function, which yields tokens or throws a ConfigParseError on invalid input. Include directives are not supported, they must be handled at a higher level (cf. the TokenStream class). ''' token_map = compile_regexes([ (FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|' r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'), (IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'), (IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'), (IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'), (IntToken, 'integer', r'[-+]?[0-9]+'), (BoolToken, 'boolean', r'(?i)(true|false)\b'), (StrToken, 'string', r'"([^"\\]|\\.)*"'), (Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'), (Token, '}', r'\}'), (Token, '{', r'\{'), (Token, ')', r'\)'), (Token, '(', r'\('), (Token, ']', r'\]'), (Token, '[', r'\['), (Token, ',', r','), (Token, ';', r';'), (Token, '=', r'='), (Token, ':', r':'), ]) def __init__(self, filename): self.filename = filename self.row = 1 self.column = 1 def tokenize(self, string): '''Yield tokens from the input string or throw ConfigParseError''' pos = 0 while pos < len(string): m = SKIP_RE.match(string, pos=pos) if m: skip_lines = m.group(0).split('\n') if len(skip_lines) > 1: self.row += len(skip_lines) - 1 self.column = 1 + len(skip_lines[-1]) else: self.column += len(skip_lines[0]) pos = m.end() continue for cls, type, regex in self.token_map: m = regex.match(string, pos=pos) if m: yield cls(type, m.group(0), self.filename, self.row, self.column) self.column += len(m.group(0)) pos = m.end() break else: raise ConfigParseError( "Couldn't load config in %r row %d, column %d: %r" % (self.filename, self.row, self.column, string[pos:pos+20])) class TokenStream: '''Offer a parsing-oriented view on tokens Provide several methods that are useful to parsers, like ``accept()``, ``expect()``, ... The ``from_file()`` method is the preferred way to read input files, as it handles include directives, which the ``Tokenizer`` class does not do. ''' def __init__(self, tokens): self.position = 0 self.tokens = list(tokens) @classmethod def from_file(cls, f, filename=None, includedir='', seenfiles=None): '''Create a token stream by reading an input file Read tokens from `f`. If an include directive ('@include "file.cfg"') is found, read its contents as well. The `filename` argument is used for error messages and to detect circular imports. ``includedir`` sets the lookup directory for included files. ``seenfiles`` is used internally to detect circular includes, and should normally not be supplied by users of is function. ''' if filename is None: filename = getattr(f, 'name', '') if seenfiles is None: seenfiles = set() if filename in seenfiles: raise ConfigParseError("Circular include: %r" % (filename,)) seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it. tokenizer = Tokenizer(filename=filename) lines = [] tokens = [] for line in f: m = re.match(r'@include "(.*)"$', line.strip()) if m: tokens.extend(tokenizer.tokenize(''.join(lines))) lines = [re.sub(r'\S', ' ', line)] includefilename = decode_escapes(m.group(1)) includefilename = os.path.join(includedir, includefilename) try: includefile = open(includefilename, "r") except IOError: raise ConfigParseError("Could not open include file %r" % (includefilename,)) with includefile: includestream = cls.from_file(includefile, filename=includefilename, includedir=includedir, seenfiles=seenfiles) tokens.extend(includestream.tokens) else: lines.append(line) tokens.extend(tokenizer.tokenize(''.join(lines))) return cls(tokens) def peek(self): '''Return (but do not consume) the next token At the end of input, ``None`` is returned. ''' if self.position >= len(self.tokens): return None return self.tokens[self.position] def accept(self, *args): '''Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, return None. ''' token = self.peek() if token is None: return None for arg in args: if token.type == arg: self.position += 1 return token return None def expect(self, *args): '''Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, raise a ConfigParseError. ''' t = self.accept(*args) if t is not None: return t self.error("expected: %r" % (args,)) def error(self, msg): '''Raise a ConfigParseError at the current input position''' if self.finished(): raise ConfigParseError("Unexpected end of input; %s" % (msg,)) else: t = self.peek() raise ConfigParseError("Unexpected token %s; %s" % (t, msg)) def finished(self): '''Return ``True`` if the end of the token stream is reached.''' return self.position >= len(self.tokens) class Parser: '''Recursive descent parser for libconfig files Takes a ``TokenStream`` as input, the ``parse()`` method then returns the config file data in a ``json``-module-style format. ''' def __init__(self, tokenstream): self.tokens = tokenstream def parse(self): return self.configuration() def configuration(self): result = self.setting_list_or_empty() if not self.tokens.finished(): raise ConfigParseError("Expected end of input but found %s" % (self.tokens.peek(),)) return result def setting_list_or_empty(self): result = AttrDict() while True: s = self.setting() if s is None: return result result[s[0]] = s[1] def setting(self): name = self.tokens.accept('name') if name is None: return None self.tokens.expect(':', '=') value = self.value() if value is None: self.tokens.error("expected a value") self.tokens.accept(';', ',') return (name.text, value) def value(self): acceptable = [self.scalar_value, self.array, self.list, self.group] return self._parse_any_of(acceptable) def scalar_value(self): # This list is ordered so that more common tokens are checked first. acceptable = [self.string, self.boolean, self.integer, self.float, self.hex, self.integer64, self.hex64] return self._parse_any_of(acceptable) def value_list_or_empty(self): return tuple(self._comma_separated_list_or_empty(self.value)) def scalar_value_list_or_empty(self): return self._comma_separated_list_or_empty(self.scalar_value) def array(self): return self._enclosed_block('[', self.scalar_value_list_or_empty, ']') def list(self): return self._enclosed_block('(', self.value_list_or_empty, ')') def group(self): return self._enclosed_block('{', self.setting_list_or_empty, '}') def boolean(self): return self._create_value_node('boolean') def integer(self): return self._create_value_node('integer') def integer64(self): return self._create_value_node('integer64') def hex(self): return self._create_value_node('hex') def hex64(self): return self._create_value_node('hex64') def float(self): return self._create_value_node('float') def string(self): t_first = self.tokens.accept('string') if t_first is None: return None values = [t_first.value] while True: t = self.tokens.accept('string') if t is None: break values.append(t.value) return ''.join(values) def _create_value_node(self, tokentype): t = self.tokens.accept(tokentype) if t is None: return None return t.value def _parse_any_of(self, nonterminals): for fun in nonterminals: result = fun() if result is not None: return result return None def _comma_separated_list_or_empty(self, nonterminal): values = [] while True: v = nonterminal() if v is None: return values values.append(v) if not self.tokens.accept(','): return values def _enclosed_block(self, start, nonterminal, end): if not self.tokens.accept(start): return None result = nonterminal() self.tokens.expect(end) return result def load(f, filename=None, includedir=''): '''Load the contents of ``f`` (a file-like object) to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> with open('test/example.cfg') as f: ... config = libconf.load(f) >>> config['window']['title'] 'libconfig example' >>> config.window.title 'libconfig example' ''' if isinstance(f.read(0), bytes): raise TypeError("libconf.load() input file must by unicode") tokenstream = TokenStream.from_file(f, filename=filename, includedir=includedir) return Parser(tokenstream).parse() def loads(string, filename=None, includedir=''): '''Load the contents of ``string`` to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> config = libconf.loads('window: { title: "libconfig example"; };') >>> config['window']['title'] 'libconfig example' >>> config.window.title 'libconfig example' ''' try: f = io.StringIO(string) except TypeError: raise TypeError("libconf.loads() input string must by unicode") return load(f, filename=filename, includedir=includedir) # dump() logic ############## class LibconfList(tuple): pass class LibconfArray(list): pass class LibconfInt64(LONGTYPE): pass def is_long_int(i): '''Return True if argument should be dumped as int64 type Either because the argument is an instance of LibconfInt64, or because it exceeds the 32bit integer value range. ''' return (isinstance(i, LibconfInt64) or not (SMALL_INT_MIN <= i <= SMALL_INT_MAX)) def dump_int(i): '''Stringize ``i``, append 'L' suffix if necessary''' return str(i) + ('L' if is_long_int(i) else '') def dump_string(s): '''Stringize ``s``, adding double quotes and escaping as necessary Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and ``\t``. Escape all remaining unprintable characters in ``\xFF``-style. The returned string will be surrounded by double quotes. ''' s = (s.replace('\\', '\\\\') .replace('"', '\\"') .replace('\f', r'\f') .replace('\n', r'\n') .replace('\r', r'\r') .replace('\t', r'\t')) s = UNPRINTABLE_CHARACTER_RE.sub( lambda m: r'\x{:02x}'.format(ord(m.group(0))), s) return '"' + s + '"' def get_dump_type(value): '''Get the libconfig datatype of a value Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array), ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool), ``'f'`` (float), or ``'s'`` (string). Produces the proper type for LibconfList, LibconfArray, LibconfInt64 instances. ''' if isinstance(value, dict): return 'd' if isinstance(value, tuple): return 'l' if isinstance(value, list): return 'a' # Test bool before int since isinstance(True, int) == True. if isinstance(value, bool): return 'b' if isint(value): if is_long_int(value): return 'i64' else: return 'i' if isinstance(value, float): return 'f' if isstr(value): return 's' return None def get_array_value_dtype(lst): '''Return array value type, raise ConfigSerializeError for invalid arrays Libconfig arrays must only contain scalar values and all elements must be of the same libconfig data type. Raises ConfigSerializeError if these invariants are not met. Returns the value type of the array. If an array contains both int and long int data types, the return datatype will be ``'i64'``. ''' array_value_type = None for value in lst: dtype = get_dump_type(value) if dtype not in {'b', 'i', 'i64', 'f', 's'}: raise ConfigSerializeError( "Invalid datatype in array (may only contain scalars):" "%r of type %s" % (value, type(value))) if array_value_type is None: array_value_type = dtype continue if array_value_type == dtype: continue if array_value_type == 'i' and dtype == 'i64': array_value_type = 'i64' continue if array_value_type == 'i64' and dtype == 'i': continue raise ConfigSerializeError( "Mixed types in array (all elements must have same type):" "%r of type %s" % (value, type(value))) return array_value_type def dump_value(key, value, f, indent=0): '''Save a value of any libconfig type This function serializes takes ``key`` and ``value`` and serializes them into ``f``. If ``key`` is ``None``, a list-style output is produced. Otherwise, output has ``key = value`` format. ''' spaces = ' ' * indent if key is None: key_prefix = '' key_prefix_nl = '' else: key_prefix = key + ' = ' key_prefix_nl = key + ' =\n' + spaces dtype = get_dump_type(value) if dtype == 'd': f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl)) dump_dict(value, f, indent + 4) f.write(u'{}}}'.format(spaces)) elif dtype == 'l': f.write(u'{}{}(\n'.format(spaces, key_prefix_nl)) dump_collection(value, f, indent + 4) f.write(u'\n{})'.format(spaces)) elif dtype == 'a': f.write(u'{}{}[\n'.format(spaces, key_prefix_nl)) value_dtype = get_array_value_dtype(value) # If int array contains one or more Int64, promote all values to i64. if value_dtype == 'i64': value = [LibconfInt64(v) for v in value] dump_collection(value, f, indent + 4) f.write(u'\n{}]'.format(spaces)) elif dtype == 's': f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value))) elif dtype == 'i' or dtype == 'i64': f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value))) elif dtype == 'f' or dtype == 'b': f.write(u'{}{}{}'.format(spaces, key_prefix, value)) else: raise ConfigSerializeError("Can not serialize object %r of type %s" % (value, type(value))) def dump_collection(cfg, f, indent=0): '''Save a collection of attributes''' for i, value in enumerate(cfg): dump_value(None, value, f, indent) if i < len(cfg) - 1: f.write(u',\n') def dump_dict(cfg, f, indent=0): '''Save a dictionary of attributes''' for key in cfg: if not isstr(key): raise ConfigSerializeError("Dict keys must be strings: %r" % (key,)) dump_value(key, cfg[key], f, indent) f.write(u';\n') def dumps(cfg): '''Serialize ``cfg`` into a libconfig-formatted ``str`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). Returns the formatted string. ''' str_file = io.StringIO() dump(cfg, str_file) return str_file.getvalue() def dump(cfg, f): '''Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like object with a ``write()`` method. ''' if not isinstance(cfg, dict): raise ConfigSerializeError( 'dump() requires a dict as input, not %r of type %r' % (cfg, type(cfg))) dump_dict(cfg, f, 0) # main(): small example of how to use libconf ############################################# def main(): '''Open the libconfig file specified by sys.argv[1] and pretty-print it''' global output if len(sys.argv[1:]) == 1: with io.open(sys.argv[1], 'r', encoding='utf-8') as f: output = load(f) else: output = load(sys.stdin) dump(output, sys.stdout) if __name__ == '__main__': main() python-libconf-2.0.1/setup.cfg000066400000000000000000000001041362631300700162620ustar00rootroot00000000000000[metadata] description-file = README.rst [bdist_wheel] universal=1 python-libconf-2.0.1/setup.py000066400000000000000000000022411362631300700161570ustar00rootroot00000000000000from setuptools import setup setup( name='libconf', version='2.0.1', description="A pure-Python libconfig reader/writer with permissive license", long_description=open('README.rst').read(), author="Christian Aichinger", author_email="Greek0@gmx.net", url='https://github.com/Grk0/python-libconf', download_url='https://github.com/Grk0/python-libconf/tarball/2.0.1', license="MIT", py_modules=['libconf'], keywords='libconfig configuration parser library', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], ) python-libconf-2.0.1/test/000077500000000000000000000000001362631300700154255ustar00rootroot00000000000000python-libconf-2.0.1/test/circular1.cfg000066400000000000000000000000401362631300700177650ustar00rootroot00000000000000a = 5; @include "circular2.cfg" python-libconf-2.0.1/test/circular2.cfg000066400000000000000000000000401362631300700177660ustar00rootroot00000000000000b = 8; @include "circular1.cfg" python-libconf-2.0.1/test/example.cfg000066400000000000000000000003361362631300700175430ustar00rootroot00000000000000version = 7; window: { title: "libconfig example" position: { x: 375; y: 210; w: 800; h: 600; } }; capabilities: { can-do-lists: (true, 0x3A20, ("sublist"), {subgroup: "ok"}) can-do-arrays: [3, "yes", True] }; python-libconf-2.0.1/test/include.cfg000066400000000000000000000000251362631300700175260ustar00rootroot00000000000000include-works: true; python-libconf-2.0.1/test/test_attrdict.py000066400000000000000000000002651362631300700206570ustar00rootroot00000000000000import libconf # Tests for AttrDict behavior ############################# def test_attrdict_hasattr(): d = libconf.AttrDict() assert hasattr(d, 'no_such_attr') == False python-libconf-2.0.1/test/test_dump.py000066400000000000000000000125271362631300700200120ustar00rootroot00000000000000import io import pytest import libconf # Helper functions ################## def dump_value(key, value, **kwargs): str_file = io.StringIO() libconf.dump_value(key, value, str_file, **kwargs) return str_file.getvalue() def dump_collection(c, **kwargs): str_file = io.StringIO() libconf.dump_collection(c, str_file, **kwargs) return str_file.getvalue() def dump_dict(c, **kwargs): str_file = io.StringIO() libconf.dump_dict(c, str_file, **kwargs) return str_file.getvalue() # Actual tests ############## def test_dump_collection(): c = [1, 2, 3] c_dumped = dump_collection(c) assert c_dumped == '1,\n2,\n3' c = (1, 2, 3) c_dumped = dump_collection(c) assert c_dumped == '1,\n2,\n3' c = ((1, 2), (3)) c_dumped = dump_collection(c) assert c_dumped == '(\n 1,\n 2\n),\n3' c = ([1, 2], (3)) c_dumped = dump_collection(c) assert c_dumped == '[\n 1,\n 2\n],\n3' c = [[1, 2], (3)] c_dumped = dump_collection(c) assert c_dumped == '[\n 1,\n 2\n],\n3' c_dumped = dump_collection(c, indent=4) assert c_dumped == ' [\n 1,\n 2\n ],\n 3' def test_dump_dict_simple_string(): c = {'name': 'value'} c_dumped = dump_dict(c) assert c_dumped == 'name = "value";\n' def test_dump_dict_indentation_dicts(): c = {'a': {'b': 3}} c_dumped = dump_dict(c) assert c_dumped == 'a =\n{\n b = 3;\n};\n' def test_dump_dict_indentation_dicts_with_extra_indent(): c = {'a': {'b': 3}} c_dumped = dump_dict(c, indent=4) assert c_dumped == ' a =\n {\n b = 3;\n };\n' def test_dump_dict_indentation_dicts_within_lists(): c = {'a': ({'b': 3},)} c_dumped = dump_dict(c) assert c_dumped == 'a =\n(\n {\n b = 3;\n }\n);\n' def test_dump_string_escapes_backslashes(): s = r'abc \ def \ hij' c_dumped = libconf.dump_string(s) assert c_dumped == r'"abc \\ def \\ hij"' def test_dump_string_escapes_doublequotes(): s = r'abc "" def' c_dumped = libconf.dump_string(s) assert c_dumped == r'"abc \"\" def"' def test_dump_string_escapes_common_escape_characters(): s = '\f \n \r \t' c_dumped = libconf.dump_string(s) assert c_dumped == r'"\f \n \r \t"' def test_dump_string_escapes_unprintable_characters(): s = '\x00 \x1f \x7f' c_dumped = libconf.dump_string(s) assert c_dumped == r'"\x00 \x1f \x7f"' def test_dump_string_keeps_8bit_chars_intact(): s = '\x80 \x9d \xff' c_dumped = libconf.dump_string(s) assert c_dumped == '"\x80 \x9d \xff"' def test_dump_string_handles_unicode_strings(): s = u'\u2603' c_dumped = libconf.dump_string(s) assert c_dumped == u'"\u2603"' def test_dump_boolean(): c = (True, False) c_dumped = dump_collection(c) assert c_dumped == 'True,\nFalse' def test_dump_int(): assert libconf.dump_int(0) == '0' assert libconf.dump_int(-30) == '-30' assert libconf.dump_int(60) == '60' def test_dump_int32_has_no_l_suffix(): assert libconf.dump_int(2**31 - 1) == str(2**31 - 1) assert libconf.dump_int(-2**31) == str(-2**31) def test_dump_int64_has_l_suffix(): assert libconf.dump_int(2**31) == str(2**31) + 'L' assert libconf.dump_int(-2**31 - 1) == str(-2**31 - 1) + 'L' def test_dump_raises_on_string_input(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps("") def test_dump_raises_on_list_input(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps([]) def test_none_dict_value_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({'test': None}) def test_none_dict_key_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({None: 0}) def test_integer_dict_key_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({0: 0}) def test_invalid_value_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({'a': object()}) def test_array_with_composite_type_dict_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({'a': [{}]}) def test_array_with_composite_type_list_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({'a': [()]}) def test_array_with_composite_type_array_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({'a': [[]]}) def test_array_with_mixed_types_intstr_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({'a': [1, "str"]}) def test_array_with_mixed_types_intbool_raises(): with pytest.raises(libconf.ConfigSerializeError): libconf.dumps({'a': [1, True]}) def test_array_with_intint64(): c = {'a': [2, 2**65]} c_dumped = dump_dict(c).replace(" ", "").replace("\n", "") assert c_dumped == 'a=[2L,36893488147419103232L];' def test_LibconfArray_produces_array(): c = {'a': libconf.LibconfArray([1,2])} c_dumped = dump_dict(c).replace(" ", "").replace("\n", "") assert c_dumped == 'a=[1,2];' def test_LibconfList_produces_list(): c = {'a': libconf.LibconfList([1,2])} c_dumped = dump_dict(c).replace(" ", "").replace("\n", "") assert c_dumped == 'a=(1,2);' def test_LibconfInt64_produces_L_suffix(): c = {'a': libconf.LibconfInt64(2)} c_dumped = dump_dict(c).replace(" ", "").replace("\n", "") assert c_dumped == 'a=2L;' python-libconf-2.0.1/test/test_e2e.cfg000066400000000000000000000010761362631300700176240ustar00rootroot00000000000000# Example config appconfig: { version = 37; version-long = 370000000000000L; version-autolong = 370000000000000; name = "libconf", delimiter = faLse works = truE allows /* inline comments */ : 0x0A; eol-comments = 0x0aL; // C++ style comment list: (3, "chicken", (), {group: true}), sub_group: { /* C style comment */ sub_sub_group: { yes: "yes", @include "include.cfg" }; arr = [1, 2], str = "Strings " "are " /* c1 */ "joined despite " # c2 "comments"; }; } python-libconf-2.0.1/test/test_e2e.py000066400000000000000000000101721362631300700175120ustar00rootroot00000000000000import os import io import textwrap import pytest import libconf CURDIR = os.path.abspath(os.path.dirname(__file__)) # Tests for load() and loads() ############################## def test_loads_maintains_dict_order(): config = libconf.loads(u'''l: 1; i: 5; b: 3; c: 1; o: 9; n: 0; f: 7;''') assert ''.join(config.keys()) == 'libconf' def test_example_config(): example_file = os.path.join(CURDIR, 'test_e2e.cfg') with io.open(example_file, 'r', encoding='utf-8') as f: c = libconf.load(f, includedir=CURDIR) assert c.appconfig.version == 37 assert c.appconfig['version-long'] == 370000000000000 assert c.appconfig['version-autolong'] == 370000000000000 assert c.appconfig.name == "libconf" assert c.appconfig.delimiter == False assert c.appconfig.works == True assert c.appconfig.allows == 0xA assert c.appconfig['eol-comments'] == 0xA assert c.appconfig.list == (3, "chicken", (), dict(group=True)) assert c.appconfig.sub_group.sub_sub_group.yes == "yes" assert c.appconfig.sub_group.sub_sub_group['include-works'] == True assert c.appconfig.sub_group.arr == [1, 2] assert c.appconfig.sub_group.str == "Strings are joined despite comments"; def test_string_merging(): # Unicode characters are supported, \u escapes not. input = u"""s = "abc\x21def\n" /* comment */ "newline-" # second comment "here \u2603 \\u2603";""" assert libconf.loads(input).s == u"abc\x21def\nnewline-here \u2603 \\u2603" def test_nonexisting_include_raises(): input = u'''@include "/NON_EXISTING_FILE/DOESNT_EXIST"''' with pytest.raises(libconf.ConfigParseError): libconf.loads(input) def test_circular_include_raises(): circular_file = os.path.join(CURDIR, 'circular1.cfg') with io.open(circular_file, 'r', encoding='utf-8') as f: with pytest.raises(libconf.ConfigParseError): libconf.load(f, includedir=CURDIR) def test_loads_of_bytes_throws(): with pytest.raises(TypeError) as excinfo: libconf.loads(b'') assert 'libconf.loads' in str(excinfo.value) def test_load_of_BytesIO_throws(): with pytest.raises(TypeError) as excinfo: libconf.load(io.BytesIO(b'a: "37";')) assert 'libconf.load' in str(excinfo.value) def test_lists_support_trailing_comma(): config = libconf.loads(u'''a: (1, 2, 3,);''') assert config.a == (1, 2, 3) def test_arrays_support_trailing_comma(): config = libconf.loads(u'''a: [1, 2, 3,];''') assert config.a == [1, 2, 3] # Tests for dump() and dumps() ############################## def test_dump_special_characters(): d = {'a': ({'b': [u"\x00 \n \x7f abc \xff \u2603"]},)} s = libconf.dumps(d) expected = textwrap.dedent(u'''\ a = ( { b = [ "\\x00 \\n \\x7f abc \xff \u2603" ]; } ); ''') assert s == expected # Tests for dump-load round trips ################################# def test_dumps_roundtrip(): example_file = os.path.join(CURDIR, 'test_e2e.cfg') with io.open(example_file, 'r', encoding='utf-8') as f: c = libconf.load(f, includedir=CURDIR) c_dumped = libconf.loads(libconf.dumps(c)) assert c == c_dumped def test_dump_roundtrip(): example_file = os.path.join(CURDIR, 'test_e2e.cfg') with io.open(example_file, 'r', encoding='utf-8') as f: c = libconf.load(f, includedir=CURDIR) with io.StringIO() as f: libconf.dump(c, f) f.seek(0) c_dumped = libconf.load(f, includedir=CURDIR) assert c == c_dumped def test_dump_special_characters_roundtrip(): d = {'a': ({'b': [u"\x00 \n \x7f abc \xff \u2603"]},)} d2 = libconf.loads(libconf.dumps(d)) assert d == d2 def test_roundtrip_preserves_config_entry_order(): config = libconf.loads(u'''l: 1; i: 5; b: 3; c: 1; o: 9; n: 0; f: 7;''') dumped = libconf.dumps(config) reloaded = libconf.loads(dumped) assert ''.join(reloaded.keys()) == 'libconf' def test_roundtrip_of_int64_values(): s = u'a=2L;' s2 = libconf.dumps(libconf.loads(s)) assert s == s2.replace(' ', '').replace('\n', '') python-libconf-2.0.1/test/test_tokenize.py000066400000000000000000000074271362631300700207000ustar00rootroot00000000000000import pytest import libconf def test_float(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize(" 2. .5 0.75 1.0E1 " "+2. +.5 +0.75 +1.0E1 " "-2. -.5 -0.75 -1.0E1 " "2.E3 .5E6 0.75E9 1.0E1 " "2.E+3 .5E+6 0.75E+9 1.0E+1 " "2.E-3 .5E-6 0.75E-9 1.0E-1 " "2E1 -2e1 +2e1 5e-1 " )) assert [t.type for t in tokens] == ['float'] * 28 assert [t.value for t in tokens][0:4] == [2.0, 0.5, 0.75, 10.0] assert [t.value for t in tokens][4:8] == [2.0, 0.5, 0.75, 10.0] assert [t.value for t in tokens][8:12] == [-2.0, -0.5, -0.75, -10.0] assert [t.value for t in tokens][12:16] == [2E3, .5E6, .75E9, 10] assert [t.value for t in tokens][16:20] == [2E3, .5E6, .75E9, 10] assert [t.value for t in tokens][20:24] == [2E-3, .5E-6, .75E-9, 0.1] assert [t.value for t in tokens][24:28] == [20.0, -20.0, 20.0, 0.5] def test_hex64(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize("0x13AL 0XbcdL 0xefLL 0X456789ABLL")) assert [t.type for t in tokens] == ['hex64'] * 4 assert [t.value for t in tokens] == [0x13A, 0xBCD, 0xef, 0x456789AB] def test_hex(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize("0x13A 0Xbcd 0xef 0X456789AB")) assert [t.type for t in tokens] == ['hex'] * 4 assert [t.value for t in tokens] == [0x13A, 0xBCD, 0xef, 0x456789AB] def test_integer64(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize("10L +30L -15000000000LL")) assert [t.type for t in tokens] == ['integer64'] * 3 assert [t.value for t in tokens] == [10, 30, -15000000000] def test_integer(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize("10 +30 -15000000000")) assert [t.type for t in tokens] == ['integer'] * 3 assert [t.value for t in tokens] == [10, 30, -15000000000] def test_boolean(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize("true TRUE TrUe false FALSE FaLsE")) assert [t.type for t in tokens] == ['boolean'] * 6 assert [t.value for t in tokens] == [True, True, True, False, False, False] def test_string(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize( r'''"abc" "ab\"cd" "" "\x20\\\f\n\r\t"''')) assert [t.type for t in tokens] == ['string'] * 4 assert [t.value for t in tokens] == ['abc', 'ab"cd', '', ' \\\f\n\r\t'] def test_name(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize("ident IdenT I I32A true_value falseVal")) assert [t.type for t in tokens] == ['name'] * 6 assert [t.text for t in tokens] == ['ident', 'IdenT', 'I', 'I32A', 'true_value', 'falseVal'] def test_special(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize("}]){[(=:,;")) assert [t.type for t in tokens] == list("}]){[(=:,;") def test_location(): tokenizer = libconf.Tokenizer("") tokens = list(tokenizer.tokenize("\n 0 1\n 2")) assert [t.type for t in tokens] == ['integer'] * 3 assert [(t.row, t.column) for t in tokens] == [(2, 5), (2, 9), (3, 9)] def test_invalid_token(): tokenizer = libconf.Tokenizer("") with pytest.raises(libconf.ConfigParseError) as exc_info: list(tokenizer.tokenize("\n\n `xvz")) assert '' in str(exc_info.value) assert 'row 3' in str(exc_info.value) assert 'column 9' in str(exc_info.value) assert '`xvz' in str(exc_info.value) python-libconf-2.0.1/tox.ini000066400000000000000000000003631362631300700157630ustar00rootroot00000000000000[tox] envlist = py27, py33, py34, py35, py36, py37, flake8 [testenv] commands = py.test {posargs} # substitute with tox' positional arguments deps = pytest [testenv:flake8] deps = flake8 commands=flake8 --builtins=basestring,long libconf.py