new-features #5
1 changed files with 17 additions and 14 deletions
|
|
@ -1,34 +1,37 @@
|
||||||
from typing import NamedTuple
|
from typing import NamedTuple
|
||||||
|
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
|
||||||
class Rule(NamedTuple):
|
class Rule(NamedTuple):
|
||||||
child: str
|
child: str
|
||||||
parent: str
|
parent: str
|
||||||
|
|
||||||
|
|
||||||
def is_rule_satisfied(in_list: list, rule: Rule) -> bool:
|
def _is_rule_satisfied(in_list: list, rule: Rule) -> bool:
|
||||||
child_index = in_list.index(rule.child)
|
child_index = in_list.index(rule.child)
|
||||||
parent_index = in_list.index(rule.parent)
|
parent_index = in_list.index(rule.parent)
|
||||||
return parent_index < child_index
|
return parent_index < child_index
|
||||||
|
|
||||||
|
|
||||||
def sort_by_rules(in_list: list, rules: list[Rule]) -> bool:
|
def sort_env_files_by_rule(env_list: list, rules: list[Rule]) -> list:
|
||||||
def move_item_down(in_list: list, index: int):
|
in_list = env_list.copy()
|
||||||
"""moves item"""
|
|
||||||
# assert index >
|
def swap_item_with_previous(in_list: list, 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]
|
in_list[index], in_list[index - 1] = in_list[index - 1], in_list[index]
|
||||||
|
|
||||||
for _ in range(10000):
|
for _ in range(10_000):
|
||||||
rule_satisfied: list[bool] = []
|
rule_satisfied: list[bool] = []
|
||||||
for rule in rules:
|
for rule in rules:
|
||||||
if not is_rule_satisfied(in_list, rule):
|
if _is_rule_satisfied(in_list, rule):
|
||||||
|
rule_satisfied.append(True)
|
||||||
|
else:
|
||||||
rule_satisfied.append(False)
|
rule_satisfied.append(False)
|
||||||
parent_index = in_list.index(rule.parent)
|
parent_index = in_list.index(rule.parent)
|
||||||
move_item_down(in_list, parent_index)
|
swap_item_with_previous(in_list, parent_index)
|
||||||
else:
|
|
||||||
rule_satisfied.append(True)
|
|
||||||
if all(rule_satisfied):
|
if all(rule_satisfied):
|
||||||
print("success")
|
return in_list
|
||||||
return True
|
logger.error("could not find order that satisfys all rules")
|
||||||
print("failed")
|
raise ValueError
|
||||||
return False
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue