-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCommandService.cs
More file actions
1548 lines (1381 loc) · 60.9 KB
/
CommandService.cs
File metadata and controls
1548 lines (1381 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Ultz.Extensions.Commands.Attributes.Modules;
using Ultz.Extensions.Commands.Builders;
using Ultz.Extensions.Commands.Built;
using Ultz.Extensions.Commands.Context;
using Ultz.Extensions.Commands.Cooldown;
using Ultz.Extensions.Commands.Events;
using Ultz.Extensions.Commands.Extensions;
using Ultz.Extensions.Commands.Mapping;
using Ultz.Extensions.Commands.Parsing.ArgumentParsers;
using Ultz.Extensions.Commands.Parsing.TypeParsers;
using Ultz.Extensions.Commands.Parsing.TypeParsers.Primitive;
using Ultz.Extensions.Commands.Results;
using Ultz.Extensions.Commands.Results.Failed;
using Ultz.Extensions.Commands.Results.Failed.Checks;
using Ultz.Extensions.Commands.Results.Failed.Execution;
using Ultz.Extensions.Commands.Results.Failed.Parsing;
using Ultz.Extensions.Commands.Results.Successful;
using Ultz.Extensions.Commands.Results.User;
using Ultz.Extensions.Events;
using Module = Ultz.Extensions.Commands.Built.Module;
namespace Ultz.Extensions.Commands
{
/// <summary>
/// Provides a framework for handling text based commands.
/// </summary>
public class CommandService : ICommandService
{
private static readonly Type _stringType = typeof(string);
private readonly ConcurrentDictionary<Type, IArgumentParser> _argumentParsers;
private readonly AsynchronousEvent<CommandExecutedEventArgs> _commandExecuted =
new AsynchronousEvent<CommandExecutedEventArgs>();
private readonly AsynchronousEvent<CommandExecutionFailedEventArgs> _commandExecutionFailed =
new AsynchronousEvent<CommandExecutionFailedEventArgs>();
private readonly CommandMap _map;
private readonly object _moduleLock = new object();
private readonly ConcurrentDictionary<Type, IPrimitiveTypeParser> _primitiveTypeParsers;
private readonly HashSet<Module> _topLevelModules;
private readonly ConcurrentDictionary<Type, Dictionary<Type, (bool ReplacingPrimitive, ITypeParser Instance)>>
_typeParsers;
internal readonly StringComparer StringComparer;
/// <summary>
/// Initialises a new <see cref="CommandService" /> with the specified <see cref="CommandServiceConfiguration" />.
/// </summary>
/// <param name="configuration"> The <see cref="CommandServiceConfiguration" /> to use. </param>
/// <exception cref="ArgumentNullException">
/// The configuration must not be null.
/// </exception>
public CommandService(CommandServiceConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration), "The configuration must not be null.");
}
StringComparison = configuration.StringComparison;
DefaultRunMode = configuration.DefaultRunMode;
IgnoresExtraArguments = configuration.IgnoresExtraArguments;
Separator = configuration.Separator;
SeparatorRequirement = configuration.SeparatorRequirement;
CooldownBucketKeyGenerator = configuration.CooldownBucketKeyGenerator;
QuotationMarkMap = configuration.QuoteMap != null
? new ReadOnlyDictionary<char, char>(
configuration.QuoteMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value))
: CommandUtilities.DefaultQuotationMarkMap;
NullableNouns = configuration.NullableNouns != null
? configuration.NullableNouns.ToImmutableArray()
: CommandUtilities.DefaultNullableNouns;
StringComparer = StringComparison.ToComparer();
_topLevelModules = new HashSet<Module>();
TopLevelModules = _topLevelModules.ToArray();
_map = new CommandMap(this);
_argumentParsers = new ConcurrentDictionary<Type, IArgumentParser>(Environment.ProcessorCount, 1);
SetDefaultArgumentParser(configuration.DefaultArgumentParser ??
Parsing.ArgumentParsers.Default.DefaultArgumentParser.Instance);
_typeParsers = new ConcurrentDictionary<Type, Dictionary<Type, (bool, ITypeParser)>>();
_primitiveTypeParsers = new ConcurrentDictionary<Type, IPrimitiveTypeParser>(Environment.ProcessorCount,
CommandUtilities.PrimitiveTypeParserCount * 2);
foreach (var type in Utilities.TryParseDelegates.Keys)
{
var primitiveTypeParser = Utilities.CreatePrimitiveTypeParser(type);
_primitiveTypeParsers.TryAdd(type, primitiveTypeParser);
_primitiveTypeParsers.TryAdd(Utilities.MakeNullable(type),
Utilities.CreateNullablePrimitiveTypeParser(type, primitiveTypeParser));
}
}
/// <summary>
/// Initialises a new <see cref="CommandService" /> with the default <see cref="CommandServiceConfiguration" />.
/// </summary>
public CommandService() : this(CommandServiceConfiguration.Default)
{
}
/// <summary>
/// Gets the <see cref="System.StringComparison" /> used for finding <see cref="Command" />s and <see cref="Module" />s,
/// used by the default <see langword="enum" /> parsers, and comparing <see cref="NullableNouns" />.
/// </summary>
public StringComparison StringComparison { get; }
/// <summary>
/// Gets the default <see cref="RunMode" /> for commands and modules.
/// </summary>
public RunMode DefaultRunMode { get; }
/// <summary>
/// Gets whether <see cref="Command" />s ignore extra arguments by default or not.
/// </summary>
public bool IgnoresExtraArguments { get; }
/// <summary>
/// Gets the <see cref="string" /> separator used between groups and commands.
/// </summary>
public string Separator { get; }
/// <summary>
/// Gets the separator requirement.
/// </summary>
public SeparatorRequirement SeparatorRequirement { get; }
/// <summary>
/// Gets the default <see cref="IArgumentParser" />.
/// </summary>
public IArgumentParser DefaultArgumentParser { get; private set; }
/// <summary>
/// Gets the generator <see langword="delegate" /> used for <see cref="Cooldown" /> bucket keys.
/// </summary>
public CooldownBucketKeyGeneratorDelegate CooldownBucketKeyGenerator { get; }
/// <summary>
/// Gets the quotation mark map used for non-remainder multi word arguments.
/// </summary>
public IReadOnlyDictionary<char, char> QuotationMarkMap { get; }
/// <summary>
/// Gets the collection of nouns used for nullable value type parsing.
/// </summary>
public IReadOnlyList<string> NullableNouns { get; }
/// <summary>
/// Gets the top-level modules.
/// </summary>
public IReadOnlyList<Module> TopLevelModules { get; }
/// <summary>
/// Fires after a <see cref="Command" /> was successfully executed.
/// You must use this to handle <see cref="RunMode.Parallel" /> <see cref="Command" />s.
/// </summary>
public event AsynchronousEventHandler<CommandExecutedEventArgs> CommandExecuted
{
add => _commandExecuted.Hook(value);
remove => _commandExecuted.Unhook(value);
}
/// <summary>
/// Fires after a <see cref="Command" /> failed to execute.
/// You must use this to handle <see cref="RunMode.Parallel" /> <see cref="Command" />s.
/// </summary>
public event AsynchronousEventHandler<CommandExecutionFailedEventArgs> CommandExecutionFailed
{
add => _commandExecutionFailed.Hook(value);
remove => _commandExecutionFailed.Unhook(value);
}
/// <summary>
/// Gets all of the added <see cref="Command" />s.
/// </summary>
/// <returns>
/// A list of <see cref="Command" />s.
/// </returns>
public IReadOnlyList<Command> GetAllCommands()
{
static IEnumerable<Command> GetCommands(Module module)
{
for (var i = 0; i < module.Commands.Count; i++)
{
yield return module.Commands[i];
}
for (var i = 0; i < module.Submodules.Count; i++)
{
foreach (var command in GetCommands(module.Submodules[i]))
{
yield return command;
}
}
}
lock (_moduleLock)
{
return _topLevelModules.SelectMany(GetCommands).ToImmutableArray();
}
}
/// <summary>
/// Gets all of the added <see cref="Module" />s.
/// </summary>
/// <returns>
/// A list of <see cref="Module" />s.
/// </returns>
public IReadOnlyList<Module> GetAllModules()
{
static IEnumerable<Module> GetSubmodules(Module module)
{
for (var i = 0; i < module.Submodules.Count; i++)
{
var submodule = module.Submodules[i];
yield return submodule;
foreach (var subsubmodule in GetSubmodules(submodule))
{
yield return subsubmodule;
}
}
}
lock (_moduleLock)
{
var builder = ImmutableArray.CreateBuilder<Module>();
foreach (var module in _topLevelModules)
{
builder.Add(module);
builder.AddRange(GetSubmodules(module));
}
return builder.TryMoveToImmutable();
}
}
/// <summary>
/// Attempts to find <see cref="Command" />s matching the provided path.
/// </summary>
/// <param name="path"> The path to use for searching. </param>
/// <returns>
/// An ordered list of <see cref="CommandMatch" />es.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The path must not be null.
/// </exception>
public IReadOnlyList<CommandMatch> FindCommands(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path), "The path to find commands for must not be null.");
}
List<CommandMatch> list;
lock (_moduleLock)
{
var matches = _map.FindCommands(path);
if (matches.Count == 0)
{
return matches;
}
// TODO nuke this if custom maps are a thing
list = matches as List<CommandMatch>;
}
list.Sort(Utilities.CommandOverloadComparer.Instance);
return list.AsReadOnly();
}
/// <summary>
/// Sets an <see cref="IArgumentParser" /> of the specified <typeparamref name="T" /> <see cref="Type" /> as the default
/// parser.
/// </summary>
/// <typeparam name="T"> The <see cref="Type" /> of the <see cref="IArgumentParser" />. </typeparam>
/// <exception cref="ArgumentException">
/// An argument parser of this type has not been added.
/// </exception>
public void SetDefaultArgumentParser<T>() where T : IArgumentParser
{
SetDefaultArgumentParser(typeof(T));
}
/// <summary>
/// Sets an <see cref="IArgumentParser" /> of the specified <see cref="Type" /> as the default parser.
/// </summary>
/// <param name="type"> The <see cref="Type" /> of the <see cref="IArgumentParser" />. </param>
/// <exception cref="ArgumentNullException">
/// The argument parser type to set must not be null.
/// </exception>
/// <exception cref="ArgumentException">
/// An argument parser of this type has not been added.
/// </exception>
public void SetDefaultArgumentParser(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type), "The argument parser type to set must not be null.");
}
var parser = GetArgumentParser(type);
if (parser == null)
{
throw new ArgumentException("An argument parser of this type has not been added.", nameof(type));
}
DefaultArgumentParser = parser;
}
/// <summary>
/// Sets and adds, if it has not been added before, an <see cref="IArgumentParser" /> as the default parser.
/// </summary>
/// <param name="parser"> The <see cref="IArgumentParser" /> to set. </param>
/// <exception cref="ArgumentNullException">
/// The argument parser to set must not be null.
/// </exception>
public void SetDefaultArgumentParser(IArgumentParser parser)
{
if (parser == null)
{
throw new ArgumentNullException(nameof(parser), "The argument parser to add must not be null.");
}
_argumentParsers.TryAdd(parser.GetType(), parser);
DefaultArgumentParser = parser;
}
/// <summary>
/// Adds an <see cref="IArgumentParser" />.
/// </summary>
/// <param name="parser"> The <see cref="IArgumentParser" /> to add. </param>
/// <exception cref="ArgumentNullException">
/// The argument parser to add must not be null.
/// </exception>
public void AddArgumentParser(IArgumentParser parser)
{
if (parser == null)
{
throw new ArgumentNullException(nameof(parser), "The argument parser to add must not be null.");
}
if (!_argumentParsers.TryAdd(parser.GetType(), parser))
{
throw new ArgumentException("This argument parser has already been added.", nameof(parser));
}
}
/// <summary>
/// Removes an <see cref="IArgumentParser" /> of the specified <typeparamref name="T" /> <see cref="Type" />.
/// </summary>
/// <typeparam name="T"> The <see cref="Type" /> of the <see cref="IArgumentParser" />. </typeparam>
public void RemoveArgumentParser<T>() where T : IArgumentParser
{
RemoveArgumentParser(typeof(T));
}
/// <summary>
/// Removes an <see cref="IArgumentParser" /> of the specified <see cref="Type" />.
/// </summary>
/// <param name="type"> The <see cref="Type" /> of the <see cref="IArgumentParser" />. </param>
/// <exception cref="ArgumentNullException">
/// The argument parser type to remove must not be null.
/// </exception>
/// <exception cref="ArgumentException">
/// The argument parser type to remove must not be the default argument parser's type.
/// </exception>
/// <exception cref="ArgumentException">
/// This argument parser type has not been added.
/// </exception>
public void RemoveArgumentParser(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type), "The argument parser type to remove must not be null.");
}
if (DefaultArgumentParser.GetType() == type)
{
throw new ArgumentException(
"The argument parser type to remove must not be the default argument parser's type.", nameof(type));
}
if (!_argumentParsers.TryRemove(type, out _))
{
throw new ArgumentException("This argument parser type has not been added.", nameof(type));
}
}
/// <summary>
/// Gets an <see cref="IArgumentParser" /> of the specified <typeparamref name="T" /> <see cref="Type" />.
/// </summary>
/// <typeparam name="T"> The <see cref="Type" /> of the <see cref="IArgumentParser" />. </typeparam>
/// <returns>
/// The <see cref="IArgumentParser" /> or <see langword="null" />.
/// </returns>
public IArgumentParser GetArgumentParser<T>() where T : IArgumentParser
{
return GetArgumentParser(typeof(T));
}
/// <summary>
/// Gets an <see cref="IArgumentParser" /> of the specified <see cref="Type" />.
/// </summary>
/// <param name="type"> The <see cref="Type" /> of the <see cref="IArgumentParser" />. </param>
/// <returns>
/// The <see cref="IArgumentParser" /> or <see langword="null" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The argument parser type to get must not be null.
/// </exception>
public IArgumentParser GetArgumentParser(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type), "The argument parser type to get must not be null.");
}
return _argumentParsers.TryGetValue(type, out var parser)
? parser
: null;
}
/// <summary>
/// Adds a <see cref="TypeParser{T}" /> for the specified <typeparamref name="T" /> <see cref="Type" />.
/// </summary>
/// <typeparam name="T"> The type to add the <paramref name="parser" /> for. </typeparam>
/// <param name="parser"> The <see cref="TypeParser{T}" /> to add for the <see cref="Type" />. </param>
/// <param name="replacePrimitive"> Whether to replace the primitive parser. </param>
/// <exception cref="ArgumentNullException">
/// The type parser to add must not be null.
/// </exception>
public void AddTypeParser<T>(TypeParser<T> parser, bool replacePrimitive = false)
{
if (parser == null)
{
throw new ArgumentNullException(nameof(parser), "The type parser to add must not be null.");
}
var type = typeof(T);
if (Utilities.IsNullable(type))
{
throw new ArgumentException("Cannot add custom type parsers for nullable types.", nameof(T));
}
if (replacePrimitive)
{
if (GetPrimitiveTypeParser(type) == null)
{
throw new ArgumentException($"No primitive type parser found to replace for type {type}.",
nameof(T));
}
var existingParser = GetAnyTypeParser(type, true);
if (existingParser != null)
{
throw new ArgumentException(
$"There is already a custom type parser replacing the primitive parser for type {type} - {existingParser.GetType()}.");
}
}
AddTypeParserInternal(type, parser, replacePrimitive);
}
/// <summary>
/// Removes a <see cref="TypeParser{T}" /> for the specified <see cref="Type" />.
/// </summary>
/// <typeparam name="T"> The <see cref="Type" /> to remove the <paramref name="parser" /> for. </typeparam>
/// <param name="parser"> The <see cref="TypeParser{T}" /> to remove for the <see cref="Type" />. </param>
/// <exception cref="ArgumentNullException">
/// The type parser to remove must not be null.
/// </exception>
/// <exception cref="ArgumentException">
/// The type parser to remove has not been added.
/// </exception>
public void RemoveTypeParser<T>(TypeParser<T> parser)
{
if (parser == null)
{
throw new ArgumentNullException(nameof(parser), "The type parser to remove must not be null.");
}
var type = typeof(T);
var parserType = parser.GetType();
bool found;
if (_typeParsers.TryGetValue(type, out var typeParsers))
{
lock (typeParsers)
{
found = typeParsers.Remove(parserType);
}
}
else
{
found = false;
}
if (!found)
{
throw new ArgumentException("The type parser to remove has not been added.");
}
if (type.IsValueType)
{
var nullableType = Utilities.MakeNullable(type);
if (_typeParsers.TryGetValue(nullableType, out var nullableTypeParsers))
{
lock (nullableTypeParsers)
{
nullableTypeParsers.Remove(parserType);
}
}
}
}
/// <summary>
/// Removes all added <see cref="TypeParser{T}" />s. This does not affect primitive type parsers.
/// </summary>
public void RemoveAllTypeParsers()
{
_typeParsers.Clear();
}
/// <summary>
/// Retrieves a <see cref="TypeParser{T}" /> from the added non-primitive parsers for the specified
/// <typeparamref name="T" /> <see cref="Type" />.
/// </summary>
/// <typeparam name="T"> The <see cref="Type" /> the <see cref="TypeParser{T}" /> is for. </typeparam>
/// <param name="replacingPrimitive">
/// Whether the <see cref="TypeParser{T}" /> replaces one of the primitive parsers or
/// not.
/// </param>
/// <returns>
/// The <see cref="TypeParser{T}" /> or <see langword="null" /> if not found.
/// </returns>
public TypeParser<T> GetTypeParser<T>(bool replacingPrimitive = false)
{
return GetAnyTypeParser(typeof(T), replacingPrimitive) as TypeParser<T>;
}
/// <summary>
/// Retrieves a <see cref="TypeParser{T}" /> of the specified <typeparamref name="TParser" /> <see cref="Type" />.
/// </summary>
/// <typeparam name="T"> The <see cref="Type" /> the <see cref="TypeParser{T}" /> is for. </typeparam>
/// <typeparam name="TParser"> The <see cref="Type" /> of the <see cref="TypeParser{T}" />. </typeparam>
/// <returns>
/// The <see cref="TypeParser{T}" /> of the specified <typeparamref name="TParser" /> <see cref="Type" /> or
/// <see langword="null" /> if not found.
/// </returns>
public TParser GetSpecificTypeParser<T, TParser>() where TParser : TypeParser<T>
{
return GetSpecificTypeParser(typeof(T), typeof(TParser)) as TParser;
}
/// <summary>
/// Attempts to add all valid <see cref="Module" />s and <see cref="Command" />s found in the provided
/// <see cref="Assembly" />.
/// </summary>
/// <param name="assembly"> The assembly to search. </param>
/// <param name="predicate">
/// The optional <see cref="Predicate{T}" /> delegate that defines the conditions of the
/// <see cref="Type" />s to add as <see cref="Module" />s.
/// </param>
/// <param name="action">
/// The optional <see cref="Action{T}" /> delegate that allows for mutation of the
/// <see cref="ModuleBuilder" />s before they are built.
/// </param>
/// <returns>
/// An <see cref="IReadOnlyList{Module}" /> of all found and added <see cref="Module" />s.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The assembly to add modules from must not be null.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map commands to the root node.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same signature.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same argument types, with one of them being a remainder, if the other one
/// ignores extra arguments.
/// </exception>
public IReadOnlyList<Module> AddModules(Assembly assembly, Predicate<TypeInfo> predicate = null,
Action<ModuleBuilder> action = null)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly), "The assembly to add modules from must not be null.");
}
var modules = ImmutableArray.CreateBuilder<Module>();
var types = assembly.GetExportedTypes();
for (var i = 0; i < types.Length; i++)
{
var typeInfo = types[i].GetTypeInfo();
if (!Utilities.IsValidModuleDefinition(typeInfo) || typeInfo.IsNested ||
typeInfo.GetCustomAttribute<DoNotAddAttribute>() != null)
{
continue;
}
if (predicate != null && !predicate(typeInfo))
{
continue;
}
try
{
modules.Add(AddModule(typeInfo.AsType(), action));
}
catch
{
for (var j = 0; j < modules.Count; j++)
{
RemoveModule(modules[j]);
}
throw;
}
}
return modules.TryMoveToImmutable();
}
/// <summary>
/// Attempts to instantiate, modify, and build a <see cref="ModuleBuilder" /> into a <see cref="Module" />.
/// </summary>
/// <param name="action"> The action to perform on the builder. </param>
/// <returns>
/// A <see cref="Module" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The module builder action must not be null.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map commands to the root node.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same signature.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same argument types, with one of them being a remainder, if the other one
/// ignores extra arguments.
/// </exception>
public Module AddModule(Action<ModuleBuilder> action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action), "The action must not be null.");
}
var builder = new ModuleBuilder(null);
action(builder);
var module = builder.Build(this, null);
AddModuleInternal(module);
return module;
}
/// <summary>
/// Adds the specified <see cref="Module" />.
/// </summary>
/// <param name="module"> The <see cref="Module" /> to add. </param>
/// <exception cref="ArgumentNullException">
/// The module to add must not be null.
/// </exception>
/// <exception cref="ArgumentException">
/// This module has already been added.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map commands to the root node.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same signature.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same argument types, with one of them being a remainder, if the other one
/// ignores extra arguments.
/// </exception>
public void AddModule(Module module)
{
if (module == null)
{
throw new ArgumentNullException(nameof(module), "The module to add must not be null.");
}
if (module.Parent != null)
{
throw new ArgumentException("The module to add must not be a nested module.", nameof(module));
}
lock (_moduleLock)
{
if (_topLevelModules.Contains(module))
{
throw new ArgumentException("This module has already been added.", nameof(module));
}
AddModuleInternal(module);
}
}
/// <summary>
/// Attempts to add the specified <typeparamref name="TModule" /> <see cref="Type" /> as a <see cref="Module" />.
/// </summary>
/// <typeparam name="TModule"> The <see cref="Type" /> to add. </typeparam>
/// <param name="action">
/// The optional <see cref="Action{T}" /> delegate that allows for mutation of the
/// <see cref="ModuleBuilder" /> before it is built.
/// </param>
/// <returns>
/// A <see cref="Module" />.
/// </returns>
/// <exception cref="ArgumentException">
/// The type has already been added as a module.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map commands to the root node.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same signature.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same argument types, with one of them being a remainder, if the other one
/// ignores extra arguments.
/// </exception>
public Module AddModule<TModule>(Action<ModuleBuilder> action = null)
{
return AddModule(typeof(TModule), action);
}
/// <summary>
/// Attempts to add the specified <see cref="Type" /> as a <see cref="Module" />.
/// </summary>
/// <param name="type"> The <see cref="Type" /> to add. </param>
/// <param name="action">
/// The optional <see cref="Action{T}" /> delegate that allows for mutation of the
/// <see cref="ModuleBuilder" /> before it is built.
/// </param>
/// <returns>
/// A <see cref="Module" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The type to add must not be null.
/// </exception>
/// <exception cref="ArgumentException">
/// The type has already been added as a module.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map commands to the root node.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same signature.
/// </exception>
/// <exception cref="CommandMappingException">
/// Cannot map multiple overloads with the same argument types, with one of them being a remainder, if the other one
/// ignores extra arguments.
/// </exception>
public Module AddModule(Type type, Action<ModuleBuilder> action = null)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type), "The type to add must not be null.");
}
var builder = Utilities.CreateModuleBuilder(this, null, type.GetTypeInfo());
action?.Invoke(builder);
var module = builder.Build(this, null);
AddModuleInternal(module);
return module;
}
/// <summary>
/// Removes the specified <see cref="Module" />.
/// </summary>
/// <param name="module"> The <see cref="Module" /> to remove. </param>
/// <exception cref="ArgumentNullException">
/// The module to remove must not be null.
/// </exception>
/// <exception cref="ArgumentException">
/// This module has not been added.
/// </exception>
public void RemoveModule(Module module)
{
if (module == null)
{
throw new ArgumentNullException(nameof(module), "The module to remove must not be null.");
}
RemoveModuleInternal(module);
}
/// <summary>
/// Removes all added <see cref="Module" />s.
/// </summary>
public void RemoveAllModules()
{
Module[] topLevelModules;
lock (_moduleLock)
{
topLevelModules = _topLevelModules.ToArray();
for (var i = 0; i < topLevelModules.Length; i++)
{
RemoveModuleInternal(topLevelModules[i]);
}
}
}
/// <summary>
/// Attempts to find <see cref="Command" />s matching the input and executes the most suitable one.
/// </summary>
/// <param name="input"> The input. </param>
/// <param name="context"> The <see cref="CommandContext" /> to use during execution. </param>
/// <returns>
/// An <see cref="IResult" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The input must not be null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The context must not be null.
/// </exception>
public async Task<IResult> ExecuteAsync(string input, CommandContext context)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input), "The input must not be null.");
}
if (context == null)
{
throw new ArgumentNullException(nameof(context), "The context must not be null.");
}
var matches = FindCommands(input);
if (matches.Count == 0)
{
return new CommandNotFoundResult();
}
var pathLength = matches[0].Path.Count;
Dictionary<Command, FailedResult> failedOverloads = null;
for (var i = 0; i < matches.Count; i++)
{
var match = matches[i];
if (match.Path.Count < pathLength)
{
continue;
}
if (!match.Command.IsEnabled)
{
AddFailedOverload(ref failedOverloads, match.Command, new CommandDisabledResult(match.Command));
continue;
}
context.Command = match.Command;
context.Alias = match.Alias;
context.Path = match.Path;
context.RawArguments = match.RawArguments;
try
{
var checkResult = await match.Command.RunChecksAsync(context).ConfigureAwait(false);
if (checkResult is ChecksFailedResult checksFailedResult)
{
if (checksFailedResult.Module != null || matches.Count == 1)
{
return checksFailedResult;
}
AddFailedOverload(ref failedOverloads, match.Command, checksFailedResult);
continue;
}
}
catch (Exception ex)
{
var executionFailedResult =
new ExecutionFailedResult(match.Command, CommandExecutionStep.Checks, ex);
await InvokeCommandErroredAsync(executionFailedResult, context).ConfigureAwait(false);
return executionFailedResult;
}
ArgumentParserResult argumentParserResult;
try
{
IArgumentParser argumentParser;
if (match.Command.CustomArgumentParserType != null)
{
argumentParser = GetArgumentParser(match.Command.CustomArgumentParserType);
if (argumentParser == null)
{
throw new InvalidOperationException(
$"Custom argument parser of type {match.Command.CustomArgumentParserType} for command {match.Command} not found.");
}
}
else
{
argumentParser = DefaultArgumentParser;
}
argumentParserResult = await argumentParser.ParseAsync(context).ConfigureAwait(false);
if (argumentParserResult == null)
{
throw new InvalidOperationException(
"The result from IArgumentParser.ParseAsync must not be null.");
}
if (!argumentParserResult.IsSuccessful)
{
if (matches.Count == 1)
{
return new ArgumentParseFailedResult(context, argumentParserResult);
}
AddFailedOverload(ref failedOverloads, match.Command,
new ArgumentParseFailedResult(context, argumentParserResult));
continue;
}
}
catch (Exception ex)
{
var executionFailedResult =
new ExecutionFailedResult(match.Command, CommandExecutionStep.ArgumentParsing, ex);
await InvokeCommandErroredAsync(executionFailedResult, context).ConfigureAwait(false);
return executionFailedResult;
}
object[] parsedArguments;
try
{
var result = await CreateArgumentsAsync(argumentParserResult, context).ConfigureAwait(false);
if (result.FailedResult != null)
{
if (matches.Count == 1)
{
return result.FailedResult;
}
AddFailedOverload(ref failedOverloads, match.Command, result.FailedResult);
continue;
}
parsedArguments = result.ParsedArguments;
}
catch (Exception ex)
{
var executionFailedResult =
new ExecutionFailedResult(match.Command, CommandExecutionStep.TypeParsing, ex);
await InvokeCommandErroredAsync(executionFailedResult, context).ConfigureAwait(false);
return executionFailedResult;
}
context.InternalArguments = parsedArguments;
return await InternalExecuteAsync(context).ConfigureAwait(false);
}
return new OverloadsFailedResult(failedOverloads);
}
/// <summary>
/// Attempts to parse the arguments for the provided <see cref="Command" /> and execute it.
/// </summary>
/// <param name="command"> The <see cref="Command" /> to execute. </param>
/// <param name="rawArguments"> The raw arguments to use for this <see cref="Command" />'s parameters. </param>
/// <param name="context"> The <see cref="CommandContext" /> to use during execution. </param>
/// <returns>
/// An <see cref="IResult" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The command must not be null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The raw arguments must not be null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The context must not be null.
/// </exception>
public async Task<IResult> ExecuteAsync(Command command, string rawArguments, CommandContext context)
{
if (command == null)
{
throw new ArgumentNullException(nameof(command), "The command must not be null.");
}
if (rawArguments == null)
{
throw new ArgumentNullException(nameof(rawArguments), "The raw arguments must not be null.");
}
if (context == null)