diff --git a/Modix.Bot/Modules/ReplModule.cs b/Modix.Bot/Modules/ReplModule.cs index 62eb46f4..f2caf66e 100644 --- a/Modix.Bot/Modules/ReplModule.cs +++ b/Modix.Bot/Modules/ReplModule.cs @@ -14,7 +14,7 @@ using Modix.Services.Utilities; using Newtonsoft.Json; -namespace Modix.Modules +namespace Modix.Bot.Modules { public class Result { @@ -59,7 +59,7 @@ public async Task ReplInvokeAsync( [Summary("The code to execute.")] string code) { - if (!(Context.Channel is IGuildChannel) || !(Context.User is IGuildUser guildUser)) + if (Context.Channel is not IGuildChannel || Context.User is not IGuildUser guildUser) { await ModifyOrSendErrorEmbed("The REPL can only be executed in public guild channels."); return; @@ -85,7 +85,6 @@ public async Task ReplInvokeAsync( { var client = _httpClientFactory.CreateClient(HttpClientNames.RetryOnTransientErrorPolicy); res = await client.PostAsync(_replUrl, content); - } catch (IOException ex) { @@ -101,7 +100,7 @@ await ModifyOrSendErrorEmbed("Recieved an invalid response from the REPL service return; } - if (!res.IsSuccessStatusCode & res.StatusCode != HttpStatusCode.BadRequest) + if (!res.IsSuccessStatusCode && res.StatusCode != HttpStatusCode.BadRequest) { await ModifyOrSendErrorEmbed($"Status Code: {(int)res.StatusCode} {res.StatusCode}", message); return; @@ -172,7 +171,7 @@ private async Task BuildEmbedAsync(IGuildUser guildUser, Result pa { embed.AddField(a => a.WithName("Console Output") .WithValue(Format.Code(consoleOut.TruncateTo(MaxFormattedFieldSize), "txt"))); - await embed.UploadToServiceIfBiggerThan(consoleOut, MaxFormattedFieldSize, _pasteService); + await embed.UploadToServiceIfBiggerThan(consoleOut, MaxFormattedFieldSize, _pasteService); } if (!string.IsNullOrWhiteSpace(parsedResult.Exception)) @@ -190,6 +189,7 @@ private static string FormatOrEmptyCodeblock(string input, string language) { if (string.IsNullOrWhiteSpace(input)) return "```\n```"; + return Format.Code(input, language); } } diff --git a/Modix.Services/CodePaste/CodePasteService.cs b/Modix.Services/CodePaste/CodePasteService.cs index 455ff990..ab907ca2 100644 --- a/Modix.Services/CodePaste/CodePasteService.cs +++ b/Modix.Services/CodePaste/CodePasteService.cs @@ -1,10 +1,10 @@ -using Discord; +using System; +using System.Net.Http; +using System.Threading.Tasks; +using Discord; using Modix.Data.Utilities; using Modix.Services.Utilities; using Newtonsoft.Json.Linq; -using System; -using System.Net.Http; -using System.Threading.Tasks; namespace Modix.Services.CodePaste { @@ -63,22 +63,17 @@ public async Task UploadCodeAsync(IMessage msg, string code = null) var formatted = string.Format(Header, $"{msg.Author.Username}#{msg.Author.DiscriminatorValue}", msg.Channel.Name, DateTimeOffset.UtcNow.ToString("dddd, MMMM d yyyy @ H:mm:ss"), msg.Id, - FormatUtilities.FixIndentation(code ?? msg.Content)); + code ?? msg.Content); return await UploadCodeAsync(formatted); } - public Embed BuildEmbed(IUser user, string content, string url) - { - var cleanCode = FormatUtilities.FixIndentation(content); - - return new EmbedBuilder() + public static Embed BuildEmbed(IUser user, string content, string url) => new EmbedBuilder() .WithTitle("Your message was re-uploaded") .WithUserAsAuthor(user) - .WithDescription(cleanCode.Trim().Truncate(200, 6)) + .WithDescription(content.Trim().Truncate(200, 6)) .AddField("Auto-Paste", url, true) .WithColor(new Color(95, 186, 125)) .Build(); - } } } diff --git a/Modix.Services/Utilities/FormatUtilities.cs b/Modix.Services/Utilities/FormatUtilities.cs index 53864c3d..9f01f9e6 100644 --- a/Modix.Services/Utilities/FormatUtilities.cs +++ b/Modix.Services/Utilities/FormatUtilities.cs @@ -21,7 +21,7 @@ namespace Modix.Services.Utilities { public static class FormatUtilities { - private static readonly Regex _buildContentRegex = new Regex(@"```([^\s]+|)"); + private static readonly Regex _buildContentRegex = new(@"```([^\s]*)", RegexOptions.Compiled); /// /// Prepares a piece of input code for use in HTTP operations @@ -34,54 +34,9 @@ public static StringContent BuildContent(string code) return new StringContent(cleanCode, Encoding.UTF8, "text/plain"); } - /// - /// Attempts to get the language of the code piece - /// - /// The code - /// The code language if a match is found, null of none are found - public static string GetCodeLanguage(string message) - { - var match = _buildContentRegex.Match(message); - if (match.Success) - { - var codeLanguage = match.Groups[1].Value; - return string.IsNullOrEmpty(codeLanguage) ? null : codeLanguage; - } - else - { - return null; - } - } - - public static string StripFormatting(string code) - { - var cleanCode = _buildContentRegex.Replace(code.Trim(), string.Empty); //strip out the ` characters and code block markers - cleanCode = cleanCode.Replace("\t", " "); //spaces > tabs - cleanCode = FixIndentation(cleanCode); - return cleanCode; - } - - /// - /// Attempts to fix the indentation of a piece of code by aligning the left sidie. - /// - /// The code to align - /// The newly aligned code - public static string FixIndentation(string code) - { - var lines = code.Split('\n'); - var indentLine = lines.SkipWhile(d => d.FirstOrDefault() != ' ').FirstOrDefault(); - - if (indentLine != null) - { - var indent = indentLine.LastIndexOf(' ') + 1; - - var pattern = $@"^[^\S\n]{{{indent}}}"; - - return Regex.Replace(code, pattern, "", RegexOptions.Multiline); - } - - return code; - } + public static string StripFormatting(string code) => + //strip out the ` characters and code block markers + _buildContentRegex.Replace(code.Trim(), string.Empty); public static async Task UploadToServiceIfBiggerThan(this EmbedBuilder embed, string content, uint size, CodePasteService service) { @@ -106,7 +61,7 @@ public static string FormatInfractionCounts(IDictionary cou return "This user is clean - no active infractions!"; } - var formatted = + var formatted = counts.Select(d => { var formattedKey = d.Key.Humanize().ToLower(); @@ -116,7 +71,7 @@ public static string FormatInfractionCounts(IDictionary cou return $"This user has {formatted}"; } - + /// /// Collapses plural forms into a "singular(s)"-type format. /// @@ -174,7 +129,7 @@ public static IReadOnlyCollection CollapsePlurals(IReadOnlyCollection lines.Length - processedLines.Count - braceOnlyLinesEliminated; + { + return lines.Length - processedLines.Count - braceOnlyLinesEliminated; + } string GetRemainingLineCountComment(int remainingCount) { @@ -337,6 +294,5 @@ void AddRemainingLineComment() processedLines.Add(GetRemainingLineCountComment(GetRemainingLineCount())); } } -#nullable restore } }