Skip to content

Commit

Permalink
refactor: move filter_dict_keys to invenio_records
Browse files Browse the repository at this point in the history
  • Loading branch information
yashlamba authored and slint committed Feb 20, 2024
1 parent 5b0e99f commit 39aa799
Show file tree
Hide file tree
Showing 3 changed files with 2 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,10 @@
"""Community PID slug field."""
from uuid import UUID

from invenio_records.dictutils import filter_dict_keys
from invenio_records.systemfields import SystemField
from sqlalchemy.orm.exc import NoResultFound

from ....utils import filter_dict_keys


def is_valid_uuid(value):
"""Check if the provided value is a valid UUID."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@

"""Communities system field."""

from invenio_records.dictutils import filter_dict_keys
from invenio_records.systemfields import SystemField

from .....utils import filter_dict_keys
from .context import CommunitiesFieldContext
from .manager import CommunitiesRelationManager

Expand Down
35 changes: 0 additions & 35 deletions invenio_communities/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,38 +109,3 @@ def on_datastore_post_commit(sender, session):
users = role.users.all()
for user in users:
on_user_membership_change(Identity(user.id))


# FIXME: This function should be in invenio_records.dictutils
def filter_dict_keys(src, keys):
"""Filter a dictionary based on a list of key paths."""
# Split the keys into top-level and nested keys
top_level_keys = [key for key in keys if "." not in key]
nested_keys = [key for key in keys if "." in key]

# Filter the top-level keys
result = {key: src[key] for key in top_level_keys if key in src}

# Handle nested keys
for key in nested_keys:
parts = key.split(".")
current_dict = src
for part in parts[:-1]:
if part in current_dict:
current_dict = current_dict[part]
else:
break # Skip this key if the path does not exist
# Update the filtered dictionary with the nested key if it exists
if parts[-2] in result and parts[-1] in current_dict:
if parts[-2] not in result:
result[parts[-2]] = {}
result[parts[-2]][parts[-1]] = current_dict[parts[-1]]

# Handle specific case for top-level keys that are dictionaries but not explicitly mentioned
for key in src:
if key not in result and isinstance(src[key], dict):
subkeys = [k.split(".", 1)[1] for k in keys if k.startswith(f"{key}.")]
if subkeys:
result[key] = filter_dict_keys(src[key], subkeys)

return result

0 comments on commit 39aa799

Please sign in to comment.