Skip to content

Commit

Permalink
refactoring and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
PrincessRTFM committed Dec 9, 2024
1 parent 6cd2ff1 commit c40f5f8
Show file tree
Hide file tree
Showing 15 changed files with 46 additions and 57 deletions.
8 changes: 3 additions & 5 deletions TinyCmds/Attributes/ArgumentsAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
namespace PrincessRTFM.TinyCmds.Attributes;

[AttributeUsage(AttributeTargets.Class)]
internal class ArgumentsAttribute: Attribute {
internal class ArgumentsAttribute(params string[] args): Attribute {
public string ArgumentDescription => string.Join(" ", this.Arguments.Select(a => a.EndsWith('?') ? $"[{a.TrimEnd('?')}]" : $"<{a}>"));
public string[] Arguments { get; }
public int RequiredArguments => this.Arguments.Where(a => !a.EndsWith('?')).Count();
public string[] Arguments { get; } = args;
public int RequiredArguments => this.Arguments.Count(a => !a.EndsWith('?'));
public int MaxArguments => this.Arguments.Length;

public ArgumentsAttribute(params string[] args) => this.Arguments = args;
}
11 changes: 3 additions & 8 deletions TinyCmds/Attributes/CommandAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,7 @@
namespace PrincessRTFM.TinyCmds.Attributes;

[AttributeUsage(AttributeTargets.Class)]
internal class CommandAttribute: Attribute {
public string Command { get; }
public string[] Aliases { get; }

public CommandAttribute(string command, params string[] aliases) {
this.Command = command;
this.Aliases = aliases;
}
internal class CommandAttribute(string command, params string[] aliases): Attribute {
public string Command { get; } = command;
public string[] Aliases { get; } = aliases;
}
6 changes: 2 additions & 4 deletions TinyCmds/Attributes/HelpTextAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
namespace PrincessRTFM.TinyCmds.Attributes;

[AttributeUsage(AttributeTargets.Class)]
internal class HelpTextAttribute: Attribute {
public string HelpMessage { get; }

public HelpTextAttribute(params string[] helpMessage) => this.HelpMessage = string.Join("\n", helpMessage);
internal class HelpTextAttribute(params string[] helpMessage): Attribute {
public string HelpMessage { get; } = string.Join("\n", helpMessage);
}
6 changes: 2 additions & 4 deletions TinyCmds/Attributes/SummaryAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
namespace PrincessRTFM.TinyCmds.Attributes;

[AttributeUsage(AttributeTargets.Class)]
internal class SummaryAttribute: Attribute {
public string Summary { get; }

public SummaryAttribute(string helpMessage) => this.Summary = helpMessage;
internal class SummaryAttribute(string helpMessage): Attribute {
public string Summary { get; } = helpMessage;
}
8 changes: 4 additions & 4 deletions TinyCmds/Chat/ChatUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ internal static List<Payload> GenerateMessagePayloads(params object[] payloads)

#region Chatlog functions
public static void ShowMessage(params object[] payloads) {
if (payloads.Length < 1 || !payloads.Where(e => e is not null).Any())
if (payloads.Length < 1 || !payloads.Any(e => e is not null))
return;
Plugin.Chat.Print(new SeString(GenerateMessagePayloads(payloads)));
}
public static void ShowPrefixedMessage(params object[] payloads) {
if (payloads.Length < 1 || !payloads.Where(e => e is not null).Any())
if (payloads.Length < 1 || !payloads.Any(e => e is not null))
return;
List<object> plList = [
ChatColour.PREFIX,
Expand All @@ -49,12 +49,12 @@ public static void ShowPrefixedMessage(params object[] payloads) {
ShowMessage(plList.ToArray());
}
public static void ShowError(params object[] payloads) {
if (payloads.Length < 1 || !payloads.Where(e => e is not null).Any())
if (payloads.Length < 1 || !payloads.Any(e => e is not null))
return;
Plugin.Chat.PrintError(new SeString(GenerateMessagePayloads(payloads)));
}
public static void ShowPrefixedError(params object[] payloads) {
if (payloads.Length < 1 || !payloads.Where(e => e is not null).Any())
if (payloads.Length < 1 || !payloads.Any(e => e is not null))
return;
List<object> plList = [
ChatColour.PREFIX,
Expand Down
4 changes: 2 additions & 2 deletions TinyCmds/CommandAssertionFailureException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ namespace PrincessRTFM.TinyCmds;
[Serializable]
public class CommandAssertionFailureException: Exception {
public CommandAssertionFailureException() { }
public CommandAssertionFailureException(string message) : base(message) { }
public CommandAssertionFailureException(string message, Exception inner) : base(message, inner) { }
public CommandAssertionFailureException(string? message) : base(message) { }
public CommandAssertionFailureException(string? message, Exception? inner) : base(message, inner) { }
}
8 changes: 2 additions & 6 deletions TinyCmds/Commands/LocateBestFATECommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,8 @@ protected override unsafe void Execute(string? command, string rawArguments, Fla
uint originalTime = minTime;
uint originalProgress = maxProgress;
List<Fate> fates = new(Plugin.Fates.Length);
foreach (Fate? fate in Plugin.Fates) {
if (fate is not null)
fates.Add(fate);
}
byte fateLevel = fates.Where(f => f.Level <= maxLevel).Any()
fates.AddRange(Plugin.Fates.Where(f => f is not null));
byte fateLevel = fates.Any(f => f.Level <= maxLevel)
? fates.OrderByDescending(f => f.Level).First().Level
: fates.OrderBy(f => f.Level).First().Level;
Fate[] filtered = fates.Where(f => f.Level == fateLevel).ToArray();
Expand Down Expand Up @@ -205,7 +202,6 @@ protected override unsafe void Execute(string? command, string rawArguments, Fla
if (flags['f']) {
uint zone = Plugin.Client.TerritoryType;
Map map = Plugin.Data.GetExcelSheet<TerritoryType>()?.GetRowOrDefault(zone)?.Map.Value ?? throw new NullReferenceException("Cannot find map ID");
ExcelSheet<TerritoryTypeTransient>? transientSheet = Plugin.Data.Excel.GetSheet<TerritoryTypeTransient>();
uint mapId = map.RowId;
AgentMap* agentMap = AgentMap.Instance();
Vector3 pos = accepted[0].Position;
Expand Down
1 change: 0 additions & 1 deletion TinyCmds/Commands/LocateGameObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ protected override unsafe void Execute(string? command, string rawArguments, Fla

uint zone = Plugin.Client.TerritoryType;
Map map = Plugin.Data.GetExcelSheet<TerritoryType>()?.GetRowOrDefault(zone)?.Map.Value ?? throw new NullReferenceException("Cannot find map ID");
ExcelSheet<TerritoryTypeTransient>? transientSheet = Plugin.Data.Excel.GetSheet<TerritoryTypeTransient>();
uint mapId = map.RowId;
int count = found.Count();

Expand Down
4 changes: 2 additions & 2 deletions TinyCmds/Internal/GameFunctionBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public T? Delegate {
return null;
}
}
internal GameFunctionBase(string sig, int offset = 0) {
protected GameFunctionBase(string sig, int offset = 0) {
if (Plugin.Scanner.TryScanText(sig, out this.addr)) {
this.addr += offset;
ulong totalOffset = (ulong)this.Address.ToInt64() - (ulong)Plugin.Scanner.Module.BaseAddress.ToInt64();
Expand All @@ -34,7 +34,7 @@ internal GameFunctionBase(string sig, int offset = 0) {
}
}
[SuppressMessage("Reliability", "CA2020:Prevent from behavioral change", Justification = "If that explodes, we SHOULD be throwing")]
internal GameFunctionBase(IntPtr address, int offset = 0) {
protected GameFunctionBase(IntPtr address, int offset = 0) {
this.addr = address + offset;
ulong totalOffset = (ulong)this.Address.ToInt64() - (ulong)Plugin.Scanner.Module.BaseAddress.ToInt64();
Logger.Info($"{this.GetType().Name} loaded; address = 0x{this.Address.ToInt64():X16}, base memory offset = 0x{totalOffset:X16}");
Expand Down
18 changes: 12 additions & 6 deletions TinyCmds/Internal/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,23 @@ private static string msgPrefix {
[Conditional("DEBUG")]
internal static void Debug(string tmpl, params object[] args) => Plugin.Log.Debug($"{msgPrefix} {string.Format(tmpl, args)}");
[Conditional("DEBUG")]
internal static void Verbose(string tmpl, params object[] args) => Plugin.Log.Verbose($"{msgPrefix} {string.Format(tmpl, args)}");
internal static void Info(string tmpl, params object[] args) => Plugin.Log.Information($"{msgPrefix} {string.Format(tmpl, args)}");
internal static void Warning(string tmpl, params object[] args) => Plugin.Log.Warning($"{msgPrefix} {string.Format(tmpl, args)}");
internal static void Error(string tmpl, params object[] args) => Plugin.Log.Error($"{msgPrefix} {string.Format(tmpl, args)}");
internal static void Fatal(string tmpl, params object[] args) => Plugin.Log.Fatal($"{msgPrefix} {string.Format(tmpl, args)}");
[Conditional("DEBUG")]
internal static void Debug(Exception ex, string tmpl, params object[] args) => Plugin.Log.Debug(ex, $"{msgPrefix} {string.Format(tmpl, args)}");

[Conditional("DEBUG")]
internal static void Verbose(string tmpl, params object[] args) => Plugin.Log.Verbose($"{msgPrefix} {string.Format(tmpl, args)}");
[Conditional("DEBUG")]
internal static void Verbose(Exception ex, string tmpl, params object[] args) => Plugin.Log.Verbose(ex, $"{msgPrefix} {string.Format(tmpl, args)}");

internal static void Info(string tmpl, params object[] args) => Plugin.Log.Information($"{msgPrefix} {string.Format(tmpl, args)}");
internal static void Info(Exception ex, string tmpl, params object[] args) => Plugin.Log.Information(ex, $"{msgPrefix} {string.Format(tmpl, args)}");

internal static void Warning(string tmpl, params object[] args) => Plugin.Log.Warning($"{msgPrefix} {string.Format(tmpl, args)}");
internal static void Warning(Exception ex, string tmpl, params object[] args) => Plugin.Log.Warning(ex, $"{msgPrefix} {string.Format(tmpl, args)}");

internal static void Error(string tmpl, params object[] args) => Plugin.Log.Error($"{msgPrefix} {string.Format(tmpl, args)}");
internal static void Error(Exception ex, string tmpl, params object[] args) => Plugin.Log.Error(ex, $"{msgPrefix} {string.Format(tmpl, args)}");

internal static void Fatal(string tmpl, params object[] args) => Plugin.Log.Fatal($"{msgPrefix} {string.Format(tmpl, args)}");
internal static void Fatal(Exception ex, string tmpl, params object[] args) => Plugin.Log.Fatal(ex, $"{msgPrefix} {string.Format(tmpl, args)}");

}
11 changes: 6 additions & 5 deletions TinyCmds/PluginCommand.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

Expand All @@ -22,10 +23,10 @@ public abstract class PluginCommand: IDisposable {
ShowInHelp = false,
};
public string CommandComparable => this.Command.TrimStart('/').ToLower();
public string[] AliasesComparable => this.Aliases.Select(s => s.TrimStart('/').ToLower()).ToArray();
public string[] HelpLines => this.Help.Split('\r', '\n').Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
public string[] InvocationNames => (new string[] { this.Command }).Concat(this.Aliases).ToArray();
public string[] InvocationNamesComparable => (new string[] { this.CommandComparable }).Concat(this.AliasesComparable).ToArray();
public IEnumerable<string> AliasesComparable => this.Aliases.Select(s => s.TrimStart('/').ToLower());
public IEnumerable<string> HelpLines => this.Help.Split('\r', '\n').Where(s => !string.IsNullOrWhiteSpace(s));
public IEnumerable<string> InvocationNames => (new string[] { this.Command }).Concat(this.Aliases);
public IEnumerable<string> InvocationNamesComparable => (new string[] { this.CommandComparable }).Concat(this.AliasesComparable);
public string Command { get; }
public string Summary { get; }
public string Help { get; }
Expand All @@ -39,7 +40,7 @@ public abstract class PluginCommand: IDisposable {
public string InternalName { get; init; }

#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public PluginCommand() {
protected PluginCommand() {
Type t = this.GetType();
CommandAttribute attrCommand = t.GetCustomAttribute<CommandAttribute>() ?? throw new InvalidOperationException("Cannot construct PluginCommand from type without CommandAttribute");
ArgumentsAttribute? args = t.GetCustomAttribute<ArgumentsAttribute>();
Expand Down
5 changes: 2 additions & 3 deletions TinyCmds/PluginCommandManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ public PluginCommandManager(Plugin core) {
object instance = RuntimeHelpers.GetUninitializedObject(t);
PropertyInfo prop = b
.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Where(prop => prop.PropertyType == p)
.First();
.First(prop => prop.PropertyType == p);
Plugin.Log.Information($"Injecting {p.Name} object to {t.Name}.{prop.Name}");
prop.SetValue(instance, core);
Plugin.Log.Information($"Invoking {t.Name}.<ctor>()");
Expand All @@ -53,7 +52,7 @@ public PluginCommandManager(Plugin core) {
.Where(o => o is not null)
.Cast<PluginCommand>()
.ToList();
this.HelpHandler = this.commandList.Where(c => c.GetType().GetCustomAttribute<PluginCommandHelpHandlerAttribute>() is not null).FirstOrDefault();
this.HelpHandler = this.commandList.Find(c => c.GetType().GetCustomAttribute<PluginCommandHelpHandlerAttribute>() is not null);
}

internal void AddCommandHandlers() {
Expand Down
3 changes: 1 addition & 2 deletions TinyCmds/TimeSpec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ public static bool TryParse(string spec, out uint hours, out uint minutes, out u
try {
Match match = Matcher.Match(spec.ToLower());
if (match.Success) {
foreach (Capture capture in match.Groups[1].Captures.Cast<Capture>()) { // apparently it's `object`s for some reason???
string piece = capture.Value;
foreach (string piece in match.Groups[1].Captures.Cast<Capture>().Select(c => c.Value)) { // apparently it's `object`s for some reason???
switch (piece[^1]) {
case 'h':
hours += uint.Parse(piece[..^1]);
Expand Down
2 changes: 1 addition & 1 deletion TinyCmds/Utils/ArgumentParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace PrincessRTFM.TinyCmds.Utils;

public class ArgumentParser {
public static class ArgumentParser {

// From https://metacpan.org/dist/Text-ParseWords/source/lib/Text/ParseWords.pm - I really hope this works :/
[System.Diagnostics.CodeAnalysis.SuppressMessage("GeneratedRegex", "SYSLIB1045:Convert to 'GeneratedRegexAttribute'.", Justification = "Way too big and long to be one-lined for the attribute")]
Expand Down
8 changes: 4 additions & 4 deletions TinyCmds/Utils/FlagMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,19 @@ public void SetAll(IEnumerable<string> keys) {
this[key] = true;
}
}
public void Set(params string[] keys) => this.SetAll(keys);

public void SetAll(IEnumerable<char> keys) => this.SetAll(keys.Select(c => c.ToString()));

public void Set(params string[] keys) => this.SetAll(keys);
public void Set(params char[] keys) => this.SetAll(keys);

public void ToggleAll(IEnumerable<string> keys) {
foreach (string key in keys) {
this[key] = !this[key];
}
}
public void Toggle(params string[] keys) => this.ToggleAll(keys);

public void ToggleAll(IEnumerable<char> keys) => this.ToggleAll(keys.Select(c => c.ToString()));

public void Toggle(params string[] keys) => this.ToggleAll(keys);
public void Toggle(params char[] keys) => this.ToggleAll(keys);

public bool Get(string key) => this[key];
Expand Down

0 comments on commit c40f5f8

Please sign in to comment.