From 51db74f0b513ed757ac2eb0ce499617b8c935a1f Mon Sep 17 00:00:00 2001 From: Daniel Date: Sat, 2 Dec 2023 14:41:37 +0100 Subject: [PATCH] cleanup --- src/env_file_helper.py | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/src/env_file_helper.py b/src/env_file_helper.py index 2f52f28..20ca508 100644 --- a/src/env_file_helper.py +++ b/src/env_file_helper.py @@ -1,34 +1,37 @@ from typing import NamedTuple +from loguru import logger + class Rule(NamedTuple): child: 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) parent_index = in_list.index(rule.parent) return parent_index < child_index -def sort_by_rules(in_list: list, rules: list[Rule]) -> bool: - def move_item_down(in_list: list, index: int): - """moves item""" - # assert index > +def sort_env_files_by_rule(env_list: list, rules: list[Rule]) -> list: + in_list = env_list.copy() + + 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] - for _ in range(10000): + for _ in range(10_000): rule_satisfied: list[bool] = [] 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) parent_index = in_list.index(rule.parent) - move_item_down(in_list, parent_index) - else: - rule_satisfied.append(True) + swap_item_with_previous(in_list, parent_index) if all(rule_satisfied): - print("success") - return True - print("failed") - return False + return in_list + logger.error("could not find order that satisfys all rules") + raise ValueError