Updated editorconfig to (mostly?) require braces around if/else statements, and applied the new formatting rules

This commit is contained in:
Kwoth
2022-02-02 01:44:45 +01:00
parent b22cd5a81e
commit ffa2c3f119
202 changed files with 2108 additions and 920 deletions

View File

@@ -14,9 +14,7 @@ public class CurrencyService : ICurrencyService, INService
public Task<IWallet> GetWalletAsync(ulong userId, CurrencyType type = CurrencyType.Default)
{
if (type == CurrencyType.Default)
{
return Task.FromResult<IWallet>(new DefaultWallet(userId, _db.GetDbContext()));
}
throw new ArgumentOutOfRangeException(nameof(type));
}
@@ -111,10 +109,9 @@ public class CurrencyService : ICurrencyService, INService
{
await using var fromWallet = await GetWalletAsync(fromId);
await using var toWallet = await GetWalletAsync(toId);
var extra = new TxData("gift", fromName, note, fromId);
return await fromWallet.Transfer(amount, toWallet, extra);
}
}

View File

@@ -2,5 +2,5 @@
public enum CurrencyType
{
Default,
Default
}

View File

@@ -66,9 +66,8 @@ public class DefaultWallet : IWallet
{
CurrencyAmount = x.CurrencyAmount + amount
});
if (changed == 0)
{
await _ctx.DiscordUser
.ToLinqToDBTable()
.Value(x => x.UserId, UserId)
@@ -76,7 +75,6 @@ public class DefaultWallet : IWallet
.Value(x => x.Discriminator, "????")
.Value(x => x.CurrencyAmount, amount)
.InsertAsync();
}
await tran.CommitAsync();
}
@@ -88,7 +86,7 @@ public class DefaultWallet : IWallet
Note = txData.Note,
Type = txData.Type,
Extra = txData.Extra,
OtherId = txData.OtherId,
OtherId = txData.OtherId
};
await _ctx.CreateLinqToDbContext()
@@ -100,7 +98,7 @@ public class DefaultWallet : IWallet
_ctx.SaveChanges();
_ctx.Dispose();
}
public async ValueTask DisposeAsync()
{
await _ctx.SaveChangesAsync();

View File

@@ -3,11 +3,11 @@ namespace NadekoBot.Services.Currency;
public interface IWallet : IDisposable, IAsyncDisposable
{
public ulong UserId { get; }
public Task<long> GetBalance();
public Task<bool> Take(long amount, TxData txData);
public Task Add(long amount, TxData txData);
public async Task<bool> Transfer(
long amount,
IWallet to,

View File

@@ -1,3 +1,7 @@
namespace NadekoBot.Services.Currency;
public record class TxData(string Type, string Extra, string? Note = "", ulong? OtherId = null);
public record class TxData(
string Type,
string Extra,
string? Note = "",
ulong? OtherId = null);

View File

@@ -26,8 +26,10 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService
public async Task<bool> RunEarlyBehavioursAsync(SocketGuild guild, IUserMessage usrMsg)
{
foreach (var beh in earlyBehaviors)
{
if (await beh.RunBehavior(guild, usrMsg))
return true;
}
return false;
}
@@ -52,6 +54,7 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService
public async Task<bool> RunLateBlockersAsync(ICommandContext ctx, CommandInfo cmd)
{
foreach (var exec in lateBlockers)
{
if (await exec.TryBlockLate(ctx, cmd.Module.GetTopLevelModule().Name, cmd))
{
Log.Information("Late blocking User [{User}] Command: [{Command}] in [{Module}]",
@@ -60,6 +63,7 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService
exec.GetType().Name);
return true;
}
}
return false;
}
@@ -67,6 +71,7 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService
public async Task RunLateExecutorsAsync(SocketGuild guild, IUserMessage usrMsg)
{
foreach (var exec in lateExecutors)
{
try
{
await exec.LateExecute(guild, usrMsg);
@@ -75,5 +80,6 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService
{
Log.Error(ex, "Error in {TypeName} late executor: {ErrorMessage}", exec.GetType().Name, ex.Message);
}
}
}
}

View File

@@ -42,7 +42,8 @@ public sealed class BotCredsProvider : IBotCredsProvider
public BotCredsProvider(int? totalShards = null)
{
_totalShards = totalShards;
if (!File.Exists(CredsExamplePath)) File.WriteAllText(CredsExamplePath, Yaml.Serializer.Serialize(_creds));
if (!File.Exists(CredsExamplePath))
File.WriteAllText(CredsExamplePath, Yaml.Serializer.Serialize(_creds));
MigrateCredentials();
@@ -79,9 +80,17 @@ public sealed class BotCredsProvider : IBotCredsProvider
|| string.IsNullOrWhiteSpace(_creds.RestartCommand?.Args))
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
_creds.RestartCommand = new() { Args = "dotnet", Cmd = "NadekoBot.dll -- {0}" };
_creds.RestartCommand = new()
{
Args = "dotnet",
Cmd = "NadekoBot.dll -- {0}"
};
else
_creds.RestartCommand = new() { Args = "NadekoBot.exe", Cmd = "{0}" };
_creds.RestartCommand = new()
{
Args = "NadekoBot.exe",
Cmd = "{0}"
};
}
if (string.IsNullOrWhiteSpace(_creds.RedisOptions))

View File

@@ -45,9 +45,12 @@ public class FontProvider : INService
// any fonts present in data/fonts should be added as fallback fonts
// this will allow support for special characters when drawing text
foreach (var font in Directory.GetFiles(@"data/fonts"))
{
if (font.EndsWith(".ttf"))
FallBackFonts.Add(_fonts.Install(font));
else if (font.EndsWith(".ttc")) FallBackFonts.AddRange(_fonts.InstallCollection(font));
else if (font.EndsWith(".ttc"))
FallBackFonts.AddRange(_fonts.InstallCollection(font));
}
RipFont = NotoSans.CreateFont(20, FontStyle.Bold);
DottyFont = FallBackFonts.First(x => x.Name == "dotty");

View File

@@ -164,7 +164,11 @@ public class GoogleApiService : IGoogleApiService, INService
_creds = creds;
_httpFactory = factory;
var bcs = new BaseClientService.Initializer { ApplicationName = "Nadeko Bot", ApiKey = _creds.GoogleApiKey };
var bcs = new BaseClientService.Initializer
{
ApplicationName = "Nadeko Bot",
ApiKey = _creds.GoogleApiKey
};
_yt = new(bcs);
_sh = new(bcs);
@@ -181,7 +185,8 @@ public class GoogleApiService : IGoogleApiService, INService
throw new ArgumentOutOfRangeException(nameof(count));
var match = _plRegex.Match(keywords);
if (match.Length > 1) return new[] { match.Groups["id"].Value };
if (match.Length > 1)
return new[] { match.Groups["id"].Value };
var query = _yt.Search.List("snippet");
query.MaxResults = count;
query.Type = "playlist";
@@ -256,7 +261,11 @@ public class GoogleApiService : IGoogleApiService, INService
try
{
var response = await _sh.Url.Insert(new() { LongUrl = url }).ExecuteAsync();
var response = await _sh.Url.Insert(new()
{
LongUrl = url
})
.ExecuteAsync();
return response.Id;
}
catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.Forbidden)
@@ -322,7 +331,8 @@ public class GoogleApiService : IGoogleApiService, INService
q.Id = string.Join(",", videoIdsList.Take(toGet));
videoIdsList = videoIdsList.Skip(toGet).ToList();
var items = (await q.ExecuteAsync()).Items;
foreach (var i in items) toReturn.Add(i.Id, XmlConvert.ToTimeSpan(i.ContentDetails.Duration));
foreach (var i in items)
toReturn.Add(i.Id, XmlConvert.ToTimeSpan(i.ContentDetails.Duration));
} while (remaining > 0);
return toReturn;

