Avoid saving the same content in SerializableFile calls

Normally this should not matter and it does not, but https://github.com/JustArchiNET/ASF-ui/pull/1409#issuecomment-855873098 highlighted a potential enhancement idea in which the caller requests ASF to save the same content as currently exists. Since write operation could emit unnecessary event which forces ASF to start/stop/restart bot/process, I believe that it's justified to add a read operation in front of it to ensure that the file actually needs to be written over.
This commit is contained in:
Archi 2021-06-07 14:34:15 +02:00
parent 8e4e0fbbee
commit 84d18874a2
No known key found for this signature in database
GPG key ID: 6B138B4C64555AEA

View file

@ -82,15 +82,23 @@ namespace ArchiSteamFarm.Helpers {
throw new InvalidOperationException(nameof(json));
}
// We always want to write entire content to temporary file first, in order to never load corrupted data, also when target file doesn't exist
string newFilePath = FilePath + ".new";
// We always want to write entire content to temporary file first, in order to never load corrupted data, also when target file doesn't exist
await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
if (System.IO.File.Exists(FilePath)) {
System.IO.File.Replace(newFilePath, FilePath!, null);
string currentJson = await File.ReadAllTextAsync(FilePath!).ConfigureAwait(false);
if (json == currentJson) {
return;
}
await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
System.IO.File.Replace(newFilePath, FilePath, null);
} else {
System.IO.File.Move(newFilePath, FilePath!);
await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
System.IO.File.Move(newFilePath, FilePath);
}
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
@ -132,13 +140,23 @@ namespace ArchiSteamFarm.Helpers {
try {
// We always want to write entire content to temporary file first, in order to never load corrupted data, also when target file doesn't exist
await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
if (System.IO.File.Exists(filePath)) {
string currentJson = await File.ReadAllTextAsync(filePath).ConfigureAwait(false);
if (json == currentJson) {
return true;
}
await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
System.IO.File.Replace(newFilePath, filePath, null);
} else {
await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
System.IO.File.Move(newFilePath, filePath);
}
return true;
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
@ -146,8 +164,6 @@ namespace ArchiSteamFarm.Helpers {
} finally {
GlobalFileSemaphore.Release();
}
return true;
}
}
}