-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathJPL.CmdLineParser.pas
2171 lines (1776 loc) · 63.1 KB
/
JPL.CmdLineParser.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
unit JPL.CmdLineParser;
{
Jacek Pazera
http://www.pazera-software.com
Command line parser - Parser of parameters passed to the program on the command line.
Assumptions: Using as few units as possible. No generics.collections, fgl, etc.
2020.05.02
[+] function GetOptionValues(OptionName: string): TStringDynArray
This functions returns all values for the given option.
User can pass many values for one option, eg.: -f "file 1" -f "file 2" -f "file 3".
GetOptionValue returns value of the last option ("file 3").
GetOptionsValues returns the array of ALL values.
2018.02.28 Removed dependency on JPL.Strings and JP.Utils
2018.01.22
[+] AcceptAllNonOptions: Boolean
If AcceptAllNonOptions = True, all parameters that do not starts with the "-", "/" or "--" will be saved in
the FUnknownParams array, and they will not be treated as errors.
}
{$I .\..\jp.inc}
{$IFDEF FPC}{$MODE OBJFPC}{$H+}{$ENDIF}
{:<@include(..\doc\unit_JP.CmdLineParser.txt)}
interface
// function CommandLineToArgvW(lpCmdLine: LPCWSTR; var pNumArgs: Integer): PPWideChar; stdcall;
// function CommandLineToArgvW; external shell32 name 'CommandLineToArgvW';
// https://msdn.microsoft.com/pl-pl/library/windows/desktop/ms683156(v=vs.85).aspx - GetCommandLine function
// https://msdn.microsoft.com/pl-pl/library/windows/desktop/bb776391(v=vs.85).aspx - CommandLineToArgvW function
// https://msdn.microsoft.com/pl-pl/library/windows/desktop/17w5ykft(v=vs.85).aspx - Parsing C++ Command-Line Arguments
{ TODO : Parsowanie dowolnego łańcucha (nie tylko ParamStr/GetCommandLine)}
{ TODO : Dodać obsługę parametrów typu: -pValue (-p=Value) }// http://docwiki.embarcadero.com/Libraries/Berlin/en/System.SysUtils.FindCmdLineSwitch
{ DONE : Dodać obsługę Sticked Params (opcji "przypiętych" do określonych pozycji)}
{ DONE : Dodać obsługę poleceń (commands) }
{ TODO : Poszukać odpowiednika CommandLineToArgvW dla Linuxa }
// Mandatory arguments to long options are mandatory for short options too.
uses
{$IFDEF MSWINDOWS} Windows, {$ENDIF}
Types, // needed for TStringDynArray
SysUtils;
var
{$IFDEF LINUX}
ENDL: string = #10; //:< End of Line marker. Windows: #13#10 (CRLF), Linux: #10 (LF)
{$ELSE}
ENDL: string = #13#10; //:< End of Line marker. Windows: #13#10 (CRLF), Linux: #10 (LF)
{$ENDIF}
LongOptPrefix: string = '--'; //:< Long option prefix. Default '@--'
EqChar: Char = '='; //:< Option-Value separator. @--option_nameEqCharOption_value
DefaultStopParsingSwitch: string = '--'; //:< Domyślna wartość parametru, po którym przerywana jest analiza dalszych parametrów
ShortOptPrefixes: set of AnsiChar = ['-', '/']; //:< Set of short option prefixes. Default @code('-'), @code('/').
DefaultUsageArgName: string = 'ARG';
type
{$IFDEF DELPHI2009_OR_BELOW}
TArray<T> = array of T;
{$ENDIF}
// IMPORTANT!
// cpmCustom: "-abc=123" after parsing it will be treated as a string
// cpmDelphi: "-abc=123" after parsing it will be treated as a option abc with value = 123
TClpParsingMode = (cpmCustom, cpmDelphi); { TODO: Block the cpmCustom mode on Linux. Currently it works only on Windows. }
{ Does the CommandLineToArgvW equivalent for Linux exists? }
TClpUsageFormat = (cufNone, cufSimple, cufWget);
TArgv = array of string; // TArray<string>; <- Delphi 2009 exception (Why ???)
TClpParamType = (
cptCommand,
cptSticked, // "sticked" parameter to given position
cptNone, // unknown
cptShort, // short option
cptMixedShort, // short_option=value
cptLong, // long option
cptMixedLong, // long option with value
cptInvalid, // eg. --=
cptStopMarker, // default '--' : Stop parsing options (like 7z.exe). Rar uses one dash: '-'.
cptString //< "some value" OR "-abc=value" when cpmCustom parsing mode is enabled (Windows only)
);
TClpValueType = (cvtNone, cvtRequired, cvtOptional);
TClpOptionType = (cotNone, cotShort, cotLong, cotBoth);
TClpCommand = record
ShortName: string;
LongName: string;
UsageInfo: string;
Hidden: Boolean;
end;
TClpStickedParam = record
Position: integer;
ParamValue: string;
UsageName: string;
UsageInfo: string;
end;
TClpUnknownParam = record
ParamStr: string;
Index: integer;
end;
TClpParam = record
ParamStr: string;
OptionName: string;
OptionValue: string;
ParamType: TClpParamType;
Index: integer;
Parsed: Boolean;
end;
TClpOption = record
ShortName: string;
LongName: string;
Value: string;
ValueType: TClpValueType;
OptionType: TClpOptionType;
IsOptionNeeded: Boolean;
Exists: Boolean;
Parsed: Boolean;
Hidden: Boolean;
UsageInfo: string;
UsageArgName: string;
UsageCategory: string;
end;
TClpError = record
Param: string;
ErrorMsg: string;
Index: integer;
end;
TClpOptionExtraInfo = record
OptionName: string;
LeftPadding: integer;
InfoStr: string;
end;
{$REGION ' --- TJPCmdLineParser --- '}
TJPCmdLineParser = class
private
FAcceptAllNonOptions: Boolean;
FRunTimeParamsStr: string;
FRunTimeParams: TArgv;
FRunTimeParamCount: integer;
FErrors: {$IFDEF FPC}specialize{$ENDIF} TArray<TClpError>; // array of TClpError;
CLParams: {$IFDEF FPC}specialize{$ENDIF} TArray<TClpParam>; // wszystkie paramerty przechwycone z linii poleceń
FOptions: {$IFDEF FPC}specialize{$ENDIF} TArray<TClpOption>; // lista zarejestrowanych opcji
FSkippedParams: {$IFDEF FPC}specialize{$ENDIF} TArray<string>; // parametry, które wystąpiły po StopParsingSwitch
FCommands: {$IFDEF FPC}specialize{$ENDIF} TArray<TClpCommand>; // można zarejestrować wiele poleceń (commands), ale tylko jedno może (musi) być podane w linii poleceń
FStickedParams: {$IFDEF FPC}specialize{$ENDIF} TArray<TClpStickedParam>; // parametry przypisane ("przyklejone") do określonej pozycji
FUnknownParams: {$IFDEF FPC}specialize{$ENDIF} TArray<TClpUnknownParam>; // lista nieznanych parametrów
// List of additional information for options. They will be used in the OptionsUsageStr function.
FOptionsExtraInfo: {$IFDEF FPC}specialize{$ENDIF} TArray<TClpOptionExtraInfo>;
FCommandLineParsingMode: TClpParsingMode;
FStopParsingSwitch: string;
FIgnoreCase: Boolean;
FAllowDuplicates: Boolean;
FUsageFormat: TClpUsageFormat;
FCommandPosition: integer;
FCommandValue: string;
procedure ClearArrays;
function GetRunTimeParam(Index: integer): string;
function GetRunTimeParams: string;
procedure FillRunTimeParamsArray;
procedure SetAcceptAllNonOptions(AValue: Boolean);
procedure SetCommandLineParsingMode(const Value: TClpParsingMode);
procedure SetStopParsingSwitch(const Value: string);
function StrToParamType(Param: string): TClpParamType;
procedure Parse_1;
procedure Parse_2;
function IsShortOptPrefix(C: Char): Boolean;
procedure SetIgnoreCase(const Value: Boolean);
function GetError(Index: integer): TClpError;
function GetErrorCount: integer;
procedure LogError(const Param, ErrorMsg: string; const Index: integer);
function GetErrorsStr: string;
function GetOption(Index: integer): TClpOption;
procedure SetAllowDuplicates(const Value: Boolean);
function LongOptionsCount: integer;
function ShortOptionsCount: integer;
procedure SetUsageFormat(const Value: TClpUsageFormat);
function GetSkippedParam(Index: integer): string;
function GetSkippedParamsCount: integer;
procedure FillSkippedParamsArray(const StartIndex: integer);
function GetCommand(Index: integer): TClpCommand;
function GetCommandCount: integer;
function GetStickedParam(Index: integer): TClpStickedParam;
function GetStickedParamCount: integer;
function GetUnknownParam(Index: integer): TClpUnknownParam;
function GetUnknownParamCount: integer;
procedure LogUnknownParam(const ParamStr: string; const ParamIndex: integer);
function GetOptionCount: integer;
function GetParsedParam(Index: integer): TClpParam;
function GetParsedParamCount: integer;
public
constructor Create;
destructor Destroy; override;
procedure ResetAll;
procedure Parse;
function ParamsAsString: string;
// ------------------------------------- OPTIONS ----------------------------------------------
function GetShortOptionIndex(OptionName: string): integer;
function GetLongOptionIndex(OptionName: string): integer;
function GetOptionIndex(const OptionName: string): integer;
function GetShortOptionValue(OptionName: string; NoValueStr: string = ''): string;
function GetLongOptionValue(OptionName: string; NoValueStr: string = ''): string;
function GetOptionValue(const OptionName: string; NoValueStr: string = ''): string;
function GetOptionValues(OptionName: string): TStringDynArray;
function TryGetOptionValueAsBool(
const OptionName: string; out ResultValue: Boolean; TrueStr: string = '1|y|yes'; FalseStr: string = '0|n|no';
IgnoreBoolStrCase: Boolean = True
): Boolean;
function IsShortOptionExists(OptionName: string): Boolean;
function IsLongOptionExists(OptionName: string): Boolean;
function IsOptionExists(OptionName: string): Boolean;
procedure RegisterShortOption(const OptionName: string; ValueType: TClpValueType = cvtNone; IsOptionNeeded: Boolean = False; Hidden: Boolean = False;
UsageInfo: string = ''; UsageArgName: string = ''; UsageCategory: string = '');
procedure RegisterLongOption(const OptionName: string; ValueType: TClpValueType = cvtNone; IsOptionNeeded: Boolean = False; Hidden: Boolean = False;
UsageInfo: string = ''; UsageArgName: string = ''; UsageCategory: string = '');
procedure RegisterOption(ShortName: string; LongName: string = ''; ValueType: TClpValueType = cvtNone; IsOptionNeeded: Boolean = False; Hidden: Boolean = False;
UsageInfo: string = ''; UsageArgName: string = ''; UsageCategory: string = '');
function OptionsAsString: string;
function OptionsUsageStr(Prefix: string = ' '; Category: string = ''; MaxLineLen: integer = 90; OptionsToInfoSep: string = ' '; MaxPadding: integer = 30): string;
// ------------------------------------- COMMANDS ----------------------------------------------------
procedure RegisterCommand(ShortName: string; LongName: string = ''; Position: integer = 1; Hidden: Boolean = False; Description: string = '');
procedure AddCommand(ShortName: string; LongName: string = ''; Hidden: Boolean = False; Description: string = '');
function GetCommandIndex(CommandName: string): integer;
function CommandExists(CommandName: string): Boolean;
function CommandsAsString: string;
function CommandsUsageStr(Prefix: string = ' '; MaxLineLen: integer = 90; CommandToInfoSep: string = ' '; MaxPadding: integer = 30): string;
// --------------------------------------- STICKED PARAMS -------------------------------------------
function GetStickedParamIndex(const ParamPosition: integer): integer;
function StickedParamExists(const ParamPosition: integer): Boolean;
function GetStickedParamValue(const ParamPosition: integer): string;
procedure RegisterStickedParam(const ParamPosition: integer; UsageName: string; UsageInfo: string = '');
function StickedParamsAsString: string;
// ----------------- Additional information for options. Used by the OptionsUsageStr func. -------------------------
function GetOptionExtraInfoIndex(const OptionName: string): integer;
procedure SetOptionExtraInfo(const OptionName, Info: string; Padding: integer = 4);
function TryGetOptionExtraInfo(const OptionName: string; out oei: TClpOptionExtraInfo): Boolean;
property UsageFormat: TClpUsageFormat read FUsageFormat write SetUsageFormat;
// Run time params - parametry przekazane w linii poleceń (not parsed)
property RunTimeParamsStr: string read FRunTimeParamsStr;
property RunTimeParams[Index: integer]: string read GetRunTimeParam;
property RunTimeParamCount: integer read FRunTimeParamCount;
// Parsed params - parametry przetworzone (z wartościami)
property ParsedParamCount: integer read GetParsedParamCount;
property ParsedParam[Index: integer]: TClpParam read GetParsedParam;
property CommandLineParsingMode: TClpParsingMode read FCommandLineParsingMode write SetCommandLineParsingMode;
property StopParsingSwitch: string read FStopParsingSwitch write SetStopParsingSwitch;
property IgnoreCase: Boolean read FIgnoreCase write SetIgnoreCase;
property Errors[Index: integer]: TClpError read GetError;
property ErrorCount: integer read GetErrorCount;
property ErrorsStr: string read GetErrorsStr;
property OptionCount: integer read GetOptionCount;
property Options[Index: integer]: TClpOption read GetOption;
property AllowDuplicates: Boolean read FAllowDuplicates write SetAllowDuplicates;
property SkippedParams[Index: integer]: string read GetSkippedParam;
property SkippedParamsCount: integer read GetSkippedParamsCount;
property Commands[Index: integer]: TClpCommand read GetCommand;
property CommandCount: integer read GetCommandCount;
property CommandPosition: integer read FCommandPosition;
property CommandValue: string read FCommandValue;
property StickedParams[Index: integer]: TClpStickedParam read GetStickedParam;
property StickedParamCount: integer read GetStickedParamCount;
property UnknownParams[Index: integer]: TClpUnknownParam read GetUnknownParam;
property UnknownParamCount: integer read GetUnknownParamCount;
// If AcceptAllNonOptions = True, all parameters that do not start with the "-" or "/" sign
// will be saved in FUnknownParams array.
property AcceptAllNonOptions: Boolean read FAcceptAllNonOptions write SetAcceptAllNonOptions;
end;
{$ENDREGION}
{$region ' --- INT helpers --- '}
function BoolToStr(const B: Boolean; ResultIfTrue: string = 'Yes'; ResultIfFalse: string = 'No'): string;
function SplitText(Text: string; MaxLen, Padding: integer; PadFirstLine: Boolean = False; PaddingChar: Char = ' '; ENDL: string = #13#10): string;
procedure SplitCmdLine(CmdLine: string; var argv: TArgv);
function ParamTypeToStr(const ParamType: TClpParamType): string;
function CLParamToStr(CLParam: TClpParam; PaddingStr: string = ' '): string;
function OptionRecToStr(Option: TClpOption; PaddingStr: string = ' '): string;
procedure ClearOptionRec(var Option: TClpOption);
function CommandToStr(Command: TClpCommand; PaddingStr: string = ' '): string;
function StickedParamToStr(StickedParam: TClpStickedParam; PaddingStr: string = ' '): string;
function StripQuotes(s: string; QChar: Char = '"'): string;
{$endregion helpers}
implementation
{$region ' copied from JPL units '}
function PadRight(Text: string; i: integer; AChar: Char = ' '): string;
var
x, y, k: integer;
s: string;
begin
s := '';
if Length(Text) < i then
begin
x := Length(Text);
y := i - x;
for k := 1 to y do s := s + AChar;
Text := Text + s;
end;
Result := Text;
end;
procedure SplitStrToArray(s: string; var Arr: {$IFDEF FPC}specialize{$ENDIF} TArray<string>; const EndLineStr: string = sLineBreak);
var
x: integer;
begin
SetLength(Arr, 0);
if s = '' then Exit;
x := Pos(EndLineStr, s);
while x > 0 do
begin
SetLength(Arr, Length(Arr) + 1);
Arr[Length(Arr) - 1] := Copy(s, 1, x - 1);
s := Copy(s, x + Length(EndLineStr), Length(s));
x := Pos(EndLineStr, s);
end;
if s <> '' then
begin
SetLength(Arr, Length(Arr) + 1);
Arr[Length(Arr) - 1] := s;
end;
end;
{$endregion copied from JPL units}
constructor TJPCmdLineParser.Create;
begin
inherited;
ResetAll;
end;
destructor TJPCmdLineParser.Destroy;
begin
ClearArrays;
inherited;
end;
procedure TJPCmdLineParser.ResetAll;
begin
ClearArrays;
FCommandPosition := -1;
FCommandValue := '';
FAllowDuplicates := False;
FUsageFormat := cufSimple;
FStopParsingSwitch := DefaultStopParsingSwitch;
FCommandLineParsingMode := cpmCustom;
FRunTimeParamsStr := GetRunTimeParams;
FillRunTimeParamsArray;
end;
procedure TJPCmdLineParser.ClearArrays;
begin
SetLength(FRunTimeParams, 0);
SetLength(FErrors, 0);
SetLength(CLParams, 0);
SetLength(FOptions, 0);
SetLength(FCommands, 0);
SetLength(FStickedParams, 0);
SetLength(FUnknownParams, 0);
SetLength(FOptionsExtraInfo, 0);
end;
{$region ' ------------------------------- PARSE -------------------------------- '}
procedure TJPCmdLineParser.Parse;
begin
Parse_1;
Parse_2;
end;
procedure TJPCmdLineParser.Parse_1; // faza wstępna
var
i, Position: integer;
RTParam: string;
CLP: TClpParam;
begin
SetLength(CLParams, 0);
for i := 0 to Length(FRunTimeParams) - 1 do
begin
RTParam := FRunTimeParams[i];
if RTParam = '' then Continue;
//Writeln(RTParam);
SetLength(CLParams, Length(CLParams) + 1);
Position := i + 1;
CLP.ParamStr := RTParam;
if FCommandPosition = Position then CLP.ParamType := cptCommand
else if StickedParamExists(Position) then CLP.ParamType := cptSticked
else CLP.ParamType := StrToParamType(RTParam);
CLP.Index := i;
CLP.Parsed := False;
CLP.OptionName := '';
CLP.OptionValue := '';
CLParams[Length(CLParams) - 1] := CLP;
//if CLP.ParamType = cptInvalid then LogError(RTParam, 'Invalid parameter', i);
end;
end;
{$hints off}
procedure TJPCmdLineParser.Parse_2; // faza 2-ga (końcowa)
function StripPrefix(ClpParam: TClpParam): string;
var
bLong, bShort: Boolean;
s: string;
begin
bLong := (ClpParam.ParamType = cptLong) or (ClpParam.ParamType = cptMixedLong);
bShort := (ClpParam.ParamType = cptShort) or (ClpParam.ParamType = cptMixedShort);
s := ClpParam.ParamStr;
if bLong then Delete(s, 1, Length(LongOptPrefix))
else if bShort then Delete(s, 1, 1)
else s := '';
Result := s;
end;
function IsOption(ClpParam: TClpParam): Boolean;
begin
Result := (ClpParam.ParamType = cptShort) or (ClpParam.ParamType = cptMixedShort) or
(ClpParam.ParamType = cptLong) or (ClpParam.ParamType = cptMixedLong);
end;
function IsMixedOption(ClpParam: TClpParam): Boolean;
begin
Result := (ClpParam.ParamType = cptMixedShort) or (ClpParam.ParamType = cptMixedLong);
end;
function IsNotMixedOption(ClpParam: TClpParam): Boolean;
begin
Result := (ClpParam.ParamType = cptShort) or (ClpParam.ParamType = cptLong);
end;
function IsShortOption(ClpParam: TClpParam): Boolean;
begin
Result := (ClpParam.ParamType = cptShort) or (ClpParam.ParamType = cptMixedShort);
end;
function IsLongOption(ClpParam: TClpParam): Boolean;
begin
Result := (ClpParam.ParamType = cptLong) or (ClpParam.ParamType = cptMixedLong);
end;
procedure GetNameVal(const MixedOpt: string; var sOptName, sOptValue: string);
var
x: integer;
begin
sOptName := '';
sOptValue := '';
x := Pos(EqChar, MixedOpt);
if x < 0 then Exit;
sOptName := Copy(MixedOpt, 1, x - 1);
sOptValue := Copy(MixedOpt, x + 1, Length(MixedOpt));
end;
function IsOptionAcceptsValue(Option: TClpOption): Boolean;
begin
Result := (Option.ValueType = cvtRequired) or (Option.ValueType = cvtOptional);
end;
function IsOptionValueRequired(Option: TClpOption): Boolean;
begin
Result := Option.ValueType = cvtRequired;
end;
var
i, IndNext, xOptInd, xInd: integer;
ParamRec, ParamRecNext: TClpParam;
Option: TClpOption;
sOpt, sVal: string;
bVal, bParamParsed: Boolean;
begin
// Writeln('--------- PARSE_2 ------------');
// Writeln('Params: ', Length(CLParams));
for i := 0 to Length(CLParams) - 1 do
begin
if i < Length(CLParams) - 1 then IndNext := i + 1 else IndNext := -1;
ParamRec := CLParams[i];
if ParamRec.Parsed then Continue;
bVal := False;
bParamParsed := True;
// -------------------------------------- COMMAND --------------------------------------
if ParamRec.ParamType = cptCommand then
begin
ParamRec.Parsed := True;
if CommandExists(ParamRec.ParamStr) then FCommandValue := ParamRec.ParamStr
else
begin
FCommandValue := '';
LogError(ParamRec.ParamStr, 'Unknown command', i);
end;
CLParams[i] := ParamRec;
Continue;
end
// ----------------------------------- STICKED PARAM ------------------------------------------
else if ParamRec.ParamType = cptSticked then
begin
ParamRec.Parsed := True;
xInd := GetStickedParamIndex(i + 1);
if xInd >= 0 then FStickedParams[xInd].ParamValue := ParamRec.ParamStr
else LogError(ParamRec.ParamStr, 'Sticked parameter not registered at position ' + IntToStr(i + 1), i);
CLParams[i] := ParamRec;
Continue;
end
// -------------------------- STOP PARSING MARKER ------------------------------------------------------
// Koniec analizy parametrów. Wszystkie pozostałe parametry trafiają do tablicy FSkippedParams
else if ParamRec.ParamType = cptStopMarker then
begin
CLParams[i].Parsed := True;
FillSkippedParamsArray(i + 1);
Break;
end
// ------------------------------------- OPTIONS -------------------------------------------------------
// bieżący parametr jest opcją (rozpoczyna się od '-' lub '--')
else if IsOption(ParamRec) then
begin
sOpt := StripPrefix(ParamRec);
sVal := '';
if IsMixedOption(ParamRec) then
begin
bVal := True;
GetNameVal(sOpt, sOpt, sVal);
end;
ParamRec.OptionName := sOpt;
if IsShortOption(ParamRec) then xOptInd := GetShortOptionIndex(ParamRec.OptionName)
else xOptInd := GetLongOptionIndex(ParamRec.OptionName);
if xOptInd >= 0 then
begin
Option := FOptions[xOptInd];
Option.Exists := True;
if IsOptionAcceptsValue(Option) then
if bVal then Option.Value := sVal
else
// sprawdzenie, czy następny parametr zawiera wartość (value) dla bieżącej opcji
if IndNext > 0 then
begin
ParamRecNext := CLParams[IndNext];
if (ParamRecNext.ParamType = cptNone) or (ParamRecNext.ParamType = cptString) then
begin
sVal := ParamRecNext.ParamStr;
Option.Value := sVal;
bVal := True;
CLParams[IndNext].Parsed := True;
end
else if IsOptionValueRequired(Option) then LogError(sOpt, 'Option requires value', i);
end
// brak następnego parametru, a opcja wymaga wartości - error
else if IsOptionValueRequired(Option) then LogError(sOpt, 'Option requires value', i);
if bVal then
if not IsOptionAcceptsValue(Option) then LogError(sOpt, 'Option does not accept value', i)
else Option.Value := sVal;
Option.Parsed := True;
FOptions[xOptInd] := Option;
bParamParsed := True;
end
else
begin
// brak takiej opcji (xOptInd < 0)
LogError(sOpt, 'Unregistered option', i);
bParamParsed := True;
end;
if bVal then ParamRec.OptionValue := sVal;
end // if IsOption
else
begin
if FAcceptAllNonOptions then
begin
bParamParsed := True;
LogUnknownParam(CLParams[i].ParamStr, i);
end
else bParamParsed := False;
end;
ParamRec.Parsed := bParamParsed;
CLParams[i] := ParamRec;
end; // for i
// sprawdzanie niesparsowanych parametrów
for i := 0 to Length(CLParams) - 1 do
if not CLParams[i].Parsed then
begin
LogError(CLParams[i].ParamStr, 'Unknown parameter', i);
LogUnknownParam(CLParams[i].ParamStr, i);
end;
end;
{$hints on}
{$endregion PARSE}
{$region ' ---------------------------- COMMANDS ----------------------- '}
function TJPCmdLineParser.GetCommand(Index: integer): TClpCommand;
begin
Result := FCommands[Index];
end;
function TJPCmdLineParser.GetCommandCount: integer;
begin
Result := Length(FCommands);
end;
function TJPCmdLineParser.CommandExists(CommandName: string): Boolean;
begin
Result := GetCommandIndex(CommandName) >= 0;
end;
function TJPCmdLineParser.GetCommandIndex(CommandName: string): integer;
var
i: integer;
ShortName, LongName: string;
begin
Result := -1;
if FIgnoreCase then CommandName := UpperCase(CommandName);
for i := 0 to Length(FCommands) - 1 do
begin
ShortName := FCommands[i].ShortName;
LongName := FCommands[i].LongName;
if FIgnoreCase then
begin
ShortName := UpperCase(ShortName);
LongName := UpperCase(LongName);
end;
if (CommandName = ShortName) or (CommandName = LongName) then
begin
Result := i;
Break;
end;
end;
end;
procedure TJPCmdLineParser.RegisterCommand(ShortName: string; LongName: string = ''; Position: integer = 1; Hidden: Boolean = False; Description: string = '');
var
xInd: integer;
begin
FCommandPosition := Position;
xInd := GetCommandIndex(ShortName);
if xInd < 0 then xInd := GetCommandIndex(LongName);
if xInd < 0 then
begin
SetLength(FCommands, Length(FCommands) + 1);
xInd := Length(FCommands) - 1;
end;
FCommands[xInd].ShortName := ShortName;
FCommands[xInd].LongName := LongName;
FCommands[xInd].UsageInfo := Description;
FCommands[xInd].Hidden := Hidden;
end;
procedure TJPCmdLineParser.AddCommand(ShortName: string; LongName: string = ''; Hidden: Boolean = False; Description: string = '');
begin
RegisterCommand(ShortName, LongName, FCommandPosition, Hidden, Description);
end;
function TJPCmdLineParser.CommandsAsString: string;
var
i: integer;
s: string;
begin
s := 'Commands: ' + IntToStr(Length(FCommands)) + ENDL;
s := s + 'Command position: ' + IntToStr(FCommandPosition) + ENDL;
for i := 0 to Length(FCommands) - 1 do
begin
s := s + 'Command ' + IntToStr(i) + ENDL;
s := s + CommandToStr(FCommands[i]) + ENDL;
end;
Result := s;
end;
{$endregion COMMANDS}
{$region ' ------------------------------- OPTIONS --------------------------------- '}
procedure TJPCmdLineParser.RegisterOption(ShortName: string; LongName: string = ''; ValueType: TClpValueType = cvtNone; IsOptionNeeded: Boolean = False;
Hidden: Boolean = False; UsageInfo: string = ''; UsageArgName: string = ''; UsageCategory: string = '');
var
xInd: integer;
OptionType: TClpOptionType;
bHasShortName, bHasLongName: Boolean;
begin
ShortName := Trim(ShortName);
LongName := Trim(LongName);
bHasShortName := ShortName <> '';
bHasLongName := LongName <> '';
if (not bHasShortName) and (not bHasLongName) then Exit; // the name (short or/and long) is required
xInd := -1;
if not FAllowDuplicates then
begin
if ShortName <> '' then xInd := GetShortOptionIndex(ShortName);
if (LongName <> '') and (xInd < 0) then xInd := GetLongOptionIndex(LongName);
end;
if xInd < 0 then
begin
SetLength(FOptions, Length(FOptions) + 1);
xInd := Length(FOptions) - 1;
ClearOptionRec(FOptions[xInd]);
end;
FOptions[xInd].LongName := LongName;
FOptions[xInd].ShortName := ShortName;
FOptions[xInd].ValueType := ValueType;
FOptions[xInd].IsOptionNeeded := IsOptionNeeded;
FOptions[xInd].Exists := False;
FOptions[xInd].Parsed := False;
FOptions[xInd].Hidden := Hidden;
FOptions[xInd].UsageInfo := UsageInfo;
FOptions[xInd].UsageArgName := UsageArgName;
FOptions[xInd].UsageCategory := UsageCategory;
if bHasShortName and bHasLongName then OptionType := cotBoth
else if bHasShortName then OptionType := cotShort
else OptionType := cotLong;
FOptions[xInd].OptionType := OptionType;
end;
procedure TJPCmdLineParser.RegisterShortOption(const OptionName: string; ValueType: TClpValueType = cvtNone; IsOptionNeeded: Boolean = False; Hidden: Boolean = False;
UsageInfo: string = ''; UsageArgName: string = ''; UsageCategory: string = '');
var
xInd: integer;
OptionType: TClpOptionType;
bNewRec: Boolean;
begin
xInd := -1;
bNewRec := False;
if not FAllowDuplicates then xInd := GetOptionIndex(OptionName);
if xInd < 0 then
begin
bNewRec := True;
SetLength(FOptions, Length(FOptions) + 1);
xInd := Length(FOptions) - 1;
ClearOptionRec(FOptions[xInd]);
FOptions[xInd].OptionType := cotShort;
end;
FOptions[xInd].ShortName := OptionName;
FOptions[xInd].ValueType := ValueType;
FOptions[xInd].IsOptionNeeded := IsOptionNeeded;
FOptions[xInd].Exists := False;
FOptions[xInd].Parsed := False;
FOptions[xInd].Hidden := Hidden;
FOptions[xInd].UsageInfo := UsageInfo;
FOptions[xInd].UsageArgName := UsageArgName;
FOptions[xInd].UsageCategory := UsageCategory;
if not bNewRec then
begin
OptionType := FOptions[xInd].OptionType;
if OptionType <> cotBoth then
begin
if OptionType = cotLong then OptionType := cotBoth else OptionType := cotShort;
FOptions[xInd].OptionType := OptionType;
end;
end;
end;
procedure TJPCmdLineParser.RegisterLongOption(const OptionName: string; ValueType: TClpValueType = cvtNone; IsOptionNeeded: Boolean = False; Hidden: Boolean = False;
UsageInfo: string = ''; UsageArgName: string = ''; UsageCategory: string = '');
var
xInd: integer;
OptionType: TClpOptionType;
bNewRec: Boolean;
begin
xInd := -1;
bNewRec := False;
if not FAllowDuplicates then xInd := GetOptionIndex(OptionName);
if xInd < 0 then
begin
bNewRec := True;
SetLength(FOptions, Length(FOptions) + 1);
xInd := Length(FOptions) - 1;
ClearOptionRec(FOptions[xInd]);
FOptions[xInd].OptionType := cotLong;
end;
FOptions[xInd].LongName := OptionName;
FOptions[xInd].ValueType := ValueType;
FOptions[xInd].IsOptionNeeded := IsOptionNeeded;
FOptions[xInd].Exists := False;
FOptions[xInd].Parsed := False;
FOptions[xInd].Hidden := Hidden;
FOptions[xInd].UsageInfo := UsageInfo;
FOptions[xInd].UsageArgName := UsageArgName;
FOptions[xInd].UsageCategory := UsageCategory;
if not bNewRec then
begin
OptionType := FOptions[xInd].OptionType;
if OptionType <> cotBoth then
begin
if OptionType = cotShort then OptionType := cotBoth else OptionType := cotLong;
FOptions[xInd].OptionType := OptionType;
end;
end;
end;
function TJPCmdLineParser.GetOptionValue(const OptionName: string; NoValueStr: string = ''): string;
var
xInd: integer;
begin
xInd := GetOptionIndex(OptionName);
if xInd >= 0 then Result := StripQuotes(FOptions[xInd].Value) else Result := NoValueStr;
end;
function TJPCmdLineParser.TryGetOptionValueAsBool(
const OptionName: string; out ResultValue: Boolean; TrueStr: string = '1|y|yes'; FalseStr: string = '0|n|no';
IgnoreBoolStrCase: Boolean = True): Boolean;
var
Arr: {$IFDEF DCC}TArray<string>; {$ELSE} array of string; {$ENDIF}
sVal: string;
i: integer;
begin
Result := False;
sVal := GetOptionValue(OptionName);
if sVal = '' then Exit;
if IgnoreBoolStrCase then
begin
sVal := UpperCase(sVal);
TrueStr := UpperCase(TrueStr);
FalseStr := UpperCase(FalseStr);
end;
SetLength(Arr, 0);
SplitStrToArray(TrueStr, Arr, '|');
for i := 0 to High(Arr) do
begin
if Arr[i] = sVal then
begin
Result := True;
ResultValue := True;
Exit;
end;
end;
SplitStrToArray(FalseStr, Arr, '|');
for i := 0 to High(Arr) do
begin
if Arr[i] = sVal then
begin
Result := True;
ResultValue := False;
Exit;
end;
end;
end;
function TJPCmdLineParser.GetShortOptionValue(OptionName: string; NoValueStr: string = ''): string;
var
xInd: integer;
begin
xInd := GetShortOptionIndex(OptionName);
if xInd >= 0 then Result := StripQuotes(FOptions[xInd].Value) else Result := NoValueStr;
end;
function TJPCmdLineParser.GetLongOptionValue(OptionName: string; NoValueStr: string = ''): string;
var
xInd: integer;
begin
xInd := GetLongOptionIndex(OptionName);
if xInd >= 0 then Result := StripQuotes(FOptions[xInd].Value) else Result := NoValueStr;
end;
function TJPCmdLineParser.GetOptionValues(OptionName: string): TStringDynArray;
var
i: integer;
Option: TClpOption;
ShortOptionName, LongOptionName, ParamOptionName: string;
b: Boolean;
Param: TClpParam;
begin
SetLength(Result, 0);
if OptionName = '' then Exit;
if FIgnoreCase then OptionName := UpperCase(OptionName);
// Wyszukuję krótką i pełną nazwę opcji OptionName
b := False;
for i := 0 to OptionCount - 1 do
begin
Option := Options[i];
if not Option.Parsed then Continue;
if FIgnoreCase then
begin
ShortOptionName := UpperCase(Option.ShortName);
LongOptionName := UpperCase(Option.LongName);
end
else
begin