Replace redundant code with new common function

This commit is contained in:
Noi 2022-07-05 21:01:30 -07:00
parent ffaae04bc6
commit 2dafdf07db

View file

@ -36,27 +36,20 @@ class Definition {
const string ErrNoRegex = $"No patterns were defined under {nameof(Regex)}"; const string ErrNoRegex = $"No patterns were defined under {nameof(Regex)}";
var regexRules = new List<Regex>(); var regexRules = new List<Regex>();
var rxconf = def[nameof(Regex)]; List<string> inputs;
if (rxconf == null) throw new ModuleLoadException(ErrNoRegex + errpostfx); try {
if (rxconf.Type == JTokenType.Array) { inputs = Misc.LoadStringOrStringArray(def[nameof(Regex)]);
foreach (var input in rxconf.Values<string>()) { } catch (ArgumentNullException) {
try { throw new ModuleLoadException(ErrNoRegex + errpostfx);
regexRules.Add(new Regex(input!, opts)); }
} catch (Exception ex) when (ex is ArgumentException or NullReferenceException) { foreach (var inputRule in inputs) {
throw new ModuleLoadException("Unable to parse regular expression pattern" + errpostfx);
}
}
} else {
var rxstr = rxconf.Value<string>();
try { try {
regexRules.Add(new Regex(rxstr!, opts)); regexRules.Add(new Regex(inputRule, opts));
} catch (Exception ex) when (ex is ArgumentException or NullReferenceException) { } catch (Exception ex) when (ex is ArgumentException or NullReferenceException) {
throw new ModuleLoadException("Unable to parse regular expression pattern" + errpostfx); throw new ModuleLoadException("Unable to parse regular expression pattern" + errpostfx);
} }
} }
if (regexRules.Count == 0) { if (regexRules.Count == 0) throw new ModuleLoadException(ErrNoRegex + errpostfx);
throw new ModuleLoadException(ErrNoRegex + errpostfx);
}
Regex = regexRules.AsReadOnly(); Regex = regexRules.AsReadOnly();
// Filtering // Filtering
@ -66,18 +59,14 @@ class Definition {
// Reply options // Reply options
var replyConf = def[nameof(Reply)]; var replyConf = def[nameof(Reply)];
if (replyConf?.Type == JTokenType.String) { try {
// Single string response Reply = Misc.LoadStringOrStringArray(replyConf);
Reply = new List<string>() { replyConf.Value<string>()! }.AsReadOnly(); haveResponse = Reply.Count > 0;
haveResponse = true; } catch (ArgumentNullException) {
} else if (replyConf?.Type == JTokenType.Array) {
// Have multiple responses
Reply = new List<string>(replyConf.Values<string>()!).AsReadOnly();
haveResponse= true;
} else {
// Have no response
Reply = Array.Empty<string>(); Reply = Array.Empty<string>();
haveResponse = false; haveResponse = false;
} catch (ArgumentException) {
throw new ModuleLoadException($"Encountered a problem within 'Reply'{errpostfx}");
} }
// Command options // Command options