sort_env_files_by_rule working with EnvFile list
This commit is contained in:
parent
ddfec4ccdc
commit
83d082f9cb
1 changed files with 16 additions and 8 deletions
|
|
@ -9,22 +9,29 @@ class EnvFile(NamedTuple):
|
|||
config: dict[str, str]
|
||||
env_type: str
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"EnvFile(type={self.env_type})"
|
||||
|
||||
|
||||
class DependencyRule(NamedTuple):
|
||||
child: str
|
||||
dependency: str
|
||||
|
||||
|
||||
def _is_rule_satisfied(in_list: list, rule: DependencyRule) -> bool:
|
||||
child_index = in_list.index(rule.child)
|
||||
parent_index = in_list.index(rule.dependency)
|
||||
return parent_index < child_index
|
||||
def _is_rule_satisfied(in_list: list, rule: DependencyRule) -> tuple[bool, int]:
|
||||
child_indices = [index for index, element in enumerate(in_list) if element.env_type == rule.child]
|
||||
child_index = min(child_indices)
|
||||
# child_index = in_list.index(rule.child)
|
||||
parent_indices = [index for index, element in enumerate(in_list) if element.env_type == rule.dependency]
|
||||
parent_index = max(parent_indices)
|
||||
# parent_index = in_list.index(rule.dependency)
|
||||
return parent_index < child_index, parent_index
|
||||
|
||||
|
||||
def sort_env_files_by_rule(env_list: list, rules: list[DependencyRule]) -> list:
|
||||
def sort_env_files_by_rule(env_list: list[EnvFile], rules: list[DependencyRule]) -> list:
|
||||
in_list = env_list.copy()
|
||||
|
||||
def swap_item_with_previous(in_list: list, index: int):
|
||||
def swap_item_with_previous(in_list: list[EnvFile], index: int):
|
||||
"""swaps item at index N with item at index N-1"""
|
||||
assert index > 0, "cannot swap with negative index"
|
||||
in_list[index], in_list[index - 1] = in_list[index - 1], in_list[index]
|
||||
|
|
@ -32,11 +39,12 @@ def sort_env_files_by_rule(env_list: list, rules: list[DependencyRule]) -> list:
|
|||
for _ in range(10_000):
|
||||
rule_satisfied: list[bool] = []
|
||||
for rule in rules:
|
||||
if _is_rule_satisfied(in_list, rule):
|
||||
is_rule_satisfied, parent_index = _is_rule_satisfied(in_list, rule)
|
||||
if is_rule_satisfied:
|
||||
rule_satisfied.append(True)
|
||||
else:
|
||||
rule_satisfied.append(False)
|
||||
parent_index = in_list.index(rule.dependency)
|
||||
# parent_index = in_list.index(rule.dependency)
|
||||
swap_item_with_previous(in_list, parent_index)
|
||||
if all(rule_satisfied):
|
||||
return in_list
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue