1
0
Fork 1
mirror of https://github.com/TeamOctolings/Octobot.git synced 2025-01-31 00:19:00 +03:00

Fix JSON corruption when saving (#100)

This PR fixes an issue that caused guild data JSON files to be corrupted
upon saving. As it turns out `File.OpenWrite(string)` does not clear the
file before writing to it. That means, if a file contains `{"MyKey":
"MyValue"}` and I write `{}` to it using `File.OpenWrite(string)`, the
contents of the file will be `{}MyKey": "MyValue"}`. This is a malformed
JSON and will cause an error upon next bot startup.

In addition, this PR blacklists the `File.OpenWrite` method using
`CodeAnalysis/BannedSymbols.txt` to prevent its accidental use in the
future.

Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com>
This commit is contained in:
Octol1ttle 2023-08-22 12:46:57 +05:00 committed by GitHub
parent 5831f5205c
commit 31968837e5
Signed by: GitHub
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 4 additions and 3 deletions

View file

@ -17,3 +17,4 @@ M:Humanizer.InflectorExtensions.Kebaberize(System.String);Humanizer's .Kebaberiz
P:System.DateTime.Now;Use System.DateTime.UtcNow instead.
P:System.DateTimeOffset.Now;Use System.DateTimeOffset.UtcNow instead.
P:System.DateTimeOffset.DateTime;Use System.DateTimeOffset.UtcDateTime instead.
M:System.IO.File.OpenWrite(System.String);File.OpenWrite(string) does not clear the file before writing to it. Use File.Create(string) instead.

View file

@ -48,15 +48,15 @@ public sealed class GuildDataService : IHostedService
var tasks = new List<Task>();
foreach (var data in _datas.Values)
{
await using var settingsStream = File.OpenWrite(data.SettingsPath);
await using var settingsStream = File.Create(data.SettingsPath);
tasks.Add(JsonSerializer.SerializeAsync(settingsStream, data.Settings, cancellationToken: ct));
await using var eventsStream = File.OpenWrite(data.ScheduledEventsPath);
await using var eventsStream = File.Create(data.ScheduledEventsPath);
tasks.Add(JsonSerializer.SerializeAsync(eventsStream, data.ScheduledEvents, cancellationToken: ct));
foreach (var memberData in data.MemberData.Values)
{
await using var memberDataStream = File.OpenWrite($"{data.MemberDataPath}/{memberData.Id}.json");
await using var memberDataStream = File.Create($"{data.MemberDataPath}/{memberData.Id}.json");
tasks.Add(JsonSerializer.SerializeAsync(memberDataStream, memberData, cancellationToken: ct));
}
}