using Titano.Core.Diagnostics; namespace Titano.Core.Packaging; /// /// Installs a verified file set without leaving a half-updated folder. Files are first written into a staging /// folder inside the target (same volume, so moves are renames); then moves them into place, /// parking every replaced file in a backup folder. If any move fails, completed moves are undone in reverse order /// and the previous install is restored. Staging and backup folders are removed on dispose. /// public sealed class InstallTransaction : IDisposable { private const string StagingPrefix = ".setup-staging-"; private const string BackupPrefix = ".setup-backup-"; private readonly string _backup; public InstallTransaction(string targetDirectory) { TargetDirectory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(targetDirectory)); Directory.CreateDirectory(TargetDirectory); RemoveStaleFolders(TargetDirectory); var id = Guid.NewGuid().ToString("N")[..8]; StagingDirectory = Path.Combine(TargetDirectory, StagingPrefix + id); _backup = Path.Combine(TargetDirectory, BackupPrefix + id); Directory.CreateDirectory(StagingDirectory); } public string TargetDirectory { get; } /// Where the new files are written before . public string StagingDirectory { get; } /// Moves the staged files (payload-relative paths) into the target, all or nothing. public void Commit(IReadOnlyCollection relativePaths) { var completed = new List<(string Staged, string Target, string? Backup)>(relativePaths.Count); try { foreach (var relative in relativePaths) { var staged = PayloadPath.Resolve(StagingDirectory, relative); var target = PayloadPath.Resolve(TargetDirectory, relative); if (!File.Exists(staged)) throw new FileNotFoundException($"Staged file '{relative}' is missing.", staged); Directory.CreateDirectory(Path.GetDirectoryName(target)!); string? backup = null; if (File.Exists(target)) { backup = PayloadPath.Resolve(_backup, relative); Directory.CreateDirectory(Path.GetDirectoryName(backup)!); File.Move(target, backup); } try { File.Move(staged, target); } catch { if (backup is not null) File.Move(backup, target); throw; } completed.Add((staged, target, backup)); } } catch { Rollback(completed); throw; } } public void Dispose() { TryDeleteTree(StagingDirectory); TryDeleteTree(_backup); } private static void Rollback(List<(string Staged, string Target, string? Backup)> completed) { for (var i = completed.Count - 1; i >= 0; i--) { var (staged, target, backup) = completed[i]; try { File.Move(target, staged, overwrite: true); if (backup is not null) File.Move(backup, target); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Error("setup", $"Rollback could not restore '{target}'", ex); } } } /// Removes staging/backup folders left by an interrupted earlier run (they are always ours by name). private static void RemoveStaleFolders(string target) { foreach (var dir in Directory.EnumerateDirectories(target, ".setup-*")) { var name = Path.GetFileName(dir); if (name.StartsWith(StagingPrefix, StringComparison.Ordinal) || name.StartsWith(BackupPrefix, StringComparison.Ordinal)) TryDeleteTree(dir); } } private static void TryDeleteTree(string path) { try { if (Directory.Exists(path)) Directory.Delete(path, recursive: true); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("setup", $"Could not remove '{path}'", ex); } } } /// Removes installed files by their logged payload paths, never anything else under the folder. public static class InstalledFiles { /// /// Deletes each listed file under and prunes folders the deletion left empty (the root /// itself only when ). Missing files count as removed; returns the paths that /// could not be deleted, for example because a program still holds them open. /// public static IReadOnlyList Remove(string root, IEnumerable relativePaths, bool removeEmptyRoot = false) { var fullRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); var failed = new List(); var folders = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var relative in relativePaths) { var path = PayloadPath.Resolve(fullRoot, relative); try { if (File.Exists(path)) { File.SetAttributes(path, FileAttributes.Normal); File.Delete(path); } folders.Add(Path.GetDirectoryName(path)!); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("setup", $"Could not remove '{path}'", ex); failed.Add(relative); } } // Deepest folders first, so a parent is examined after its children were pruned. foreach (var folder in folders.OrderByDescending(f => f.Length)) { for (var dir = folder; dir.Length > fullRoot.Length; dir = Path.GetDirectoryName(dir)!) { if (!TryRemoveEmpty(dir)) break; } } if (removeEmptyRoot) TryRemoveEmpty(fullRoot); return failed; } private static bool TryRemoveEmpty(string dir) { try { if (!Directory.Exists(dir) || Directory.EnumerateFileSystemEntries(dir).Any()) return false; Directory.Delete(dir); return true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return false; } } }