Andy Mikhailenko avatar Andy Mikhailenko committed 24a9079

Add structure unfolding functions

Comments (0)

Files changed (1)

monk/manipulation.py

 import types
 
 
+__all__ = [
+    # mergers
+    'ValueMerger', 'TypeMerger', 'DictMerger', 'ListMerger', 'FuncMerger',
+    'AnyMerger',
+    # functions
+    'merge_value', 'merged',
+    # helpers
+    'unfold_list_of_dicts', 'unfold_to_list'
+]
+
+
 class ValueMerger(object):
     """ Base class for value mergers.
     """
         result[key] = value
 
     return result
+
+
+def unfold_list_of_dicts(value, default_key):
+    """
+    [{...}] → [{...}]
+     {...}  → [{...}]
+    u'xyz'  → [{default_key: u'xyz'}]
+    """
+    if value is None:
+        return []
+    if isinstance(value, dict):
+        return [value]
+    if isinstance(value, unicode):
+        return [{default_key: value}]
+    if isinstance(value, list):
+        if not all(isinstance(x, dict) for x in value):
+            def _fix(x):
+                return {default_key: x} if isinstance(x, unicode) else x
+            return [_fix(x) for x in value]
+    return value
+
+
+def unfold_to_list(value):
+    """
+    [x] → [x]
+     x  → [x]
+    """
+    if value and not isinstance(value, list):
+        return [value]
+    else:
+        return value
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.