diff --git a/src/env_file_helper.py b/src/env_file_helper.py index 5c9440d..8e88ad7 100644 --- a/src/env_file_helper.py +++ b/src/env_file_helper.py @@ -19,6 +19,7 @@ class DependencyRule(NamedTuple): def _get_indices_with_string(in_list: list[EnvFile], string: str) -> list[int]: + """returns all indices of items in in_list, where item.env_type matches string""" return [index for index, element in enumerate(in_list) if element.env_type == string] @@ -28,7 +29,11 @@ def _swap_item_with_previous(in_list: list[EnvFile], index: int): 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: +def is_rule_satisfied(in_list: list[EnvFile], rule: DependencyRule, swap=False) -> bool: + """returns if the ordering in in_list is compliant with the given rule + + if swap=True, some reordering will happen in case of a violated rule""" + 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) @@ -38,7 +43,8 @@ def _is_rule_satisfied(in_list: list[EnvFile], rule: DependencyRule) -> bool: if parent_index < child_index: results.append(True) else: - _swap_item_with_previous(in_list, parent_index) + if swap: + _swap_item_with_previous(in_list, parent_index) results.append(False) return all(results) @@ -49,7 +55,7 @@ def sort_env_files_by_rule(env_list: list[EnvFile], rules: list[DependencyRule]) for _ in range(10_000): rule_satisfied: list[bool] = [] for rule in rules: - rule_satisfied.append(_is_rule_satisfied(in_list, rule)) + rule_satisfied.append(is_rule_satisfied(in_list, rule, swap=True)) if all(rule_satisfied): return in_list