Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

fix(revert): keep unreadable revert data instead of overwriting it

fatDuck4a6b70392a5f
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index e86fb29..888910c 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -64,8 +64,12 @@ public class RevertManagerTests
}
[Fact]
- public async Task IsAppliedAsync_WithInvalidJson_ReturnsFalse()
+ public async Task IsAppliedAsync_WithInvalidJson_CountsAsApplied()
{
+ // Deliberate reversal: a file that exists but cannot be parsed still means the item was
+ // applied once. Reporting it as untouched invited a fresh apply, which then wrote over
+ // the only copy of the backup. The payload is parked by the next save instead, which
+ // RevertIntegrityTests covers.
var id = Guid.NewGuid();
var path = Path.Combine(Shared.RevertDirectory, id + ".json");
var cancellationToken = TestContext.Current.CancellationToken;
@@ -77,12 +81,12 @@ public class RevertManagerTests
var isApplied = await RevertManager.IsAppliedAsync(id);
- Assert.False(isApplied);
+ Assert.True(isApplied);
}
finally
{
- if (File.Exists(path))
- File.Delete(path);
+ foreach (var file in Directory.GetFiles(Shared.RevertDirectory, id + ".json*"))
+ File.Delete(file);
}
}
@@ -630,6 +634,148 @@ public class RevertManagerChangeGuardTests
}
}
+/// <summary>
+/// Pins how revert data survives being unreadable: the bytes are kept, the item still counts
+/// as applied, and a revert says which file it could not read instead of claiming none.
+/// </summary>
+public class RevertIntegrityTests
+{
+ private static RevertManager NewManager() =>
+ new(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ TimeProvider.System
+ );
+
+ private static void Cleanup(Guid id)
+ {
+ foreach (var file in Directory.GetFiles(Shared.RevertDirectory, id + ".json*"))
+ File.Delete(file);
+ }
+
+ [Fact]
+ public async Task SaveRevertDataAsync_UnreadableFile_IsParkedAndKeptByteForByte()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+ const string damaged = "{ this is not valid json }";
+
+ try
+ {
+ await File.WriteAllTextAsync(path, damaged, cancellationToken);
+
+ var changes = new ChangeSet();
+ changes.Add("Registry", "wrote a value", true, new MockRevertStep());
+
+ await NewManager().SaveRevertDataAsync(changes, id, "IntegrityTest", cancellationToken);
+
+ var parked = Directory.GetFiles(Shared.RevertDirectory, id + ".json.unreadable-*");
+ Assert.Single(parked);
+ Assert.Equal(damaged, await File.ReadAllTextAsync(parked[0], cancellationToken));
+ Assert.True(File.Exists(path));
+ Assert.NotEqual(damaged, await File.ReadAllTextAsync(path, cancellationToken));
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
+ [Fact]
+ public async Task SaveRevertDataAsync_SchemaFromAFutureBuild_IsParked()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ try
+ {
+ var future = JsonConvert.SerializeObject(
+ new RevertData
+ {
+ SchemaVersion = 99,
+ OptimizationId = id,
+ OptimizationName = "Future",
+ AppliedAt = DateTime.UtcNow,
+ Steps = Array.Empty<RevertStepData?>(),
+ }
+ );
+ await File.WriteAllTextAsync(path, future, cancellationToken);
+
+ var changes = new ChangeSet();
+ changes.Add("Registry", "wrote a value", true, new MockRevertStep());
+
+ await NewManager().SaveRevertDataAsync(changes, id, "IntegrityTest", cancellationToken);
+
+ var parked = Directory.GetFiles(Shared.RevertDirectory, id + ".json.unreadable-*");
+ Assert.Single(parked);
+ Assert.Contains("SchemaVersion", await File.ReadAllTextAsync(parked[0], cancellationToken));
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
+ [Fact]
+ public async Task IsAppliedAsync_CountsUnreadableAndParkedData()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ try
+ {
+ Assert.False(await RevertManager.IsAppliedAsync(id));
+
+ await File.WriteAllTextAsync(path, "{ broken }", cancellationToken);
+ Assert.True(await RevertManager.IsAppliedAsync(id));
+
+ var parked = path + ".unreadable-20260101000000";
+ File.Move(path, parked);
+ Assert.True(await RevertManager.IsAppliedAsync(id));
+
+ File.Delete(parked);
+ Assert.False(await RevertManager.IsAppliedAsync(id));
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
+ [Fact]
+ public async Task RevertAsync_UnreadableData_NamesTheFileAndKeepsIt()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ try
+ {
+ await File.WriteAllTextAsync(path, "{ broken }", cancellationToken);
+
+ var result = await NewManager()
+ .RevertAsync(new MockOptimization(id), cancellationToken: cancellationToken);
+
+ Assert.False(result.Success);
+ // The path is substituted into the message, so this holds in every language.
+ Assert.Contains(path, result.Message);
+ Assert.True(File.Exists(path));
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+}
+
public class RetryableTestRevertStep : IRevertStep
{
public const string StepType = "RetryableTest";
diff --git a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
index 0cf5436..734c550 100644
--- a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
@@ -2264,5 +2264,8 @@
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>لا شيء لتغييره</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>تعذّرت قراءة بيانات التراجع الخاصة بـ {0}، لذلك لم يتم التراجع عن أي شيء. تم الاحتفاظ بالملف في {1}.</value>
+ </data>
</root>
diff --git a/optimizerDuck/Resources/Languages/Translations.de-DE.resx b/optimizerDuck/Resources/Languages/Translations.de-DE.resx
index 97c4739..6e7b27d 100644
--- a/optimizerDuck/Resources/Languages/Translations.de-DE.resx
+++ b/optimizerDuck/Resources/Languages/Translations.de-DE.resx
@@ -2274,4 +2274,7 @@ Aktualisiere jetzt, um die neuesten Funktionen, Verbesserungen und Fehlerbehebun
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Nichts zu ändern</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Die Wiederherstellungsdaten für {0} konnten nicht gelesen werden, es wurde also nichts zurückgesetzt. Die Datei bleibt unter {1} erhalten.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.es-ES.resx b/optimizerDuck/Resources/Languages/Translations.es-ES.resx
index 07319b0..23a85ee 100644
--- a/optimizerDuck/Resources/Languages/Translations.es-ES.resx
+++ b/optimizerDuck/Resources/Languages/Translations.es-ES.resx
@@ -4027,4 +4027,7 @@ Actualiza ahora para disfrutar de las nuevas funciones y mejoras.</value>
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Nada que cambiar</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>No se pudieron leer los datos de reversión de {0}, así que no se revirtió nada. El archivo se conservó en {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
index ec8270b..0590c8f 100644
--- a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
@@ -2222,4 +2222,7 @@ Mettez à jour maintenant pour profiter des dernières fonctionnalités, amélio
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Rien à modifier</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Les données de restauration de {0} n'ont pas pu être lues, rien n'a donc été restauré. Le fichier a été conservé dans {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.he-IL.resx b/optimizerDuck/Resources/Languages/Translations.he-IL.resx
index e874120..4c20ee3 100644
--- a/optimizerDuck/Resources/Languages/Translations.he-IL.resx
+++ b/optimizerDuck/Resources/Languages/Translations.he-IL.resx
@@ -2279,4 +2279,7 @@
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>אין מה לשנות</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>לא ניתן היה לקרוא את נתוני השחזור של {0}, ולכן דבר לא שוחזר. הקובץ נשמר במיקום {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.id-ID.resx b/optimizerDuck/Resources/Languages/Translations.id-ID.resx
index 28605c3..90d7e06 100644
--- a/optimizerDuck/Resources/Languages/Translations.id-ID.resx
+++ b/optimizerDuck/Resources/Languages/Translations.id-ID.resx
@@ -2279,4 +2279,7 @@ Perbarui sekarang untuk menikmati fitur terbaru, peningkatan, dan perbaikan bug.
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Tidak ada yang perlu diubah</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Data pemulihan untuk {0} tidak dapat dibaca, jadi tidak ada yang dipulihkan. File tetap disimpan di {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.it-IT.resx b/optimizerDuck/Resources/Languages/Translations.it-IT.resx
index a80f1b5..e7c3f22 100644
--- a/optimizerDuck/Resources/Languages/Translations.it-IT.resx
+++ b/optimizerDuck/Resources/Languages/Translations.it-IT.resx
@@ -2230,4 +2230,7 @@ Aggiorna ora per godere delle ultime funzionalità, miglioramenti e correzioni.<
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Nulla da modificare</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Non è stato possibile leggere i dati di ripristino di {0}, quindi non è stato ripristinato nulla. Il file è stato conservato in {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
index 9904b53..893c62a 100644
--- a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
@@ -2214,4 +2214,7 @@
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>変更はありません</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>{0} の復元データを読み取れなかったため、何も復元していません。ファイルは {1} にそのまま残しています。</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
index 4f99286..edc7514 100644
--- a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
@@ -2213,4 +2213,7 @@
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>변경할 내용 없음</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>{0}의 복원 데이터를 읽을 수 없어 아무것도 복원하지 않았습니다. 파일은 {1}에 그대로 보관했습니다.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
index ba28a38..9633e7e 100644
--- a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
+++ b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
@@ -2222,4 +2222,7 @@ Zaktualizuj teraz, aby korzystać z najnowszych funkcji, ulepszeń i poprawek b
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Nie ma nic do zmiany</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Nie można odczytać danych przywracania dla {0}, więc nic nie przywrócono. Plik zachowano w {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
index 9e4030c..8c0749a 100644
--- a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
@@ -2222,4 +2222,7 @@ Atualize agora para desfrutar das últimas funcionalidades, melhorias e correç
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Nada para alterar</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Não foi possível ler os dados de reversão de {0}, então nada foi revertido. O arquivo foi mantido em {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index 9765efc..9be952c 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -2280,4 +2280,7 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Nothing to change</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Revert data for {0} could not be read, so nothing was reverted. The file was kept at {1}.</value>
+ </data>
</root>
diff --git a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
index 352e2d4..02f0a44 100644
--- a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
@@ -2222,4 +2222,7 @@
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Нечего менять</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Не удалось прочитать данные восстановления для {0}, поэтому ничего не восстановлено. Файл сохранён в {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
index 7ac118f..3411bb0 100644
--- a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
@@ -2213,4 +2213,7 @@ En son özelliklerden, iyileştirmelerden ve hata düzeltmelerinden yararlanmak
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Değiştirilecek bir şey yok</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>{0} için geri alma verileri okunamadı, bu nedenle hiçbir şey geri alınmadı. Dosya {1} konumunda saklandı.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index 32d9538..3f526f6 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -2214,4 +2214,7 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>Không cần thay đổi</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>Không đọc được dữ liệu hoàn tác của {0}, nên chưa hoàn tác gì. Tệp vẫn được giữ tại {1}.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
index d37199c..1988c62 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
@@ -2230,4 +2230,7 @@
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>无需更改</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>无法读取 {0} 的还原数据,因此未还原任何内容。文件保留在 {1}。</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
index 9ce73fe..eb3956b 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
@@ -2217,4 +2217,7 @@
<data name="Optimization.Apply.Snackbar.NothingToDo.Title" xml:space="preserve">
<value>無需變更</value>
</data>
+ <data name="Revert.Error.UnreadableData" xml:space="preserve">
+ <value>無法讀取 {0} 的還原資料,因此未還原任何內容。檔案保留在 {1}。</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index 74d90a7..ac03196 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -389,35 +389,16 @@ public class OptimizationService(
if (optimizations.Length == 0)
return;
- // scan revert directory for which optimizations are currently applied
- // we infer applied state from file presence, not a database
- var revertFiles = await Task.Run(() =>
- {
- if (!Directory.Exists(Shared.RevertDirectory))
- return new HashSet<string>();
-
- return Directory
- .GetFiles(Shared.RevertDirectory, "*.json")
- .Select(Path.GetFileNameWithoutExtension)
- .Where(f => f != null)
- .ToHashSet(StringComparer.OrdinalIgnoreCase)!;
- })
- .ConfigureAwait(false);
-
+ // Applied state comes from the presence of revert data, not from a database, and a
+ // file that cannot be read still counts as data, so an item is never offered for a
+ // fresh apply while an old payload is still sitting next to it.
foreach (var opt in optimizations)
{
- var idStr = opt.Id.ToString();
- if (revertFiles.Contains(idStr))
- {
- var data = await RevertManager.GetRevertDataAsync(opt.Id).ConfigureAwait(false);
- opt.State.IsApplied = data != null;
- opt.State.AppliedAt = data?.AppliedAt;
- }
- else
- {
- opt.State.IsApplied = false;
- opt.State.AppliedAt = null;
- }
+ var applied = await RevertManager.IsAppliedAsync(opt.Id).ConfigureAwait(false);
+ opt.State.IsApplied = applied;
+ opt.State.AppliedAt = applied
+ ? (await RevertManager.GetRevertDataAsync(opt.Id).ConfigureAwait(false))?.AppliedAt
+ : null;
}
}
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index 57a215d..25403d5 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -73,7 +73,7 @@ public class RevertManager(
{
cancellationToken.ThrowIfCancellationRequested();
var data =
- await LoadAsync(filePath, _logger).ConfigureAwait(false)
+ await LoadForWriteAsync(filePath).ConfigureAwait(false)
?? new RevertData
{
SchemaVersion = SchemaVersion,
@@ -135,11 +135,26 @@ public class RevertManager(
{
var steps = await LoadStepsAsync(optimization.Id).ConfigureAwait(false);
if (steps.Count == 0)
+ {
+ var path = GetFilePath(optimization.Id);
+ var unreadable = File.Exists(path) ? path : FindParkedFile(path);
+ if (unreadable is not null)
+ return new RevertResult
+ {
+ Success = false,
+ Message = Loc.Instance[
+ "Revert.Error.UnreadableData",
+ optimization.Name,
+ unreadable
+ ],
+ };
+
return new RevertResult
{
Success = false,
Message = Loc.Instance["Revert.Error.NoDataFound", optimization.Name],
};
+ }
var failedSteps = new List<Change>();
var sortedSteps = steps.OrderByDescending(s => s.Index).ToList();
@@ -275,7 +290,7 @@ public class RevertManager(
{
cancellationToken.ThrowIfCancellationRequested();
var data =
- await LoadAsync(filePath, _logger).ConfigureAwait(false)
+ await LoadForWriteAsync(filePath).ConfigureAwait(false)
?? new RevertData
{
SchemaVersion = SchemaVersion,
@@ -380,10 +395,15 @@ public class RevertManager(
}
}
- public static async Task<bool> IsAppliedAsync(Guid id)
+ /// <summary>
+ /// Whether the item has revert data at all, readable or not. A file that exists but
+ /// cannot be parsed still means the item was applied once, so it is never presented as
+ /// untouched, and neither is a file that was parked after a failed read.
+ /// </summary>
+ public static Task<bool> IsAppliedAsync(Guid id)
{
- var data = await LoadAsync(GetFilePath(id)).ConfigureAwait(false);
- return data is { Steps.Length: > 0 };
+ var path = GetFilePath(id);
+ return Task.FromResult(File.Exists(path) || FindParkedFile(path) is not null);
}
public static async Task<RevertData?> GetRevertDataAsync(Guid id)
@@ -413,6 +433,54 @@ public class RevertManager(
// ObjectDisposedException; the entries are cheap and safely reused.
}
+ /// <summary>
+ /// Loads revert data for a write. The loader returns null both for "no file" and for
+ /// "cannot be read"; only the second case has something to preserve, and the write that
+ /// follows would replace the last copy of a backup, so it is parked first.
+ /// </summary>
+ private async Task<RevertData?> LoadForWriteAsync(string filePath)
+ {
+ var loaded = await LoadAsync(filePath, _logger).ConfigureAwait(false);
+ if (loaded is not null || !File.Exists(filePath))
+ return loaded;
+
+ var parkedPath = ParkUnreadable(filePath);
+ _logger.LogWarning(
+ "Revert data at {Path} could not be read; kept as {Parked}",
+ filePath,
+ parkedPath
+ );
+ return null;
+ }
+
+ /// <summary>The newest parked copy of an unreadable revert file, or null when there is none.</summary>
+ private static string? FindParkedFile(string path)
+ {
+ var directory = Path.GetDirectoryName(path);
+ if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory))
+ return null;
+
+ var matches = Directory.GetFiles(directory, Path.GetFileName(path) + ".unreadable-*");
+ if (matches.Length == 0)
+ return null;
+
+ return matches.OrderBy(static m => m, StringComparer.Ordinal).Last();
+ }
+
+ /// <summary>Moves an unreadable revert file aside, keeping its bytes, and returns the new path.</summary>
+ private string ParkUnreadable(string path)
+ {
+ var stamp = _time.GetUtcNow().ToString("yyyyMMddHHmmss");
+ var parked = $"{path}.unreadable-{stamp}";
+
+ var attempt = 1;
+ while (File.Exists(parked))
+ parked = $"{path}.unreadable-{stamp}-{attempt++}";
+
+ File.Move(path, parked);
+ return parked;
+ }
+
private static string GetFilePath(Guid id)
{
return Path.Combine(Shared.RevertDirectory, $"{id}.json");