ソースを参照

Merged in aznashwan/coriolis-core/endpoint-options-utils (pull request #115)

Endpoint options utils
Nashwan Azhari 8 年 前
コミット
32f72956c2
1 ファイル変更32 行追加0 行削除
  1. 32 0
      coriolis/utils.py

+ 32 - 0
coriolis/utils.py

@@ -409,3 +409,35 @@ def get_url_with_credentials(url, username, password):
         quote_url(username), quote_url(password or ''), netloc)
     parts = parts._replace(netloc=netloc)
     return parse.urlunsplit(parts)
+
+
+def get_unique_option_ids(resources, id_key="id", name_key="name"):
+    """Given a list of dictionaries with both the specified 'id_key' and
+    'name_key' in each, returns a list of strings, each identifying a certain
+    dictionary thusly:
+       - if the value under the 'name_key' of a dict is not unique among all
+         others, returns the value of the 'id_key'
+       - else, returns the value of the 'name_key
+    """
+    if not all([name_key in d and id_key in d for d in resources]):
+        raise KeyError(
+            "Some resources are missing the name key '%s' "
+            "or ID key '%s': %s" % (name_key, id_key, resources))
+
+    name_mappings = {}
+    for resource in resources:
+        if resource[name_key] in name_mappings:
+            name_mappings[resource[name_key]].append(resource[id_key])
+        else:
+            name_mappings[resource[name_key]] = [resource[id_key]]
+
+    identifiers = []
+    for name, ids in name_mappings.items():
+        # if it has only one id, it is unique, append name
+        if len(ids) == 1:
+            identifiers.append(name)
+        else:
+            # if it has multiple ids, append ids
+            identifiers.extend(ids)
+
+    return identifiers