Refactor mod list to return an object with a list of errors

So we don't throw and catch like Java
This commit is contained in:
2025-03-17 20:38:52 +01:00
parent 86a7c16194
commit fb8d3195db
4 changed files with 387 additions and 85 deletions

View File

@@ -4,6 +4,15 @@ import 'package:rimworld_modman/logger.dart';
import 'package:rimworld_modman/mod.dart';
import 'package:xml/xml.dart';
class LoadOrder {
final List<String> loadOrder = [];
final List<String> errors = [];
LoadOrder();
bool get hasErrors => errors.isNotEmpty;
}
class ModList {
String configPath = '';
String modsPath = '';
@@ -208,9 +217,8 @@ class ModList {
}
}
List<List<String>> checkIncompatibilities() {
List<List<String>> checkIncompatibilities(List<String> activeModIds) {
List<List<String>> conflicts = [];
List<String> activeModIds = activeMods.keys.toList();
// Only check each pair once
for (final modId in activeModIds) {
@@ -227,13 +235,16 @@ class ModList {
}
/// Generate a load order for active mods
List<String> generateLoadOrder() {
LoadOrder generateLoadOrder([LoadOrder? loadOrder]) {
loadOrder ??= LoadOrder();
// Check for incompatibilities first
final conflicts = checkIncompatibilities();
final conflicts = checkIncompatibilities(activeMods.keys.toList());
if (conflicts.isNotEmpty) {
throw Exception(
"Incompatible mods selected: ${conflicts.map((c) => "${c[0]} and ${c[1]}").join(', ')}",
);
for (final conflict in conflicts) {
loadOrder.errors.add(
"Incompatible mods selected: ${conflict[0]} and ${conflict[1]}",
);
}
}
// Reset all marks for topological sort
@@ -243,11 +254,10 @@ class ModList {
mod.position = -1;
}
final result = <String>[];
int position = 0;
// Topological sort
void visit(Mod mod) {
void visit(Mod mod, LoadOrder loadOrder) {
if (!mod.enabled) {
mod.visited = true;
return;
@@ -255,7 +265,7 @@ class ModList {
if (mod.mark) {
final cyclePath =
mods.values.where((m) => m.mark).map((m) => m.name).toList();
throw Exception(
loadOrder.errors.add(
"Cyclic dependency detected: ${cyclePath.join(' -> ')}",
);
}
@@ -266,26 +276,26 @@ class ModList {
// Visit all dependencies
for (String depId in mod.dependencies) {
if (activeMods.containsKey(depId)) {
visit(mods[depId]!);
visit(mods[depId]!, loadOrder);
}
}
mod.mark = false;
mod.visited = true;
mod.position = position++;
result.add(mod.id);
loadOrder.loadOrder.add(mod.id);
}
}
// Visit all nodes
for (final mod in mods.values) {
if (!mod.visited) {
visit(mod);
visit(mod, loadOrder);
}
}
// Optimize for soft constraints
return _optimizeSoftConstraints(result);
return _optimizeSoftConstraints(loadOrder: loadOrder);
}
/// Calculate how many soft constraints are satisfied
@@ -326,18 +336,20 @@ class ModList {
}
/// Optimize for soft constraints using a greedy approach
List<String> _optimizeSoftConstraints(
List<String> initialOrder, {
LoadOrder _optimizeSoftConstraints({
int maxIterations = 5,
LoadOrder? loadOrder,
}) {
List<String> bestOrder = List.from(initialOrder);
Map<String, int> scoreInfo = _calculateSoftConstraintsScore(bestOrder);
loadOrder ??= LoadOrder();
Map<String, int> scoreInfo = _calculateSoftConstraintsScore(
loadOrder.loadOrder,
);
int bestScore = scoreInfo['satisfied']!;
int total = scoreInfo['total']!;
if (total == 0 || bestScore == total) {
// All constraints satisfied or no constraints, sort by size where possible
return _sortSizeWithinConstraints(bestOrder);
return _sortSizeWithinConstraints(loadOrder: loadOrder);
}
// Use a limited number of improvement passes
@@ -345,18 +357,18 @@ class ModList {
bool improved = false;
// Try moving each mod to improve score
for (int i = 0; i < bestOrder.length; i++) {
String modId = bestOrder[i];
for (int i = 0; i < loadOrder.loadOrder.length; i++) {
String modId = loadOrder.loadOrder[i];
Mod mod = mods[modId]!;
// Calculate current local score for this mod
Map<String, int> currentPositions = {};
for (int idx = 0; idx < bestOrder.length; idx++) {
currentPositions[bestOrder[idx]] = idx;
for (int idx = 0; idx < loadOrder.loadOrder.length; idx++) {
currentPositions[loadOrder.loadOrder[idx]] = idx;
}
// Try moving this mod to different positions
for (int newPos = 0; newPos < bestOrder.length; newPos++) {
for (int newPos = 0; newPos < loadOrder.loadOrder.length; newPos++) {
if (newPos == i) continue;
// Skip if move would break hard dependencies
@@ -365,7 +377,7 @@ class ModList {
// Moving earlier
// Check if any mod between newPos and i depends on this mod
for (int j = newPos; j < i; j++) {
String depModId = bestOrder[j];
String depModId = loadOrder.loadOrder[j];
if (mods[depModId]!.dependencies.contains(modId)) {
skip = true;
break;
@@ -375,7 +387,7 @@ class ModList {
// Moving later
// Check if this mod depends on any mod between i and newPos
for (int j = i + 1; j <= newPos; j++) {
String depModId = bestOrder[j];
String depModId = loadOrder.loadOrder[j];
if (mod.dependencies.contains(depModId)) {
skip = true;
break;
@@ -386,7 +398,7 @@ class ModList {
if (skip) continue;
// Create a new order with the mod moved
List<String> newOrder = List.from(bestOrder);
List<String> newOrder = List.from(loadOrder.loadOrder);
newOrder.removeAt(i);
newOrder.insert(newPos, modId);
@@ -398,7 +410,8 @@ class ModList {
if (newScore > bestScore) {
bestScore = newScore;
bestOrder = newOrder;
loadOrder.loadOrder.clear();
loadOrder.loadOrder.addAll(newOrder);
improved = true;
break; // Break inner loop, move to next mod
}
@@ -411,17 +424,18 @@ class ModList {
}
// After optimizing for soft constraints, sort by size where possible
return _sortSizeWithinConstraints(bestOrder);
return _sortSizeWithinConstraints(loadOrder: loadOrder);
}
/// Sort mods by size within compatible groups
List<String> _sortSizeWithinConstraints(List<String> order) {
LoadOrder _sortSizeWithinConstraints({LoadOrder? loadOrder}) {
loadOrder ??= LoadOrder();
// Find groups of mods that can be reordered without breaking constraints
List<List<String>> groups = [];
List<String> currentGroup = [];
for (int i = 0; i < order.length; i++) {
String modId = order[i];
for (int i = 0; i < loadOrder.loadOrder.length; i++) {
String modId = loadOrder.loadOrder[i];
Mod mod = mods[modId]!;
if (currentGroup.isEmpty) {
@@ -475,43 +489,55 @@ class ModList {
}
// Reconstruct the order
List<String> result = [];
loadOrder.loadOrder.clear();
for (List<String> group in groups) {
result.addAll(group);
loadOrder.loadOrder.addAll(group);
}
return result;
return loadOrder;
}
List<String> loadDependencies(
LoadOrder loadDependencies(
String modId, [
LoadOrder? loadOrder,
List<String>? toEnable,
Map<String, bool>? seen,
]) {
final mod = mods[modId]!;
loadOrder ??= LoadOrder();
toEnable ??= <String>[];
seen ??= <String, bool>{};
for (final dep in mod.dependencies) {
if (!mods.containsKey(dep)) {
loadOrder.errors.add(
'Missing dependency: ${mod.name} requires mod with ID $dep',
);
continue;
}
final depMod = mods[dep]!;
if (seen[dep] == true) {
throw Exception('Cyclic dependency detected: $modId -> $dep');
loadOrder.errors.add('Cyclic dependency detected: $modId -> $dep');
continue;
}
seen[dep] = true;
toEnable.add(depMod.id);
loadDependencies(depMod.id, toEnable, seen);
loadDependencies(depMod.id, loadOrder, toEnable, seen);
}
return toEnable;
return loadOrder;
}
List<String> loadRequired() {
LoadOrder loadRequired([LoadOrder? loadOrder]) {
loadOrder ??= LoadOrder();
final toEnable = <String>[];
for (final modid in activeMods.keys) {
loadDependencies(modid, toEnable);
loadDependencies(modid, loadOrder, toEnable);
}
for (final modid in toEnable) {
setEnabled(modid, true);
}
return generateLoadOrder();
return generateLoadOrder(loadOrder);
}
ModList copyWith({