forked from exilon/QuickLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick.Parameters.pas
705 lines (631 loc) · 20.2 KB
/
Quick.Parameters.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
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Parameters
Description : Map comandline to class
Author : Kike Pérez
Version : 1.4
Created : 12/07/2020
Modified : 29/07/2020
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Parameters;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
StrUtils,
Generics.Collections,
Quick.Commons,
{$IFDEF CONSOLE}
Quick.Console,
{$ENDIF}
rtti,
TypInfo,
Quick.RTTI.Utils;
type
CommandDescription = class(TCustomAttribute)
private
fDescription : string;
public
constructor Create(const aDescription : string);
property Description : string read fDescription;
end;
ParamCommand = class(TCustomAttribute)
private
fPosition : Integer;
public
constructor Create(aPosition : Integer);
property Position : Integer read fPosition;
end;
ParamName = class(TCustomAttribute)
private
fName : string;
fAlias : string;
public
constructor Create(const aName: string; const aAlias : string = '');
property Name : string read fName;
property Alias : string read fAlias;
end;
ParamValueIsNextParam = class(TCustomAttribute);
ParamHelp = class(TCustomAttribute)
private
fHelp : string;
fValueName : string;
public
constructor Create(const aHelp : string; const aValueName : string = '');
property Help : string read fHelp;
property ValueName : string read fValueName;
end;
ParamSwitchChar = class(TCustomAttribute)
private
fSwithChar : string;
public
constructor Create(const aSwitchChar : string);
property SwitchChar : string read fSwithChar write fSwithChar;
end;
ParamValueSeparator = class(TCustomAttribute)
private
fValueSeparator : string;
public
constructor Create(const aValueSeparator : string);
property ValueSeparator : string read fValueSeparator write fValueSeparator;
end;
ParamRequired = class(TCustomAttribute);
{$IFDEF CONSOLE}
TColorizeHelp = class
private
fCommandName : TConsoleColor;
fCommandDescription : TConsoleColor;
fCommandUsage : TConsoleColor;
fSections : TConsoleColor;
fArgumentName : TConsoleColor;
fArgumentDescription : TConsoleColor;
public
property CommandName : TConsoleColor read fCommandName write fCommandName;
property CommandDescription : TConsoleColor read fCommandDescription write fCommandDescription;
property CommandUsage : TConsoleColor read fCommandUsage write fCommandUsage;
property Sections : TConsoleColor read fSections write fSections;
property ArgumentName : TConsoleColor read fArgumentName write fArgumentName;
property ArgumentDescription : TConsoleColor read fArgumentDescription write fArgumentDescription;
end;
{$ENDIF}
TParameters = class
type
TValueType = (vtString, vtInteger, vtFloat, vtBoolean, vtEnumeration);
TParam = class
private
fName : string;
fAlias : string;
fValue : string;
fPrecisePosition : Integer;
fParamType: TValueType;
fRequired : Boolean;
fHelp : string;
fValueName : string;
fValueIsNextParam: Boolean;
fSwitchChar: string;
fValueSeparator: string;
fIsPresent: Boolean;
public
constructor Create;
property Name : string read fName write fName;
property Alias : string read fAlias write fAlias;
property Value : string read fValue write fValue;
property PrecisePosition : Integer read fPrecisePosition write fPrecisePosition;
property ParamType : TValueType read fParamType write fParamType;
property Required : Boolean read fRequired write fRequired;
property SwitchChar : string read fSwitchChar write fSwitchChar;
property ValueSeparator : string read fValueSeparator write fValueSeparator;
property Help : string read fHelp write fHelp;
property HepValueName : string read fValueName write fValueName;
property ValueIsNextParam : Boolean read fValueIsNextParam write fValueIsNextParam;
property IsPresent : Boolean read fIsPresent write fIsPresent;
function IsSwitch : Boolean;
function IsCommand : Boolean;
end;
private
fParams : TObjectList<TParam>;
fDescription : string;
fHelp: Boolean;
{$IFDEF CONSOLE}
fColorizeHelp: TColorizeHelp;
{$ENDIF}
function ExistParam(aParameter : TParam; const aParam : string) : Boolean;
function GetParamName(aParameter : TParam; const aParam : string) : string;
function GetParamValue(aParameter : TParam; const aParam : string) : string;
function ValueType(const aProp : TRttiProperty) : TValueType;
procedure ParseParams;
function CheckHelpSwitch : Boolean;
protected
{$IFDEF CONSOLE}
procedure GetColors; virtual;
{$ENDIF}
procedure Validate; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
property Description : string read fDescription write fDescription;
{$IFDEF CONSOLE}
property ColorizeHelp : TColorizeHelp read fColorizeHelp write fColorizeHelp;
procedure ShowHelp; virtual;
{$ENDIF}
function GetHelp : TStringList;
property Help : Boolean read fHelp write fHelp;
end;
TServiceParameters = class(TParameters)
private
fInstance : string;
fInstall : Boolean;
fRemove : Boolean;
fConsole : Boolean;
published
[ParamHelp('Install service with a custom name','Service name')]
property Instance : string read fInstance write fInstance;
[ParamHelp('Install as a service')]
property Install : Boolean read fInstall write fInstall;
[ParamHelp('Remove service')]
property &Remove : Boolean read fRemove write fRemove;
[ParamHelp('Force run as a console application (when runned from another service)')]
property Console : Boolean read fConsole write fConsole;
end;
ENotValidCommandlineParameter = class(Exception);
ERequiredParameterNotFound = class(Exception);
EParameterValueNotFound = class(Exception);
EParamValueNotSupported = class(Exception);
implementation
{ TParameter }
constructor TParameters.Create;
begin
{$IFDEF CONSOLE}
fColorizeHelp := TColorizeHelp.Create;
GetColors;
{$ENDIF}
fParams := TObjectList<TParam>.Create(True);
ParseParams;
{$IFDEF CONSOLE}
if fHelp then
begin
ShowHelp;
Halt;
end;
{$ENDIF}
Validate;
end;
destructor TParameters.Destroy;
begin
fParams.Free;
{$IFDEF CONSOLE}
fColorizeHelp.Free;
{$ENDIF}
inherited;
end;
function TParameters.ExistParam(aParameter : TParam; const aParam : string) : Boolean;
var
i : Integer;
parName : string;
begin
Result := False;
if aParam.IsEmpty then Exit;
for i := 1 to ParamCount do
begin
parName := ParamStr(i);
if parName = aParameter.ValueSeparator then raise ENotValidCommandlineParameter.CreateFmt('Not valid commandline "%s"', [parName]);
parName := GetParamName(aParameter,ParamStr(i));
if CompareText(parName,aParam) = 0 then Exit(True);
end;
end;
function TParameters.GetParamName(aParameter : TParam; const aParam : string) : string;
var
switch : string;
begin
if CompareText(aParam,'-' + aParameter.Alias) = 0 then switch := '-'
else switch := aParameter.SwitchChar;
if aParam.StartsWith(switch) then Result := aParam.Substring(switch.Length);
if Result.Contains(aParameter.ValueSeparator) then Result := Result.Substring(0,Result.IndexOf(aParameter.ValueSeparator));
end;
function TParameters.GetParamValue(aParameter : TParam; const aParam : string) : string;
var
i : Integer;
parName : string;
param : string;
begin
Result := '';
for i := 1 to ParamCount do
begin
param := ParamStr(i);
parName := GetParamName(aParameter,param);
if CompareText(parName,aParam) = 0 then
begin
if aParameter.ValueIsNextParam then
begin
if i < ParamCount then Result := ParamStr(i+1);
end
else
begin
if param.Contains(aParameter.ValueSeparator) then Result := param.Substring(param.IndexOf(aParameter.ValueSeparator)+(aParameter.ValueSeparator.Length));
end;
Exit;
end;
end;
end;
function TParameters.CheckHelpSwitch: Boolean;
var
param : TParam;
begin
param := TParam.Create;
param.Name := 'help';
param.Alias := 'h';
try
Result := ExistParam(param,param.Name);
finally
param.Free;
end;
end;
procedure TParameters.ParseParams;
var
param : TParam;
value : TValue;
valueint : Int64;
valuefloat : Extended;
rType : TRttiType;
rProp : TRttiProperty;
attr : TCustomAttribute;
pinfo : PTypeInfo;
found : Boolean;
begin
fHelp := CheckHelpSwitch;
rType := TRTTI.GetType(Self.ClassInfo);
//get main info
for attr in rType.GetAttributes do
begin
if attr is CommandDescription then Self.Description := CommandDescription(attr).Description;
end;
//get parameters
for rProp in TRTTI.GetProperties(rType,TRttiPropertyOrder.roFirstBase) do
begin
if rProp.Visibility <> TMemberVisibility.mvPublished then continue;
param := TParam.Create;
fParams.Add(param);
param.Name := rProp.Name;
for attr in rProp.GetAttributes do
begin
if attr is ParamHelp then
begin
param.Help := ParamHelp(attr).Help;
param.HepValueName := ParamHelp(attr).ValueName;
end;
if attr is ParamName then
begin
param.Name := ParamName(attr).Name;
param.Alias := ParamName(attr).Alias;
end;
if attr is ParamCommand then param.PrecisePosition := ParamCommand(attr).Position;
if attr is ParamRequired then param.Required := True;
if attr is ParamSwitchChar then param.SwitchChar := ParamSwitchChar(attr).SwitchChar;
if attr is ParamValueSeparator then param.ValueSeparator := ParamValueSeparator(attr).ValueSeparator;
if attr is ParamValueIsNextParam then param.ValueIsNextParam := True;
end;
param.ParamType := ValueType(rProp);
if param.IsCommand then
begin
found := ParamCount >= param.PrecisePosition;
param.SwitchChar := ' ';
end
else found := (ExistParam(param,param.Name)) or (ExistParam(param,param.Alias));
value := nil;
if found then
begin
if param.IsSwitch then
begin
value := True;
end
else
begin
if param.IsCommand then param.Value := ParamStr(param.PrecisePosition)
else param.Value := GetParamValue(param,param.Name);
if (param.Value.IsEmpty) and (not param.Alias.IsEmpty) then param.Value := GetParamValue(param,param.Alias);
if (not param.Value.IsEmpty) and (not fHelp) then
case param.ParamType of
TValueType.vtString :
begin
value := param.Value;
end;
TValueType.vtInteger :
begin
if not TryStrToInt64(param.Value,valueint) then raise EParamValueNotSupported.CreateFmt('Parameter "%s" needs a numeric value',[param.Name]);
value := valueint;
end;
TValueType.vtFloat :
begin
if not TryStrToFloat(param.Value,valuefloat) then raise EParamValueNotSupported.CreateFmt('Parameter "%s" needs a float value',[param.Name]);
value := valuefloat;
end;
TValueType.vtEnumeration :
begin
pinfo := TRTTI.GetPropertyValue(Self,param.Name).TypeInfo;
if not IsInteger(param.Value) then TValue.Make(GetEnumValue(pinfo,param.Value),pinfo,value)
else TValue.Make(StrToInt(param.Value),pinfo,value);
end;
end;
end;
param.IsPresent := True;
if not value.IsEmpty then rProp.SetValue(Self,value);
end;
end;
//add help
param := TParam.Create;
param.Name := 'Help';
param.Alias := 'h';
param.ParamType := TValueType.vtBoolean;
param.Help := 'Show this documentation';
fParams.Add(param);
end;
procedure TParameters.Validate;
var
param : TParam;
begin
if help then Exit;
for param in fParams do
begin
if param.IsPresent then
begin
if (not param.IsSwitch) and (param.Value.IsEmpty) then raise EParamValueNotSupported.CreateFmt('Value for parameter "%s" not specified',[param.Name]);
end
else
begin
if param.Required then raise ERequiredParameterNotFound.CreateFmt('Required parameter "%s" not found',[param.Name]);
end;
end;
end;
function TParameters.ValueType(const aProp: TRttiProperty): TValueType;
var
rType : TRttiType;
begin
rType := aProp.PropertyType;
case rType.TypeKind of
tkString, tkWideString, tkChar, tkUnicodeString : Result := TValueType.vtString;
tkInteger, tkInt64 : Result := TValueType.vtInteger;
tkFloat : Result := TValueType.vtFloat;
tkEnumeration :
begin
if TRTTI.GetPropertyValue(Self,aProp.Name).TypeInfo = System.TypeInfo(Boolean) then Result := TValueType.vtBoolean
else Result := TValueType.vtEnumeration;
end;
else raise EParamValueNotSupported.CreateFmt('Parameter "%s": Value not supported',[aProp.Name]);
end;
end;
{$IFDEF CONSOLE}
procedure TParameters.ShowHelp;
var
version : string;
arg : string;
value : string;
usage : string;
commands : string;
param : TParam;
maxlen : Integer;
arglen : Integer;
begin
//show app and version
version := GetAppVersionStr;
if version.IsEmpty then cout(GetAppName,fColorizeHelp.CommandName)
else cout(Format('%s v.%s',[GetAppName,GetAppVersionStr]),fColorizeHelp.CommandName);
usage := '';
maxlen := 0;
commands := '';
//show usage
arglen := 0;
for param in fParams do
begin
if (param.Name.Length + param.Alias.Length) > maxlen then maxlen := param.Name.Length + param.Alias.Length;
if param.Required then arg := '<' + param.SwitchChar + param.Name +'%s>'
else arg := '[' + param.SwitchChar + param.Name + '%s]';
if param.IsSwitch then
begin
arg := Format(arg,['']);
end
else if param.IsCommand then
begin
if param.HepValueName.IsEmpty then value := param.Name
else value := param.HepValueName;
if param.Required then commands := commands + Format('<%s> ',[value])
else commands := commands + Format('[%s] ',[value]);
Continue;
end
else
begin
if param.ValueIsNextParam then value := ' <value>'
else value := param.ValueSeparator + '<value>';
if not param.HepValueName.IsEmpty then value := StringReplace(value,'value',param.HepValueName,[rfIgnoreCase,rfReplaceAll]);
arg := Format(arg,[value]);
end;
//fit usage line
arglen := arglen + arg.Length;
if arglen > 80 then
begin
usage := usage + #10 + FillStr(' ',8 + (GetAppName.Length));
arglen := arg.Length;
end;
usage := usage + arg + ' ';
end;
maxlen := maxlen + 5;
coutSL('Usage: ',fColorizeHelp.Sections);
coutSL(Format('%s %s%s',[GetAppName,commands,usage]),fColorizeHelp.CommandUsage);
cout('',ccWhite);
cout('',ccWhite);
//show description
cout(Description,fColorizeHelp.CommandDescription);
cout('',ccWhite);
//show arguments
cout('Arguments:',fColorizeHelp.Sections);
cout('',ccWhite);
for param in fParams do
begin
//if param.IsCommand then Continue;
if param.Alias.IsEmpty then
begin
coutSL(Format(' %s%s%s',[param.SwitchChar,param.Name,FillStr(' ',maxlen - param.Name.Length)]),fColorizeHelp.ArgumentName);
end
else
begin
coutSL(Format(' %s%s, -%s%s',[param.SwitchChar,param.Name,param.Alias,FillStr(' ',maxlen - (param.Name.Length + param.Alias.Length + 3))]),fColorizeHelp.ArgumentName);
end;
coutSL(param.Help,fColorizeHelp.ArgumentDescription);
cout('',ccWhite);
end;
cout('',ccWhite);
end;
procedure TParameters.GetColors;
begin
fColorizeHelp.CommandName := ccLightCyan;
fColorizeHelp.CommandDescription := ccDarkGray;
fColorizeHelp.CommandUsage := ccLightGray;
fColorizeHelp.fSections := ccWhite;
fColorizeHelp.ArgumentName := ccWhite;
fColorizeHelp.ArgumentDescription := ccLightGray;
end;
{$ENDIF}
function TParameters.GetHelp : TStringList;
var
line : string;
version : string;
arg : string;
value : string;
usage : string;
commands : string;
param : TParam;
maxlen : Integer;
arglen : Integer;
begin
Result := TStringList.Create;
line := '';
//show app and version
version := GetAppVersionStr;
if version.IsEmpty then Result.Add(GetAppName)
else Result.Add(Format('%s v.%s',[GetAppName,GetAppVersionStr]));
usage := '';
maxlen := 0;
commands := '';
//show usage
arglen := 0;
for param in fParams do
begin
if (param.Name.Length + param.Alias.Length) > maxlen then maxlen := param.Name.Length + param.Alias.Length;
if param.Required then arg := '<' + param.SwitchChar + param.Name +'%s>'
else arg := '[' + param.SwitchChar + param.Name + '%s]';
if param.IsSwitch then
begin
arg := Format(arg,['']);
end
else if param.IsCommand then
begin
if param.HepValueName.IsEmpty then value := param.Name
else value := param.HepValueName;
if param.Required then commands := commands + Format('<%s> ',[value])
else commands := commands + Format('[%s] ',[value]);
Continue;
end
else
begin
if param.ValueIsNextParam then value := ' <value>'
else value := param.ValueSeparator + '<value>';
if not param.HepValueName.IsEmpty then value := StringReplace(value,'value',param.HepValueName,[rfIgnoreCase,rfReplaceAll]);
arg := Format(arg,[value]);
end;
//fit usage line
arglen := arglen + arg.Length;
if arglen > 80 then
begin
usage := usage + #10 + FillStr(' ',8 + (GetAppName.Length));
arglen := arg.Length;
end;
usage := usage + arg + ' ';
end;
maxlen := maxlen + 5;
Result.Add(Format('Usage: %s %s%s',[GetAppName,commands,usage]));
Result.Add('');
Result.Add('');
//show description
Result.Add(Description);
Result.Add('');
//show arguments
Result.Add('Arguments:');
Result.Add('');
for param in fParams do
begin
//if param.IsCommand then Continue;
line := '';
if param.Alias.IsEmpty then
begin
line := line + Format(' %s%s%s',[param.SwitchChar,param.Name,FillStr(' ',maxlen - param.Name.Length)]);
end
else
begin
line := line + Format(' %s%s, -%s%s',[param.SwitchChar,param.Name,param.Alias,FillStr(' ',maxlen - (param.Name.Length + param.Alias.Length + 3))]);
end;
line := line + param.Help;
Result.Add(line);
Result.Add('');
end;
end;
{ CommandDescription }
constructor CommandDescription.Create(const aDescription: string);
begin
fDescription := aDescription;
end;
{ ParamName }
constructor ParamName.Create(const aName: string; const aAlias : string = '');
begin
fName := aName;
fAlias := aAlias;
end;
{ ParamHelp }
constructor ParamHelp.Create(const aHelp : string; const aValueName : string = '');
begin
fHelp := aHelp;
if not aValueName.IsEmpty then fValueName := aValueName
else fValueName := 'value';
end;
{ TParameters.TParam }
constructor TParameters.TParam.Create;
begin
IsPresent := False;
fSwitchChar := '--';
fValueSeparator := '=';
fPrecisePosition := 0;
end;
function TParameters.TParam.IsCommand: Boolean;
begin
Result := fPrecisePosition > 0;
end;
function TParameters.TParam.IsSwitch: Boolean;
begin
Result := fParamType = TValueType.vtBoolean;
end;
{ ParamSwitchChar }
constructor ParamSwitchChar.Create(const aSwitchChar: string);
begin
fSwithChar := aSwitchChar;
end;
{ ParamValueSeparator }
constructor ParamValueSeparator.Create(const aValueSeparator: string);
begin
fValueSeparator := aValueSeparator;
end;
{ ParamCommand }
constructor ParamCommand.Create(aPosition: Integer);
begin
fPosition := aPosition;
end;
end.