Skip to content

Commit

Permalink
Add an inverse function to flatten_mapping
Browse files Browse the repository at this point in the history
`deepen_mapping` recostruct a deep mapping from a flat one given a
separator character and reference mapping to reconstruct paths.

Part of the ground work for
freeipa#26
  • Loading branch information
Martin Babinsky authored and martbab committed Dec 16, 2016
1 parent a81f9ca commit 668ff13
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
38 changes: 38 additions & 0 deletions ipadocker/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,44 @@ def flatten_mapping(mapping, separator='_', path=()):
return flat_mapping


def deepen_mapping(mapping, separator='_',
reference=None, path=()):
"""
re-create a nested mapping from a flat representation created by
@flatten_mapping. A reference dictionary is needed to unambiguously
construct all paths
:param mapping: flat mapping to transform
:param separator: separator that was used to concatenate keys in the
original nested mapping
:param path: stack holding keys of previous nesting levels
"""
if reference is None:
reference = constants.DEFAULT_CONFIG

deep_mapping = {}

key_prefix = ''

if path:
key_prefix = separator.join(path)

for key, value in reference.items():
path_to_set = path + (key,)
if isinstance(value, dict):
deep_mapping[key] = deepen_mapping(
mapping,
separator=separator,
reference=value,
path=path_to_set)
else:
flat_key = separator.join([key_prefix, key]) if key_prefix else key
if flat_key in mapping:
deep_mapping[key] = mapping[flat_key]

return deep_mapping


class IPADockerConfig(object):
"""
An object which encapsulates the merged default options and options
Expand Down
11 changes: 11 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,14 @@ def test_flattened_mapping():
"""
flat_mapping = config.flatten_mapping(NESTED_MAPPING)
assert flat_mapping == FLAT_MAPPING


def test_deepened_mapping():
"""
Tests that the `deepen_mapping` function does its job
"""

nested_mapping = config.deepen_mapping(FLAT_MAPPING,
reference=NESTED_MAPPING)

assert nested_mapping == NESTED_MAPPING

0 comments on commit 668ff13

Please sign in to comment.