sort_env_files_by_rule now supports duplicate types
This commit is contained in:
parent
126873793c
commit
abdbe35daf
1 changed files with 24 additions and 19 deletions
|
|
@ -18,34 +18,39 @@ class DependencyRule(NamedTuple):
|
|||
dependency: str
|
||||
|
||||
|
||||
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]
|
||||
def _get_indices_with_string(in_list: list[EnvFile], string: str) -> list[int]:
|
||||
return [index for index, element in enumerate(in_list) if element.env_type == string]
|
||||
|
||||
|
||||
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]
|
||||
|
||||
|
||||
def _is_rule_satisfied(in_list: list[EnvFile], rule: DependencyRule) -> bool:
|
||||
child_indices = _get_indices_with_string(in_list, rule.child)
|
||||
parent_indices = _get_indices_with_string(in_list, rule.dependency)
|
||||
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
|
||||
results: list[bool] = []
|
||||
for child_index in child_indices:
|
||||
for parent_index in parent_indices:
|
||||
if parent_index < child_index:
|
||||
results.append(True)
|
||||
else:
|
||||
_swap_item_with_previous(in_list, parent_index)
|
||||
results.append(False)
|
||||
return all(results)
|
||||
|
||||
|
||||
def sort_env_files_by_rule(env_list: list[EnvFile], rules: list[DependencyRule]) -> list[EnvFile]:
|
||||
in_list = env_list.copy()
|
||||
|
||||
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]
|
||||
|
||||
for _ in range(10_000):
|
||||
rule_satisfied: list[bool] = []
|
||||
for rule in rules:
|
||||
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)
|
||||
swap_item_with_previous(in_list, parent_index)
|
||||
rule_satisfied.append(_is_rule_satisfied(in_list, rule))
|
||||
|
||||
if all(rule_satisfied):
|
||||
return in_list
|
||||
logger.error("could not find order that satisfys all rules")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue