-
Notifications
You must be signed in to change notification settings - Fork 59
/
GpCommandLineParser.pas
1153 lines (1036 loc) · 39.6 KB
/
GpCommandLineParser.pas
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
///<summary>Attribute based command line parser.</summary>
///<author>Primoz Gabrijelcic</author>
///<remarks><para>
/// (c) 2019 Primoz Gabrijelcic
/// Free for personal and commercial use. No rights reserved.
///
/// Author : Primoz Gabrijelcic
/// Creation date : 2014-05-25
/// Last modification : 2019-08-18
/// Version : 1.05a
///</para><para>
/// History:
/// 1.05a: 2019-08-18
/// - '/' is not a valid switch delimiter on non-Windows platforms.
/// 1.05: 2018-10-16
/// - Added attribute [CLPExtendable] which allows the application to define switch
/// 'switch' that can be use as /switchextension. Application can get this
/// extension by calling the GetExtension function.
/// - Added function IGpCommandLineParser.GetExtension.
/// 1.04: 2018-02-20
/// - Added parameter `wrapAtColumn` to IGpCommandLineParser.Usage. Use value <= 0
/// to disable wrapping.
/// 1.03: 2015-02-02
/// - Multiple long names can be assigned to a single entity.
/// 1.02: 2015-01-29
/// - Added option opIgnoreUnknownSwitches which causes parser not to
/// trigger an error when it encounters an unknown switch.
/// 1.01a: 2015-01-28
/// - String comparer is no longer destroyed (as it is just a reference to
/// the global singleton).
/// 1.01: 2014-08-21
/// - A short form of a long name can be provided.
/// - Fixed a small memory leak.
/// 1.0a: 2014-07-03
/// - Fixed processing of quoted positional parameters.
/// 1.0: 2014-06-22
/// - Released
///</para></remarks>
// example parameter configuration
// TCommandLine = class
// strict private
// FAutoTest : boolean;
// FExtraFiles: string;
// FFromDate : string;
// FImportDir : string;
// FInputFile : string;
// FNumDays : integer;
// FOutputFile: string;
// FPrecision : string;
// FToDateTime: string;
// public
// [CLPLongName('ToDate'), CLPDescription('Set ending date/time', '<dt>')]
// property ToDateTime: string read FToDateTime write FToDateTime;
//
// [CLPDescription('Set precision'), CLPDefault('3.14')]
// property Precision: string read FPrecision write FPrecision;
//
// [CLPName('i'), CLPLongName('ImportDir'), CLPDescription('Set import folder', '<path>')]
// property ImportDir: string read FImportDir write FImportDir;
//
// [CLPName('a'), CLPLongName('AutoTest', 'Auto'), CLPDescription('Enable autotest mode. And now some long text for testing word wrap in Usage.')]
// property AutoTest: boolean read FAutoTest write FAutoTest;
//
// [CLPName('f'), CLPLongName('FromDate'), CLPDescription('Set starting date', '<dt>'), CLPRequired]
// property FromDate: string read FFromDate write FFromDate;
//
// [CLPName('n'), CLPDescription('Set number of days', '<days>'), CLPDefault('100')]
// property NumDays: integer read FNumDays write FNumDays;
//
// [CLPPosition(1), CLPDescription('Input file'), CLPLongName('input_file'), CLPRequired]
// property InputFile: string read FInputFile write FInputFile;
//
// [CLPPosition(2), CLPDescription('Output file'), CLPRequired]
// property OutputFile: string read FOutputFile write FOutputFile;
//
// [CLPPositionRest, CLPDescription('Extra files'), CLPName('extra_files')]
// property ExtraFiles: string read FExtraFiles write FExtraFiles;
// end;
unit GpCommandLineParser;
interface
uses
System.SysUtils,
System.TypInfo,
System.RTTI;
type
/// <summary>
/// Specifies short (one letter) name for the switch.
/// </summary>
CLPNameAttribute = class(TCustomAttribute)
strict private
FName: string;
public
constructor Create(const name: string);
property Name: string read FName;
end; { CLPNameAttribute }
/// <summary>
/// Specifies long name for the switch. If not set, property name is used
/// for long name.
/// A short form of the long name can also be provided which must match the beginning
/// of the long form. In this case, parser will accept shortened versions of the
/// long name, but no shorter than the short form.
/// An example: if 'longName' = 'autotest' and 'shortForm' = 'auto' then the parser
/// will accept 'auto', 'autot', 'autote', 'autotes' and 'autotest', but not 'aut',
/// 'au' and 'a'.
/// Multiple long names (alternate switches) can be provided for one entity.
/// </summary>
CLPLongNameAttribute = class(TCustomAttribute)
strict private
FLongName : string;
FShortForm: string;
public
constructor Create(const longName: string; const shortForm: string = '');
property LongName: string read FLongName;
property ShortForm: string read FShortForm;
end; { CLPNameAttribute }
/// <summary>
/// Specifies default value which will be used if switch is not found on
/// the command line.
/// </summary>
CLPDefaultAttribute = class(TCustomAttribute)
strict private
FDefaultValue: string;
public
constructor Create(const value: string); overload;
property DefaultValue: string read FDefaultValue;
end; { CLPDefaultAttribute }
/// <summary>
/// Provides switch description, used for the Usage function.
/// </summary>
CLPDescriptionAttribute = class(TCustomAttribute)
strict private
FDescription: string;
FParamName : string;
public
const DefaultValue = 'value';
constructor Create(const description: string; const paramName: string = '');
property Description: string read FDescription;
property ParamName: string read FParamName;
end; { CLPDescriptionAttribute }
/// <summary>
/// When present, specifies that the switch is required.
/// </summary>
CLPRequiredAttribute = class(TCustomAttribute)
public
end; { CLPRequiredAttribute }
/// <summary>
/// When present, specifies that the switch name can be arbitrarily extended.
/// The code can access this extension via GetExtension function.
/// </summary>
CLPExtendableAttribute = class(TCustomAttribute)
public
end; { CLPExtendableAttribute }
/// <summary>
/// Specifies position of a positional (unnamed) switch. First positional
/// switch has position 1.
/// </summary>
CLPPositionAttribute = class(TCustomAttribute)
strict private
FPosition: integer;
public
constructor Create(position: integer);
property Position: integer read FPosition;
end; { CLPPositionAttribute }
/// <summary>
/// Specifies switch that will receive a #13-delimited list of all
/// positional parameters for which switch definitions don't exist.
/// </summary>
CLPPositionRestAttribute = class(TCustomAttribute)
public
end; { CLPPositionRestAttribute }
TCLPErrorKind = (
//configuration error, will result in exception
ekPositionalsBadlyDefined, ekNameNotDefined, ekShortNameTooLong, ekLongFormsDontMatch,
//user data error, will result in error result
ekMissingPositional, ekExtraPositional, ekMissingNamed, ekUnknownNamed, ekInvalidData);
TCLPErrorDetailed = (
edBooleanWithData, // SBooleanSwitchCannotAcceptData
edCLPPositionRestNotString, // STypeOfACLPPositionRestPropertyMu
edExtraCLPPositionRest, // SOnlyOneCLPPositionRestPropertyIs
edInvalidDataForSwitch, // SInvalidDataForSwitch
edLongFormsDontMatch, // SLongFormsDontMatch
edMissingNameForProperty, // SMissingNameForProperty
edMissingPositionalDefinition, // SMissingPositionalParameterDefini
edMissingRequiredSwitch, // SRequiredSwitchWasNotProvided
edPositionNotPositive, // SPositionMustBeGreaterOrEqualTo1
edRequiredAfterOptional, // SRequiredPositionalParametersMust
edShortNameTooLong, // SShortNameMustBeOneLetterLong
edTooManyPositionalArguments, // STooManyPositionalArguments
edUnknownSwitch, // SUnknownSwitch
edUnsupportedPropertyType, // SUnsupportedPropertyType
edMissingRequiredParameter // SRequiredParameterWasNotProvided
);
TCLPErrorInfo = record
IsError : boolean;
Kind : TCLPErrorKind;
Detailed : TCLPErrorDetailed;
Position : integer;
SwitchName: string;
Text : string;
end; { TCLPErrorInfo }
TCLPOption = (opIgnoreUnknownSwitches);
TCLPOptions = set of TCLPOption;
IGpCommandLineParser = interface ['{C9B729D4-3706-46DB-A8A2-1E07E04F497B}']
function GetErrorInfo: TCLPErrorInfo;
function GetOptions: TCLPOptions;
procedure SetOptions(const value: TCLPOptions);
//
function GetExtension(const switch: string): string;
function Usage(wrapAtColumn: integer = 80): TArray<string>;
function Parse(commandData: TObject): boolean; overload;
function Parse(const commandLine: string; commandData: TObject): boolean; overload;
property ErrorInfo: TCLPErrorInfo read GetErrorInfo;
property Options: TCLPOptions read GetOptions write SetOptions;
end; { IGpCommandLineParser }
ECLPConfigurationError = class(Exception)
ErrorInfo: TCLPErrorInfo;
constructor Create(const errInfo: TCLPErrorInfo);
end; { ECLPConfigurationError }
/// <summary>
/// Returns global parser instance. Not thread-safe.
/// </summary>
function CommandLineParser: IGpCommandLineParser;
/// <summary>
/// Create new command line parser instance. Thread-safe.
/// </summary>
function CreateCommandLineParser: IGpCommandLineParser;
implementation
uses
System.StrUtils,
System.Classes,
System.Generics.Defaults,
System.Generics.Collections;
resourcestring
SBooleanSwitchCannotAcceptData = 'Boolean switch cannot accept data.';
SDefault = ', default: ';
SInvalidDataForSwitch = 'Invalid data for switch.';
SLongFormsDontMatch = 'Short version of the long name must match beginning of the long name';
SMissingNameForProperty = 'Missing name for property.';
SMissingPositionalParameterDefini = 'Missing positional parameter definition.';
SOnlyOneCLPPositionRestPropertyIs = 'Only one CLPPositionRest property is allowed.';
SOptions = '[options]';
SPositionMustBeGreaterOrEqualTo1 = 'Position must be greater or equal to 1.';
SRequiredParameterWasNotProvided = 'Required parameter was not provided.';
SRequiredPositionalParametersMust = 'Required positional parameters must not appear after optional positional parameters.';
SRequiredSwitchWasNotProvided = 'Required switch was not provided.';
SShortNameMustBeOneLetterLong = 'Short name must be one letter long';
STooManyPositionalArguments = 'Too many positional arguments.';
STypeOfACLPPositionRestPropertyMu = 'Type of a CLPPositionRest property must be string.';
SUnknownSwitch = 'Unknown switch.';
SUnsupportedPropertyType = 'Unsupported property %s type.';
type
TCLPSwitchType = (stString, stInteger, stBoolean);
TCLPSwitchOption = (soRequired, soPositional, soPositionRest, soExtendable);
TCLPSwitchOptions = set of TCLPSwitchOption;
TCLPLongName = record
LongForm : string;
ShortForm: string;
constructor Create(const ALongForm, AShortForm: string);
end; { TCLPLongName }
TCLPLongNames = TArray<TCLPLongName>;
TSwitchData = class
strict private
FDefaultValue : string;
FDescription : string;
FInstance : TObject;
FLongNames : TCLPLongNames;
FName : string;
FOptions : TCLPSwitchOptions;
FParamDesc : string;
FParamValue : string;
FPosition : integer;
FPropertyName : string;
FProvided : boolean;
FShortLongForm: string;
FSwitchType : TCLPSwitchType;
strict protected
function Quote(const value: string): string;
public
constructor Create(instance: TObject; const propertyName, name: string;
const longNames: TCLPLongNames; switchType: TCLPSwitchType; position: integer;
options: TCLPSwitchOptions; const defaultValue, description, paramName: string);
function AppendValue(const value, delim: string; doQuote: boolean): boolean;
procedure Enable;
function GetValue: string;
function SetValue(const value: string): boolean;
property DefaultValue: string read FDefaultValue;
property Description: string read FDescription;
property LongNames: TCLPLongNames read FLongNames;
property Name: string read FName;
property Options: TCLPSwitchOptions read FOptions;
property ParamName: string read FParamDesc;
property ParamValue: string read FParamValue write FParamValue;
property Position: integer read FPosition write FPosition;
property PropertyName: string read FPropertyName;
property Provided: boolean read FProvided;
property ShortLongForm: string read FShortLongForm;
property SwitchType: TCLPSwitchType read FSwitchType;
end; { TSwitchData }
TGpCommandLineParser = class(TInterfacedObject, IGpCommandLineParser)
strict private
const
{$IFDEF MSWINDOWS}
FSwitchDelims: array [1..3] of string = ('/', '--', '-');
{$ELSE}
FSwitchDelims: array [1..2] of string = ('--', '-');
{$ENDIF}
FParamDelims : array [1..2] of char = (':', '=');
var
FErrorInfo : TCLPErrorInfo;
FOptions : TCLPOptions;
FPositionals : TArray<TSwitchData>;
FSwitchComparer: TStringComparer;
FSwitchDict : TDictionary<string,TSwitchData>;
FSwitchList : TObjectList<TSwitchData>;
strict protected
procedure AddSwitch(instance: TObject; const propertyName, name: string; const longNames:
TCLPLongNames; switchType: TCLPSwitchType; position: integer; options:
TCLPSwitchOptions; const defaultValue, description, paramName: string);
function CheckAttributes: boolean;
function FindExtendableSwitch(const el: string; var param: string; var data: TSwitchData): boolean;
function GetCommandLine: string;
function GetErrorInfo: TCLPErrorInfo; inline;
function GetOptions: TCLPOptions;
function GrabNextElement(var s, el: string): boolean;
function IsSwitch(const el: string; var param: string; var data: TSwitchData): boolean;
function MapPropertyType(const prop: TRttiProperty): TCLPSwitchType;
procedure ProcessAttributes(instance: TObject; const prop: TRttiProperty);
function ProcessCommandLine(commandData: TObject; const commandLine: string): boolean;
procedure ProcessDefinitionClass(commandData: TObject);
function SetError(kind: TCLPErrorKind; detail: TCLPErrorDetailed; const text: string;
position: integer = 0; switchName: string = ''): boolean;
procedure SetOptions(const value: TCLPOptions);
protected // used in TGpUsageFormatter
property Positionals: TArray<TSwitchData> read FPositionals;
property SwitchList: TObjectList<TSwitchData> read FSwitchList;
public
constructor Create;
destructor Destroy; override;
function GetExtension(const switch: string): string;
function Parse(const commandLine: string; commandData: TObject): boolean; overload;
function Parse(commandData: TObject): boolean; overload;
function Usage(wrapAtColumn: integer = 80): TArray<string>;
property ErrorInfo: TCLPErrorInfo read GetErrorInfo;
property Options: TCLPOptions read GetOptions write SetOptions;
end; { TGpCommandLineParser }
TGpUsageFormatter = class
private
function AddParameter(const name, delim: string; const data: TSwitchData): string;
procedure AlignAndWrap(sl: TStringList; wrapAtColumn: integer);
function Wrap(const name: string; const data: TSwitchData): string;
function LastSpaceBefore(const s: string; startPos: integer): integer;
public
procedure Usage(parser: TGpCommandLineParser; wrapAtColumn: integer;
var usageList: TArray<string>);
end; { TGpUsageFormatter }
var
GGpCommandLineParser: IGpCommandLineParser;
{ exports }
function CommandLineParser: IGpCommandLineParser;
begin
if not assigned(GGpCommandLineParser) then
GGpCommandLineParser := CreateCommandLineParser;
Result := GGpCommandLineParser;
end; { CommandLineParser }
function CreateCommandLineParser: IGpCommandLineParser;
begin
Result := TGpCommandLineParser.Create;
end; { CreateCommandLineParser }
{ CLPNameAttribute }
constructor CLPNameAttribute.Create(const name: string);
begin
inherited Create;
FName := name;
end; { CLPNameAttribute.Create }
{ CLPLongNameAttribute }
constructor CLPLongNameAttribute.Create(const longName, shortForm: string);
begin
inherited Create;
FLongName := longName;
FShortForm := shortForm;
end; { CLPLongNameAttribute.Create }
{ CLPDefaultAttribute }
constructor CLPDefaultAttribute.Create(const value: string);
begin
inherited Create;
FDefaultValue := value;
end; { CLPDefaultAttribute.Create }
{ CLPDescriptionAttribute }
constructor CLPDescriptionAttribute.Create(const description: string; const paramName: string);
begin
inherited Create;
FDescription := description;
if paramName <> '' then
FParamName := paramName
else
FParamName := DefaultValue;
end; { CLPDescriptionAttribute.Create }
{ CLPPositionAttribute }
constructor CLPPositionAttribute.Create(position: integer);
begin
inherited Create;
FPosition := position;
end; { CLPPositionAttribute.Create }
{ TCLPLongName }
constructor TCLPLongName.Create(const ALongForm, AShortForm: string);
begin
LongForm := ALongForm;
ShortForm := AShortForm;
end; { TCLPLongName.Create }
{ TSwitchData }
constructor TSwitchData.Create(instance: TObject; const propertyName, name: string; const
longNames: TCLPLongNames; switchType: TCLPSwitchType; position: integer; options:
TCLPSwitchOptions; const defaultValue, description, paramName: string);
begin
inherited Create;
FInstance := instance;
FPropertyName := propertyName;
FName := name;
FLongNames := longNames;
FShortLongForm := shortLongForm;
FSwitchType := switchType;
FPosition := position;
FOptions := options;
FDefaultValue := defaultValue;
FDescription := description;
FParamDesc := paramName;
end; { TSwitchData.Create }
function TSwitchData.AppendValue(const value, delim: string; doQuote: boolean): boolean;
var
s: string;
begin
s := GetValue;
if s <> '' then
s := s + delim;
if doQuote then
s := s + Quote(value)
else
s := s + value;
Result := SetValue(s);
end; { TSwitchData.AppendValue }
procedure TSwitchData.Enable;
var
ctx : TRttiContext;
prop: TRttiProperty;
typ : TRttiType;
begin
if SwitchType <> stBoolean then
raise Exception.Create('TSwitchData.Enable: Not supported');
ctx := TRttiContext.Create;
typ := ctx.GetType(FInstance.ClassType);
prop := typ.GetProperty(FPropertyName);
prop.SetValue(FInstance, true);
FProvided := true;
end; { TSwitchData.Enable }
function TSwitchData.GetValue: string;
var
ctx : TRttiContext;
prop: TRttiProperty;
typ : TRttiType;
begin
ctx := TRttiContext.Create;
typ := ctx.GetType(FInstance.ClassType);
prop := typ.GetProperty(FPropertyName);
Result := prop.GetValue(FInstance).AsString;
end; { TSwitchData.GetValue }
function TSwitchData.Quote(const value: string): string;
begin
if (Pos(' ', value) > 0) or (Pos('"', value) > 0) then
Result := '"' + StringReplace(value, '"', '""', [rfReplaceAll]) + '"'
else
Result := value;
end; { TSwitchData.Quote }
function TSwitchData.SetValue(const value: string): boolean;
var
c : integer;
ctx : TRttiContext;
iValue: integer;
prop : TRttiProperty;
typ : TRttiType;
begin
Result := true;
ctx := TRttiContext.Create;
typ := ctx.GetType(FInstance.ClassType);
prop := typ.GetProperty(FPropertyName);
case SwitchType of
stString:
prop.SetValue(FInstance, value);
stInteger:
begin
Val(value, iValue, c);
if c <> 0 then
Exit(false);
prop.SetValue(FInstance, iValue);
end;
else
raise Exception.Create('TSwitchData.SetValue: Not supported');
end;
FProvided := true;
end; { TSwitchData.SetValue }
{ TGpCommandLineParser }
constructor TGpCommandLineParser.Create;
begin
inherited Create;
FSwitchList := TObjectList<TSwitchData>.Create;
FSwitchComparer := TIStringComparer.Ordinal; //don't destroy, Ordinal returns a global singleton
FSwitchDict := TDictionary<string,TSwitchData>.Create(FSwitchComparer);
end; { TGpCommandLineParser.Create }
destructor TGpCommandLineParser.Destroy;
begin
FreeAndNil(FSwitchDict);
FreeAndNil(FSwitchList);
inherited Destroy;
end; { TGpCommandLineParser.Destroy }
procedure TGpCommandLineParser.AddSwitch(instance: TObject; const propertyName, name:
string; const longNames: TCLPLongNames; switchType: TCLPSwitchType; position: integer;
options: TCLPSwitchOptions; const defaultValue, description, paramName: string);
var
data : TSwitchData;
i : integer;
longName: TCLPLongName;
begin
data := TSwitchData.Create(instance, propertyName, name, longNames, switchType,
position, options, defaultValue, description, paramName);
FSwitchList.Add(data);
if name <> '' then
FSwitchDict.Add(name, data);
for longName in longNames do begin
FSwitchDict.Add(longName.LongForm, data);
if longName.ShortForm <> '' then begin
for i := Length(longName.ShortForm) to Length(longName.LongForm) - 1 do
FSwitchDict.AddOrSetValue(Copy(longName.LongForm, 1, i), data);
end;
end;
end; { TGpCommandLineParser.AddSwitch }
/// <summary>
/// Verifies attribute consistency.
///
/// For positional attributes there must be no 'holes' (i.e. positional attributes must
/// be numbere 1,2,...N) and there must be no 'required' attributes after 'optional'
/// attributes.
///
/// There must be at most one 'Rest' positional attribute.
///
/// Each switch attribute must have a long or short name. (That is actually enforced in
/// in the current implementation as long name is set to property name by default,
/// but the test is still left in for future proofing.)
///
/// Short names (when provided) must be one letter long.
///
/// At the same time creates an array of references to positional attributes,
/// FPositionals.
/// </summary>
function TGpCommandLineParser.CheckAttributes: boolean;
var
data : TSwitchData;
hasOptional : boolean;
highPos : integer;
i : integer;
longName : TCLPLongName;
positionRest: TSwitchData;
begin
Result := true;
highPos := 0;
hasOptional := false;
positionRest := nil;
for data in FSwitchList do
if soPositional in data.Options then begin
if soPositionRest in data.Options then begin
if assigned(positionRest) then
Exit(SetError(ekPositionalsBadlyDefined, edExtraCLPPositionRest, SOnlyOneCLPPositionRestPropertyIs, 0, data.PropertyName))
else if data.SwitchType <> stString then
Exit(SetError(ekPositionalsBadlyDefined, edCLPPositionRestNotString, STypeOfACLPPositionRestPropertyMu, 0, data.PropertyName))
else
positionRest := data;
end
else begin
if data.Position <= 0 then
Exit(SetError(ekPositionalsBadlyDefined, edPositionNotPositive, SPositionMustBeGreaterOrEqualTo1, data.Position))
else if data.Position > highPos then
highPos := data.Position;
end;
if not (soRequired in data.Options) then
hasOptional := false
else if hasOptional then
Exit(SetError(ekPositionalsBadlyDefined, edRequiredAfterOptional, SRequiredPositionalParametersMust, data.Position));
end;
if assigned(positionRest) then begin
Inc(highPos);
positionRest.Position := highPos;
end;
if highPos = 0 then
Exit(true);
SetLength(FPositionals, highPos);
for i := Low(FPositionals) to High(FPositionals) do
FPositionals[i] := nil;
for data in FSwitchList do
if soPositional in data.Options then
FPositionals[data.Position-1] := data;
for i := Low(FPositionals) to High(FPositionals) do
if FPositionals[i] = nil then
Exit(SetError(ekPositionalsBadlyDefined, edMissingPositionalDefinition, SMissingPositionalParameterDefini, i+1));
for data in FSwitchList do
if not (soPositional in data.Options) then
if (data.Name = '') and (Length(data.LongNames) = 0) then
Exit(SetError(ekNameNotDefined, edMissingNameForProperty, SMissingNameForProperty, 0, data.PropertyName))
else if (data.Name <> '') and (Length(data.Name) <> 1) then
Exit(SetError(ekShortNameTooLong, edShortNameTooLong, SShortNameMustBeOneLetterLong, 0, data.Name))
else for longName in data.LongNames do
if (longName.ShortForm <> '') and (not StartsText(longName.ShortForm, longName.LongForm)) then
Exit(SetError(ekLongFormsDontMatch, edLongFormsDontMatch, SLongFormsDontMatch, 0, longName.LongForm));
end; { TGpCommandLineParser.CheckAttributes }
function TGpCommandLineParser.FindExtendableSwitch(const el: string; var param: string;
var data: TSwitchData): boolean;
var
kv: TPair<string, TSwitchData>;
begin
Result := false;
for kv in FSwitchDict do begin
if el.StartsWith(kv.Key, true) then begin
data := kv.Value;
param := el;
Delete(param, 1, Length(kv.Key));
Exit(true);
end;
end;
end; { TGpCommandLineParser.FindExtendableSwitch }
function TGpCommandLineParser.GetCommandLine: string;
var
i: integer;
begin
Result := '';
for i := 1 to ParamCount do begin
if i > 1 then
Result := Result + ' ';
if Pos(' ', ParamStr(i)) > 0 then
Result := Result + '"' + ParamStr(i) + '"'
else
Result := Result + ParamStr(i);
end;
end; { TGpCommandLineParser.GetCommandLine }
function TGpCommandLineParser.GetErrorInfo: TCLPErrorInfo;
begin
Result := FErrorInfo;
end; { TGpCommandLineParser.GetErrorInfo }
function TGpCommandLineParser.GetExtension(const switch: string): string;
var
data: TSwitchData;
begin
if not FSwitchDict.TryGetValue(switch, data) then
raise Exception.CreateFmt('Switch %s is not defined', [switch]);
if not (soExtendable in data.Options) then
raise Exception.CreateFmt('Switch %s is not extendable', [switch]);
Result := data.ParamValue;
end; { TGpCommandLineParser.GetExtension }
function TGpCommandLineParser.GetOptions: TCLPOptions;
begin
Result := FOptions;
end; { TGpCommandLineParser.GetOptions }
function TGpCommandLineParser.GrabNextElement(var s, el: string): boolean;
var
p: integer;
begin
el := '';
s := TrimLeft(s);
if s = '' then
Exit(false);
if s[1] = '"' then begin
repeat
p := PosEx('"', s, 2);
if p <= 0 then //unterminated quote
p := Length(s);
el := el + Copy(s, 1, p);
Delete(s, 1, p);
until (s = '') or (s[1] <> '"');
Delete(el, 1, 1);
if el[Length(el)] = '"' then
Delete(el, Length(el), 1);
el := StringReplace(el, '""', '"', [rfReplaceAll]);
end
else begin
p := Pos(' ', s);
if p <= 0 then //last element
p := Length(s) + 1;
el := Copy(s, 1, p-1);
Delete(s, 1, p);
end;
Result := true;
end; { TGpCommandLineParser.GrabNextElement }
function TGpCommandLineParser.IsSwitch(const el: string; var param: string;
var data: TSwitchData): boolean;
var
delimPos: integer;
minPos : integer;
name : string;
pd : char;
sd : string;
trimEl : string;
begin
Result := false;
param := '';
trimEl := el;
for sd in FSwitchDelims do
if StartsStr(sd, trimEl) then begin
trimEl := el;
Delete(trimEl, 1, Length(sd));
if trimEl <> '' then
Result := true;
break; //for sd
end;
if Result then begin //try to extract parameter data
name := trimEl;
minPos := 0;
for pd in FParamDelims do begin
delimPos := Pos(pd, name);
if (delimPos > 0) and ((minPos = 0) or (delimPos < minPos)) then
minPos := delimPos;
end;
if minPos > 0 then begin
param := name;
Delete(param, 1, minPos);
name := Copy(name, 1, minPos - 1);
end;
FSwitchDict.TryGetValue(name, data);
if not assigned(data) then //try extendable switches
FindExtendableSwitch(name, param, data);
if not assigned(data) then begin //try short name
if FSwitchDict.TryGetValue(trimEl[1], data) then begin
param := trimEl;
Delete(param, 1, 1);
if (param <> '') and (data.SwitchType = stBoolean) then //misdetection, boolean switch cannot accept data
data := nil;
end;
end;
end;
end; { TGpCommandLineParser.IsSwitch }
function TGpCommandLineParser.MapPropertyType(const prop: TRttiProperty): TCLPSwitchType;
begin
case prop.PropertyType.TypeKind of
tkInteger, tkInt64:
Result := stInteger;
tkEnumeration:
if prop.PropertyType.Handle = TypeInfo(Boolean) then
Result := stBoolean
else
raise Exception.CreateFmt(SUnsupportedPropertyType, [prop.Name]);
tkString, tkLString, tkWString, tkUString:
Result := stString;
else
raise Exception.CreateFmt(SUnsupportedPropertyType, [prop.Name]);
end;
end; { TGpCommandLineParser.MapPropertyType }
function TGpCommandLineParser.Parse(const commandLine: string; commandData: TObject): boolean;
begin
FSwitchDict.Clear;
SetLength(FPositionals, 0);
FSwitchList.Clear;
ProcessDefinitionClass(commandData);
Result := CheckAttributes;
if not Result then
raise ECLPConfigurationError.Create(ErrorInfo)
else
Result := ProcessCommandLine(commandData, commandLine);
end; { TGpCommandLineParser.Parse }
function TGpCommandLineParser.Parse(commandData: TObject): boolean;
begin
Result := Parse(GetCommandLine, commandData);
end; { TGpCommandLineParser.Parse }
procedure TGpCommandLineParser.ProcessAttributes(instance: TObject; const prop: TRttiProperty);
var
attr : TCustomAttribute;
default : string;
description: string;
longNames : TCLPLongNames;
name : string;
options : TCLPSwitchOptions;
paramName : string;
position : integer;
procedure AddLongName(const longForm, shortForm: string);
begin
SetLength(longNames, Length(longNames) + 1);
longNames[High(longNames)] := TCLPLongName.Create(longForm, shortForm);
end; { AddLongName }
begin { TGpCommandLineParser.ProcessAttributes }
name := '';
description := '';
paramName := CLPDescriptionAttribute.DefaultValue;
options := [];
position := 0;
SetLength(longNames, 0);
for attr in prop.GetAttributes do begin
if attr is CLPNameAttribute then
name := CLPNameAttribute(attr).Name
else if attr is CLPLongNameAttribute then begin
AddLongName(CLPLongNameAttribute(attr).LongName,
CLPLongNameAttribute(attr).ShortForm);
end
else if attr is CLPDefaultAttribute then
default := CLPDefaultAttribute(attr).DefaultValue
else if attr is CLPDescriptionAttribute then begin
description := CLPDescriptionAttribute(attr).Description;
paramName := CLPDescriptionAttribute(attr).paramName;
end
else if attr is CLPRequiredAttribute then
Include(options, soRequired)
else if attr is CLPExtendableAttribute then
Include(options, soExtendable)
else if attr is CLPPositionAttribute then begin
position := CLPPositionAttribute(attr).Position;
Include(options, soPositional);
end
else if attr is CLPPositionRestAttribute then begin
Include(options, soPositional);
Include(options, soPositionRest);
end;
end; //for attr
if (Length(longNames) = 0) and (not SameText(prop.Name, Trim(name))) then
AddLongName(prop.Name, '');
AddSwitch(instance, prop.Name, Trim(name), longNames, MapPropertyType(prop), position,
options, default, Trim(description), Trim(paramName));
end; { TGpCommandLineParser.ProcessAttributes }
function TGpCommandLineParser.ProcessCommandLine(commandData: TObject;
const commandLine: string): boolean;
var
data : TSwitchData;
el : string;
param : string;
position: integer;
s : string;
begin
Result := true;
for data in FSwitchList do
if data.DefaultValue <> '' then
data.SetValue(data.DefaultValue);
position := 1;
s := commandLine;
while GrabNextElement(s, el) do begin
if IsSwitch(el, param, data) then begin
if not assigned(data) then
if opIgnoreUnknownSwitches in FOptions then
continue //while
else
Exit(SetError(ekUnknownNamed, edUnknownSwitch, SUnknownSwitch, 0, el));
if data.SwitchType = stBoolean then begin
if (param = '') or (soExtendable in data.Options) then begin
data.Enable;
if param <> '' then
data.ParamValue := param;
end
else
Exit(SetError(ekInvalidData, edBooleanWithData, SBooleanSwitchCannotAcceptData, 0, el));
end
else if param <> '' then
if not data.SetValue(param) then
Exit(SetError(ekInvalidData, edInvalidDataForSwitch, SInvalidDataForSwitch, 0, el));
end
else begin
if (position-1) > High(FPositionals) then
Exit(SetError(ekExtraPositional, edTooManyPositionalArguments, STooManyPositionalArguments, 0, el));
data := FPositionals[position-1];
if soPositionRest in data.Options then begin
if not data.AppendValue(el, #13, false) then
Exit(SetError(ekInvalidData, edInvalidDataForSwitch, SInvalidDataForSwitch, 0, el));
end
else begin
if not data.SetValue(el) then
Exit(SetError(ekInvalidData, edInvalidDataForSwitch, SInvalidDataForSwitch, 0, el));
Inc(position);
end;
end;
end; //while s <> ''
for data in FPositionals do
if (soRequired in data.Options) and (not data.Provided) then
Exit(SetError(ekMissingPositional, edMissingRequiredParameter, SRequiredParameterWasNotProvided, data.Position, data.LongNames[0].LongForm));
for data in FSwitchlist do
if (soRequired in data.Options) and (not data.Provided) then
Exit(SetError(ekMissingNamed, edMissingRequiredSwitch, SRequiredSwitchWasNotProvided, 0, data.LongNames[0].LongForm));
end; { TGpCommandLineParser.ProcessCommandLine }
procedure TGpCommandLineParser.ProcessDefinitionClass(commandData: TObject);
var
ctx : TRttiContext;
prop: TRttiProperty;
typ : TRttiType;
begin
ctx := TRttiContext.Create;
typ := ctx.GetType(commandData.ClassType);
for prop in typ.GetProperties do
if prop.Parent = typ then
ProcessAttributes(commandData, prop);
end; { TGpCommandLineParser.ProcessDefinitionClass }
function TGpCommandLineParser.SetError(kind: TCLPErrorKind; detail: TCLPErrorDetailed;
const text: string; position: integer; switchName: string): boolean;
begin
FErrorInfo.Kind := kind;
FErrorInfo.Detailed := detail;
FErrorInfo.Text := text;
FErrorInfo.Position := position;
FErrorInfo.SwitchName := switchName;
FErrorInfo.IsError := true;
Result := false;
end; { TGpCommandLineParser.SetError }
procedure TGpCommandLineParser.SetOptions(const value: TCLPOptions);