View File

@@ -103,7 +103,12 @@ public class Localization : ILocalization, INService
_commandData.TryGetValue(key, out var toReturn);
if (toReturn is null)
return new() { Cmd = key, Desc = key, Usage = new[] { key } };
return new()
{
Cmd = key,
Desc = key,
Usage = new[] { key }
};
return toReturn;
}

View File

@@ -157,7 +157,8 @@ public class RedisCache : IDataCache
{
var db = Redis.GetDatabase();
data = db.StringGet($"{_redisKey}_economy");
if (data is not null) return true;
if (data is not null)
return true;
return false;
}

View File

@@ -127,9 +127,14 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor
Rategirl =
new()
{
Dot = oldData.Rategirl.Dot.ToNewCdn(), Matrix = oldData.Rategirl.Matrix.ToNewCdn()
Dot = oldData.Rategirl.Dot.ToNewCdn(),
Matrix = oldData.Rategirl.Matrix.ToNewCdn()
},
Rip = new() { Bg = oldData.Rip.Bg.ToNewCdn(), Overlay = oldData.Rip.Overlay.ToNewCdn() },
Rip = new()
{
Bg = oldData.Rip.Bg.ToNewCdn(),
Overlay = oldData.Rip.Overlay.ToNewCdn()
},
Slots = new()
{
Bg = new("https://cdn.nadeko.bot/slots/slots_bg.png"),
@@ -140,7 +145,10 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor
"https://cdn.nadeko.bot/slots/4.png", "https://cdn.nadeko.bot/slots/5.png"
}.Map(x => new Uri(x))
},
Xp = new() { Bg = oldData.Xp.Bg.ToNewCdn() },
Xp = new()
{
Bg = oldData.Xp.Bg.ToNewCdn()
},
Version = 2
};
@@ -162,6 +170,7 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor
{
ImageUrls = Yaml.Deserializer.Deserialize<ImageUrls>(await File.ReadAllTextAsync(_imagesPath));
foreach (var key in GetAllKeys())
{
switch (key)
{
case ImageKeys.CoinHeads:
@@ -200,6 +209,7 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor
default:
throw new ArgumentOutOfRangeException();
}
}
}
private async Task Load(ImageKeys key, Uri uri)

