From 8a6afb15f5d4e63b971fcc57027eb903703dd506 Mon Sep 17 00:00:00 2001 From: Paolo Ambrosio Date: Sat, 13 May 2023 07:47:38 +0100 Subject: [PATCH] Cleanup empty directories --- src/Core/Mods/JsgmeFileInstaller.cs | 36 ++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/src/Core/Mods/JsgmeFileInstaller.cs b/src/Core/Mods/JsgmeFileInstaller.cs index 1ac2438..8be57d9 100644 --- a/src/Core/Mods/JsgmeFileInstaller.cs +++ b/src/Core/Mods/JsgmeFileInstaller.cs @@ -76,18 +76,42 @@ private static void BackupFile(string path) public static void RestoreOriginalState(string dstPath, IEnumerable files) { - foreach (var file in files) + var installedPaths = files.Select(file => Path.Combine(dstPath, file)); + foreach (var path in installedPaths) { - var dstFilePath = Path.Combine(dstPath, file); - if (File.Exists(dstFilePath)) + // Some mods have duplicate entries, so files might have been removed already + if (File.Exists(path)) { - File.Delete(dstFilePath); + File.Delete(path); } - RestoreFile(dstFilePath); + RestoreFile(path); } + DeleteEmptyDirectories(dstPath, installedPaths); } - + + private static void DeleteEmptyDirectories(string dstRootPath, IEnumerable filePaths) { + var dirs = filePaths.SelectMany(dstFilePath => AncestorsUpTo(dstRootPath, dstFilePath)).Distinct().OrderByDescending(name => name.Length); + foreach (var dir in dirs) + { + // Some mods have duplicate entries, so files might have been removed already + if (Directory.Exists(dir) && !Directory.EnumerateFileSystemEntries(dir).Any()) + { + Directory.Delete(dir); + } + } + } + + private static IEnumerable AncestorsUpTo(string root, string path) + { + var ancestors = new List(); + for (var dir = Directory.GetParent(path); dir is not null && dir.FullName != root; dir = dir.Parent) + { + ancestors.Add(dir.FullName); + } + return ancestors; + } + private static void RestoreFile(string path) { var backupFilePath = BackupFileName(path);