From b348b2451d14dedd7f7b4486bd1d054a52dcabf2 Mon Sep 17 00:00:00 2001 From: snixtho Date: Sun, 29 Sep 2024 15:31:21 +0200 Subject: [PATCH] fix dependency sorting --- .../Util/SortedModuleCollection.cs | 53 ++++++++++--------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/src/EvoSC.Modules/Util/SortedModuleCollection.cs b/src/EvoSC.Modules/Util/SortedModuleCollection.cs index 3985da2ca..70619f730 100644 --- a/src/EvoSC.Modules/Util/SortedModuleCollection.cs +++ b/src/EvoSC.Modules/Util/SortedModuleCollection.cs @@ -33,54 +33,57 @@ IEnumerator IEnumerable.GetEnumerator() private List GetSortedModules() { - var dependencyGraph = MakeDependencyGraph(); - EnsureDependenciesExists(dependencyGraph); - + var graph = MakeDependencyGraph(); + EnsureDependenciesExists(graph); + var sortedDependencies = new List(); while (true) { - string? selected = null; - - foreach (var dependent in dependencyGraph) + bool found = false; + + foreach (var node in graph) { - if (dependent.Value.Count != 0) + if (node.Value.Count > 0) { continue; } - - sortedDependencies.Add(_modules[dependent.Key]); - RemoveDependent(dependencyGraph, dependent); - - selected = dependent.Key; + + sortedDependencies.Add(_modules[node.Key]); + RemoveNodeReferences(graph, node.Key); + found = true; } - if (selected == null) + if (!found) { break; } } - - DetectCycle(dependencyGraph); + + if (graph.Count > 0) + { + throw new DependencyCycleException(graph); + } + return sortedDependencies; } - private static void RemoveDependent(DependencyGraph dependencyGraph, KeyValuePair> dependent) + private static void RemoveNodeReferences(DependencyGraph graph, string nodeName) { - foreach (var dependencies in dependencyGraph) + if (graph.ContainsKey(nodeName)) { - if (dependencies.Value.Contains(dependencies.Key)) - { - dependencies.Value.Remove(dependent.Key); - } + graph.Remove(nodeName); } - - if (dependencyGraph.ContainsKey(dependent.Key)) + + foreach (var node in graph) { - dependencyGraph.Remove(dependent.Key); + if (node.Value.Contains(nodeName)) + { + node.Value.Remove(nodeName); + } } } - + private DependencyGraph MakeDependencyGraph() { var adjList = new Dictionary>();