Skip to content

Commit

Permalink
Merge pull request #13 from Never-Over/dedup-writes
Browse files Browse the repository at this point in the history
Dedup writes
  • Loading branch information
emdoyle authored Feb 13, 2024
2 parents 064cac8 + 7687457 commit c9a71f6
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions modguard/init.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from collections import defaultdict
from dataclasses import dataclass
from enum import Enum
import os
from itertools import chain
from typing import Optional

from modguard import errors, filesystem as fs
Expand All @@ -16,13 +18,44 @@ class WriteOperation(Enum):
PUBLIC = "public"


@dataclass
@dataclass(eq=True, frozen=True)
class FileWriteInformation:
location: str
operation: WriteOperation
member_name: str = ""


def deduplicate_writes(
writes: list[FileWriteInformation],
) -> list[FileWriteInformation]:
public_writes: defaultdict[str, list[FileWriteInformation]] = defaultdict(list)
result: list[FileWriteInformation] = []
# Basic uniqueness simplifies later checks
writes = list(set(writes))
for write in writes:
if write.operation == WriteOperation.BOUNDARY:
# Uniqueness check means all boundary writes should be kept
result.append(write)
elif write.operation == WriteOperation.PUBLIC:
root_public = FileWriteInformation(
location=write.location,
operation=WriteOperation.PUBLIC,
member_name="",
)
if write.location in public_writes and public_writes[write.location] == [
root_public
]:
# Root already public, skip this write
continue

if write.member_name in ["", "*"]:
# A blank public write clears all other public writes for the location
public_writes[write.location] = [root_public]
else:
public_writes[write.location].append(write)
return [*result, *chain(*public_writes.values())]


def init_project(root: str, exclude_paths: Optional[list[str]] = None) -> list[str]:
# Core functionality:
# * do nothing in any package already having a Boundary
Expand Down Expand Up @@ -101,7 +134,7 @@ def init_project(root: str, exclude_paths: Optional[list[str]] = None) -> list[s
f"Warning: Skipped member {member_name or import_mod_path} in {file_path}; could not mark as public"
)
# After we've completed our pass on inserting boundaries and public members, write to files
for write_op in write_operations:
for write_op in deduplicate_writes(write_operations):
try:
if write_op.operation == WriteOperation.BOUNDARY:
add_boundary(write_op.location)
Expand Down

0 comments on commit c9a71f6

Please sign in to comment.