Skip to content

Commit

Permalink
chore(auth): optimize permissions sync
Browse files Browse the repository at this point in the history
  • Loading branch information
nijel committed Dec 11, 2024
1 parent 05157d6 commit 3f7714f
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions weblate/auth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
)

if TYPE_CHECKING:
from weblate.auth.models import Group, Role
from weblate.auth.models import Group, Permission, Role


def is_django_permission(permission: str):
Expand All @@ -38,23 +38,35 @@ def is_django_permission(permission: str):
return "_" in parts[1] and parts[1] != "add_more"


def migrate_permissions_list(model, permissions):
def migrate_permissions_list(
model: type[Permission], permissions: tuple[tuple[str, str], ...]
) -> set[int]:
ids = set()
# Update/create permissions
# Get all existing permissions
existing_objects = model.objects.filter(
codename__in=[perm[0] for perm in permissions]
)
existing = {permission.codename: permission for permission in existing_objects}

# Iterate over expected permissions
for code, name in permissions:
instance, created = model.objects.get_or_create(
codename=code, defaults={"name": name}
)
try:
instance = existing[code]
except KeyError:
# Missing, create one
instance = model.objects.create(codename=code, name=name)
else:
# Update if needed
if instance.name != name:
instance.name = name
instance.save(update_fields=["name"])
ids.add(instance.pk)
if not created and instance.name != name:
instance.name = name
instance.save(update_fields=["name"])
return ids


def migrate_permissions(model) -> None:
def migrate_permissions(model: type[Permission]) -> None:
"""Create permissions as defined in the data."""
ids = set()
ids: set[int] = set()
# Per object permissions
ids.update(migrate_permissions_list(model, PERMISSIONS))
# Global permissions
Expand All @@ -63,7 +75,7 @@ def migrate_permissions(model) -> None:
model.objects.exclude(id__in=ids).delete()


def migrate_roles(model, perm_model) -> set[str]:
def migrate_roles(model: type[Role], perm_model: type[Permission]) -> set[str]:
"""Create roles as defined in the data."""
result = set()
for role, permissions in ROLES:
Expand Down

0 comments on commit 3f7714f

Please sign in to comment.