def get_dependency_sorted_dict()

in src/Saas.Identity/Saas.IdentityProvider/deployment/script/get-dependency-sorted-policies.py [0:0]


def get_dependency_sorted_dict(dict: dict) -> dict:
    sorted_policy_dict = {}

    # start with all the policies that don't depend on anything
    dependecy_list = [None]

    while len(dependecy_list) > 0:
        matching_dict = {}
        for id, (depend_on, xmlfile) in dict.items():
            if depend_on in dependecy_list:
                matching_dict[id] = (depend_on, xmlfile)
        for id, (depend_on, xmlfile) in matching_dict.items():
            # reset dependecy_list
            dependecy_list.clear()
            # add the found dependecy to the dependecy_list of next level
            dependecy_list.append(id)
            # add found policy to sorted dict
            sorted_policy_dict[id] = xmlfile
        if len(matching_dict) == 0:
            # no more policies found, break
            break

    if len(sorted_policy_dict) != len(dict):
        print(f"Found {len(sorted_policy_dict)} policies in total of {len(dict)} policies.")
        print("The following policies are not sorted:")
        for id, depend_on in dict.items():
            if id not in sorted_policy_dict:
                print(f"{id} depends on {depend_on}")
        raise Exception("Not all policies are sorted.")

    return sorted_policy_dict