feat(packaging): add staged install transaction and logged file removal

Extracted files land in a staging folder inside the target and are moved into
place with backups of replaced files; a failed move rolls everything back.
Removal deletes only logged payload paths and prunes folders left empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:56:37 +00:00
1 parent d79ab1e41b
commit fc8df1f411
2 files changed
+278

No files matched your search

@@ -0,0 +1,175 @@
using Titano.Core.Diagnostics;
namespace Titano.Core.Packaging;
/// <summary>
/// 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); <see cref="Commit"/> 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.
/// </summary>
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; }
/// <summary>Where the new files are written before <see cref="Commit"/>.</summary>
public string StagingDirectory { get; }
/// <summary>Moves the staged files (payload-relative paths) into the target, all or nothing.</summary>
public void Commit(IReadOnlyCollection<string> 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);
}
}
}
/// <summary>Removes staging/backup folders left by an interrupted earlier run (they are always ours by name).</summary>
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);
}
}
}
/// <summary>Removes installed files by their logged payload paths, never anything else under the folder.</summary>
public static class InstalledFiles
{
/// <summary>
/// Deletes each listed file under <paramref name="root"/> and prunes folders the deletion left empty (the root
/// itself only when <paramref name="removeEmptyRoot"/>). Missing files count as removed; returns the paths that
/// could not be deleted, for example because a program still holds them open.
/// </summary>
public static IReadOnlyList<string> Remove(string root, IEnumerable<string> relativePaths, bool removeEmptyRoot = false)
{
var fullRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
var failed = new List<string>();
var folders = new HashSet<string>(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;
}
}
}