View File

@@ -28,11 +28,17 @@ public class RemoteGrpcCoordinator : ICoordinator, IReadyExecutor
}
public void Die(bool graceful)
=> _coordClient.Die(new() { Graceful = graceful });
=> _coordClient.Die(new()
{
Graceful = graceful
});
public bool RestartShard(int shardId)
{
_coordClient.RestartShard(new() { ShardId = shardId });
_coordClient.RestartShard(new()
{
ShardId = shardId
});
return true;
}

View File

@@ -58,7 +58,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
_client.ChannelCreated += c =>
{
_= Task.Run(() =>
_ = Task.Run(() =>
{
if (c is ITextChannel)
Interlocked.Increment(ref textChannels);
@@ -71,7 +71,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
_client.ChannelDestroyed += c =>
{
_= Task.Run(() =>
_ = Task.Run(() =>
{
if (c is ITextChannel)
Interlocked.Decrement(ref textChannels);
@@ -84,7 +84,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
_client.GuildAvailable += g =>
{
_= Task.Run(() =>
_ = Task.Run(() =>
{
var tc = g.Channels.Count(cx => cx is ITextChannel);
var vc = g.Channels.Count - tc;
@@ -96,7 +96,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
_client.JoinedGuild += g =>
{
_= Task.Run(() =>
_ = Task.Run(() =>
{
var tc = g.Channels.Count(cx => cx is ITextChannel);
var vc = g.Channels.Count - tc;
@@ -108,7 +108,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
_client.GuildUnavailable += g =>
{
_= Task.Run(() =>
_ = Task.Run(() =>
{
var tc = g.Channels.Count(cx => cx is ITextChannel);
var vc = g.Channels.Count - tc;
@@ -121,7 +121,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
_client.LeftGuild += g =>
{
_= Task.Run(() =>
_ = Task.Run(() =>
{
var tc = g.Channels.Count(cx => cx is ITextChannel);
var vc = g.Channels.Count - tc;
@@ -138,7 +138,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
var guilds = _client.Guilds;
textChannels = guilds.Sum(g => g.Channels.Count(cx => cx is ITextChannel));
voiceChannels = guilds.Sum(g => g.Channels.Count(cx => cx is IVoiceChannel));
var timer = new PeriodicTimer(TimeSpan.FromHours(1));
do
{
@@ -167,7 +167,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
Log.Error(ex, "Error in botlist post");
}
} while (await timer.WaitForNextTickAsync());
}
}
public TimeSpan GetUptime()
=> DateTime.UtcNow - _started;

View File

@@ -30,10 +30,10 @@ public sealed class BotConfigService : ConfigServiceBase<BotConfig>
private void Migrate()
{
if (data.Version < 2) ModifyConfig(c => c.Version = 2);
if (data.Version < 2)
ModifyConfig(c => c.Version = 2);
if (data.Version < 3)
{
ModifyConfig(c =>
{
c.Version = 3;
@@ -46,6 +46,5 @@ public sealed class BotConfigService : ConfigServiceBase<BotConfig>
.Distinct()
.ToHashSet();
});
}
}
}

View File

@@ -78,7 +78,11 @@ public class BotStrings : IBotStrings
Log.Warning("'{CommandName}' doesn't exist in 'en-US' command strings. Please report this",
commandName);
return new() { Args = new[] { "" }, Desc = "?" };
return new()
{
Args = new[] { "" },
Desc = "?"
};
}
// Log.Warning(@"'{CommandName}' command strings don't exist in '{LanguageName}' culture.

View File

@@ -24,6 +24,7 @@ public class LocalFileStringsSource : IStringsSource
{
var outputDict = new Dictionary<string, Dictionary<string, string>>();
foreach (var file in Directory.GetFiles(_responsesPath))
{
try
{
var langDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(file));
@@ -34,6 +35,7 @@ public class LocalFileStringsSource : IStringsSource
{
Log.Error(ex, "Error loading {FileName} response strings: {ErrorMessage}", file, ex.Message);
}
}
return outputDict;
}
@@ -44,6 +46,7 @@ public class LocalFileStringsSource : IStringsSource
var outputDict = new Dictionary<string, Dictionary<string, CommandStrings>>();
foreach (var file in Directory.GetFiles(_commandsPath))
{
try
{
var text = File.ReadAllText(file);
@@ -55,6 +58,7 @@ public class LocalFileStringsSource : IStringsSource
{
Log.Error(ex, "Error loading {FileName} command strings: {ErrorMessage}", file, ex.Message);
}
}
return outputDict;
}

View File

@@ -47,7 +47,11 @@ public class RedisBotStringsProvider : IBotStringsProvider
return null;
var args = Array.ConvertAll(argsStr.Split('&'), HttpUtility.UrlDecode);
return new() { Args = args, Desc = descStr };
return new()
{
Args = args,
Desc = descStr
};
}
public void Reload()